# -*- coding: utf-8 mode: awk -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

function num(s) {
  if (s ~ /^[0-9]+$/) return int(s)
  else return s
}
function ord(s,    i) {
  s = substr(s, 1, 1)
  i = index(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", s)
  if (i != 0) i += 32 - 1
  return i
}
function hex(i,    s) {
  s = sprintf("%x", i)
  if (length(s) < 2) s = "0" s
  return s
}
function qhtml(s) {
  gsub(/&/, "\\&amp;", s)
  gsub(/"/, "\\&quot;", s)
  gsub(/>/, "\\&gt;", s)
  gsub(/</, "\\&lt;", s)
  return s
}
function unquote_html(s) {
  gsub(/&lt;/, "<", s)
  gsub(/&gt;/, ">", s)
  gsub(/&quot;/, "\"", s)
  gsub(/&amp;/, "\\&", s)
  return s
}
function qawk(s) {
  gsub(/\\/, "\\\\", s)
  gsub(/"/, "\\\"", s)
  gsub(/\n/, "\\n", s)
  return "\"" s "\""
}
function qval(s) {
  gsub(/'/, "'\\''", s)
  return "'" s "'"
}
function sqval(s) {
  return " " qval(s)
}
function qvals(             i, line) {
  line = ""
  for (i = 1; i <= NF; i++) {
    if (i > 1) line = line " "
    line = line qval($i)
  }
  return line
}
function sqvals() {
  return " " qvals()
}
function qarr(values, prefix,    i, count, line) {
  line = prefix
  count = array_len(values)
  for (i = 1; i <= count; i++) {
    if (i > 1 || line != "") line = line " "
    line = line qval(values[i])
  }
  return line
}
function qregexp(s) {
  gsub(/[[\\.^$*+?()|{]/, "\\\\&", s)
  return s
}
function qsubrepl(s) {
  gsub(/\\/, "\\\\", s)
  gsub(/&/, "\\\\&", s)
  return s
}
function qgrep(s) {
  gsub(/[[\\.^$*]/, "\\\\&", s)
  return s
}
function qegrep(s) {
  gsub(/[[\\.^$*+?()|{]/, "\\\\&", s)
  return s
}
function qsql(s, suffix) {
  gsub(/'/, "''", s)
  return "'" s "'" (suffix != ""? " " suffix: "")
}
function cqsql(s, suffix) {
  return "," qsql(s, suffix)
}
function unquote_mysqlcsv(s) {
  gsub(/\\n/, "\n", s)
  gsub(/\\t/, "\t", s)
  gsub(/\\0/, "\0", s)
  gsub(/\\\\/, "\\", s)
  return s
}
function sval(s) {
  if (s == "") return s
  else return " " s
}
function cval(s, suffix) {
  suffix = suffix != ""? " " suffix: ""
  if (s == "") return s
  else return "," s suffix
}

function printto(s, output) {
  if (output == "") {
    print s
  } else if (output ~ /^>>/) {
    sub(/^>>/, "", output)
    print s >>output
  } else if (output ~ /^>/) {
    sub(/^>/, "", output)
    print s >output
  } else if (output ~ /^\|&/) {
    sub(/^\|&/, "", output)
    print s |&output
  } else if (output ~ /^\|/) {
    sub(/^\|/, "", output)
    print s |output
  } else {
    print s >output
  }
}
function find_line(input, field, value,              orig, line) {
  orig = $0
  line = ""
  while ((getline <input) > 0) {
    if ($field == value) {
      line = $0
      break
    }
  }
  close(input)
  $0 = orig
  return line
}
function merge_line(input, field, key,               line) {
  line = find_line(input, field, $key)
  if (line != "") $0 = $0 FS line
}