add call of close() in sleep()

add call of close() in sleep()

# abs
function abs(x) { return (x < 0) ? -x : x }

# get sign of 'x'
function sign(x) { return x < 0 ? -1 : 1 }

# min
function min(a, b) { return (a < b) ? a : b }

# max
function max(a, b) { return (a > b) ? a : b }

# log base 10 of x
function log10(x) { log(x) / log(10) }

# log base 2 of x
function log2(x) { log(x) / log(2) }

# degree to radian
function d2r(deg) { return deg * atan2(0, -1) / 180 }

# radian to degree
function r2d(rad) { return rad * 180 / atan2(0, -1) }

# get value of pi
function pi() { return atan2(0, -1) }

# hypot 2 numbers
function hypot(x, y) { return sqrt(x ^ 2 + y ^ 2) }

# hypot 3 numbers
function hypot3(x, y, z) { return sqrt(x ^ 2 + y ^ 2 + z ^ 2) }

# calclation by bc(1)
function bc(expr,    cmd, tmp, anser) {
	cmd = "echo '" expr "' | bc -l"
	while (cmd | getline tmp > 0) {
		sub(/\\$/, "", tmp)
		anser = anser tmp
	}
	sub(/^\./, "0.", anser)
	close(cmd)
	return anser
}

# repeat text string
function rep(str, num,     res) { while (num--) res = res str; return res }

# sleep
function sleep(sec,    dummy) { "sleep " sec | getline dummy ; close("sleep " sec) }

# length of multi bytes character string
#function wlength(str) { gsub(/./, "a", str); return blength(str) }

# ascii code --> ascii character
function chr(n, force) {
	if (force) {
		if (n == 0x00) return "[NUL]"
		if (n == 0x01) return "[SOH]"
		if (n == 0x02) return "[STX]"
		if (n == 0x03) return "[ETX]"
		if (n == 0x04) return "[EOT]"
		if (n == 0x05) return "[ENQ]"
		if (n == 0x06) return "[ACK]"
		if (n == 0x0e) return "[SO]"
		if (n == 0x0f) return "[SI]"
		if (n == 0x10) return "[DLE]"
		if (n == 0x11) return "[DC1]"
		if (n == 0x12) return "[DC2]"
		if (n == 0x13) return "[DC3]"
		if (n == 0x14) return "[DC4]"
		if (n == 0x15) return "[NAK]"
		if (n == 0x16) return "[SYN]"
		if (n == 0x17) return "[ETB]"
		if (n == 0x18) return "[CAN]"
		if (n == 0x19) return "[EM]"
		if (n == 0x1a) return "[SUB]"
		if (n == 0x1b) return "[ESC]"
		if (n == 0x1c) return "[FS]"
		if (n == 0x1d) return "[GS]"
		if (n == 0x1e) return "[RS]"
		if (n == 0x1f) return "[US]"
		if (n == 0x7f) return "[DEL]"
	}
	return sprintf("%c", n)
}

# ascii character --> ascii code
function ord(str,    ch, res) {
	ch = substr(str, 1, 1)
	if (res = index(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", ch))
		return res + 0x1f
	else if (ch == "\a") return 0x07
	else if (ch == "\b") return 0x08
	else if (ch == "\t") return 0x09
	else if (ch == "\n") return 0x0a
	else if (ch == "\v") return 0x0b
	else if (ch == "\f") return 0x0c
	else if (ch == "\r") return 0x0d
	else  return -1
}

# abs
function abs(x) { return (x < 0) ? -x : x }

# get sign of 'x'
function sign(x) { return x < 0 ? -1 : 1 }

# min
function min(a, b) { return (a < b) ? a : b }

# max
function max(a, b) { return (a > b) ? a : b }

# log base 10 of x
function log10(x) { log(x) / log(10) }

# log base 2 of x
function log2(x) { log(x) / log(2) }

# degree to radian
function d2r(deg) { return deg * atan2(0, -1) / 180 }

# radian to degree
function r2d(rad) { return rad * 180 / atan2(0, -1) }

# get value of pi
function pi() { return atan2(0, -1) }

# hypot 2 numbers
function hypot(x, y) { return sqrt(x ^ 2 + y ^ 2) }

# hypot 3 numbers
function hypot3(x, y, z) { return sqrt(x ^ 2 + y ^ 2 + z ^ 2) }

# calclation by bc(1)
function bc(expr,    cmd, tmp, anser) {
	cmd = "echo '" expr "' | bc -l"
	while (cmd | getline tmp > 0) {
		sub(/\\$/, "", tmp)
		anser = anser tmp
	}
	sub(/^\./, "0.", anser)
	close(cmd)
	return anser
}

# repeat text string
function rep(str, num,     res) { while (num--) res = res str; return res }

# sleep
function sleep(sec,    dummy) { "sleep " sec | getline dummy }

# length of multi bytes character string
#function wlength(str) { gsub(/./, "a", str); return blength(str) }

# ascii code --> ascii character
function chr(n, force) {
	if (force) {
		if (n == 0x00) return "[NUL]"
		if (n == 0x01) return "[SOH]"
		if (n == 0x02) return "[STX]"
		if (n == 0x03) return "[ETX]"
		if (n == 0x04) return "[EOT]"
		if (n == 0x05) return "[ENQ]"
		if (n == 0x06) return "[ACK]"
		if (n == 0x0e) return "[SO]"
		if (n == 0x0f) return "[SI]"
		if (n == 0x10) return "[DLE]"
		if (n == 0x11) return "[DC1]"
		if (n == 0x12) return "[DC2]"
		if (n == 0x13) return "[DC3]"
		if (n == 0x14) return "[DC4]"
		if (n == 0x15) return "[NAK]"
		if (n == 0x16) return "[SYN]"
		if (n == 0x17) return "[ETB]"
		if (n == 0x18) return "[CAN]"
		if (n == 0x19) return "[EM]"
		if (n == 0x1a) return "[SUB]"
		if (n == 0x1b) return "[ESC]"
		if (n == 0x1c) return "[FS]"
		if (n == 0x1d) return "[GS]"
		if (n == 0x1e) return "[RS]"
		if (n == 0x1f) return "[US]"
		if (n == 0x7f) return "[DEL]"
	}
	return sprintf("%c", n)
}

# ascii character --> ascii code
function ord(str,    ch, res) {
	ch = substr(str, 1, 1)
	if (res = index(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", ch))
		return res + 0x1f
	else if (ch == "\a") return 0x07
	else if (ch == "\b") return 0x08
	else if (ch == "\t") return 0x09
	else if (ch == "\n") return 0x0a
	else if (ch == "\v") return 0x0b
	else if (ch == "\f") return 0x0c
	else if (ch == "\r") return 0x0d
	else  return -1
}


remove groff -D option (fix #40)

remove groff -D option (fix #40)

####################################################################
# Main.awk                                                         #
####################################################################

# Detect gawk version.
function initGawk(    group) {
    Gawk = "gawk"
    GawkVersion = PROCINFO["version"]

    split(PROCINFO["version"], group, ".")
    if (group[1] < 4) {
        e("[ERROR] Oops! Your gawk (version " GawkVersion ") appears to be too old.\nYou need at least gawk 4.0.0 to run this program.")
        exit 1
    }
}

# Pre-initialization (before option parsing).
function preInit() {
    initGawk()          #<< AnsiCode

    # Languages
    initBiDi()
    initLocale()
    initLocaleDisplay() #<< Locale, BiDi
    initUserLang()      #<< Locale

    RS = "\n"

    ExitCode = 0

    Option["debug"] = 0

    Option["verbose"] = 1
    Option["width"] = ENVIRON["COLUMNS"] ? ENVIRON["COLUMNS"] : 64

    Option["browser"] = ENVIRON["BROWSER"]

    Option["play"] = 0
    Option["player"] = ENVIRON["PLAYER"]

    Option["proxy"] = ENVIRON["HTTP_PROXY"] ? ENVIRON["HTTP_PROXY"] : ENVIRON["http_proxy"]

    Option["interactive"] = 0
    Option["no-rlwrap"] = 0
    Option["emacs"] = 0
    Option["prompt"] = ENVIRON["TRANS_PS"] ? ENVIRON["TRANS_PS"] : "%s>"
    Option["prompt-color"] = ENVIRON["TRANS_PS_COLOR"] ? ENVIRON["TRANS_PS_COLOR"] : "default"

    Option["input"] = ""
    Option["output"] = "/dev/stdout"

    Option["hl"] = ENVIRON["HOME_LANG"] ? ENVIRON["HOME_LANG"] : UserLang
    Option["sl"] = ENVIRON["SOURCE_LANG"] ? ENVIRON["SOURCE_LANG"] : "auto"
    Option["tl"][1] = ENVIRON["TARGET_LANG"] ? ENVIRON["TARGET_LANG"] : UserLang
}

# Post-initialization (after option parsing).
function postInit() {
    # Translate
    initHttpService()
}

# Main entry point.
BEGIN {
    preInit()

    pos = 0
    while (ARGV[++pos]) {
        # -, -no-op
        match(ARGV[pos], /^-(-?no-op)?$/)
        if (RSTART) continue

        # -V, -version
        match(ARGV[pos], /^--?(vers(i(on?)?)?|V)$/)
        if (RSTART) {
            print getVersion()
            print
            printf("%-22s%s\n", "gawk (GNU Awk)", PROCINFO["version"])
            printf("%s\n", FriBidi ? FriBidi : "fribidi (GNU FriBidi) [NOT INSTALLED]")
            printf("%-22s%s\n", "User Language", Locale[getCode(UserLang)]["name"] " (" show(Locale[getCode(UserLang)]["endonym"]) ")")
            exit
        }

        # -H, -h, -help
        match(ARGV[pos], /^--?(h(e(lp?)?)?|H)$/)
        if (RSTART) {
            print getHelp()
            exit
        }

        # -M, -m, -manual
        match(ARGV[pos], /^--?(m(a(n(u(al?)?)?)?)?|M)$/)
        if (RSTART) {
            if (ENVIRON["TRANS_MANPAGE"])
                system("echo -E \"${TRANS_MANPAGE}\" | " \
                       "groff -Wall -mtty-char -mandoc -Tutf8 -rLL=${COLUMNS}n -rLT=${COLUMNS}n | " \
                       (system("most 2>/dev/null") ?
                        "less -s -P\"\\ \\Manual page " Command "(1) line %lt (press h for help or q to quit)\"" :
                        "most -Cs"))
            else
                print getHelp()
            exit
        }

        # -r, -reference
        match(ARGV[pos], /^--?r(e(f(e(r(e(n(ce?)?)?)?)?)?)?)?$/)
        if (RSTART) {
            print getReference("endonym")
            exit
        }

        # -R, -reference-english
        match(ARGV[pos], /^--?(reference-(e(n(g(l(i(sh?)?)?)?)?)?)?|R)$/)
        if (RSTART) {
            print getReference("name")
            exit
        }

        # -d, -debug
        match(ARGV[pos], /^--?d(e(b(ug?)?)?)?$/)
        if (RSTART) {
            Option["debug"] = 1
            continue
        }

        # -v, -verbose
        match(ARGV[pos], /^--?v(e(r(b(o(se?)?)?)?)?)?$/)
        if (RSTART) {
            Option["verbose"] = 1 # default value
            continue
        }

        # -b, -brief
        match(ARGV[pos], /^--?b(r(i(ef?)?)?)?$/)
        if (RSTART) {
            Option["verbose"] = 0
            continue
        }

        # -no-ansi
        match(ARGV[pos], /^--?no-ansi/)
        if (RSTART) {
            Option["no-ansi"] = 1
            continue
        }

        # -w [num], -width [num]
        match(ARGV[pos], /^--?w(i(d(th?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["width"] = group[4] ?
                (group[5] ? group[5] : Option["width"]) :
                ARGV[++pos]
            continue
        }

        # -browser [program]
        match(ARGV[pos], /^--?browser(=(.*)?)?$/, group)
        if (RSTART) {
            Option["browser"] = group[1] ?
                (group[2] ? group[2] : Option["browser"]) :
                ARGV[++pos]
            continue
        }

        # -p, -play
        match(ARGV[pos], /^--?p(l(ay?)?)?$/)
        if (RSTART) {
            Option["play"] = 1
            continue
        }

        # -player [program]
        match(ARGV[pos], /^--?player(=(.*)?)?$/, group)
        if (RSTART) {
            Option["play"] = 1
            Option["player"] = group[1] ?
                (group[2] ? group[2] : Option["player"]) :
                ARGV[++pos]
            continue
        }

        # -x [proxy], -proxy [proxy]
        match(ARGV[pos], /^--?(proxy|x)(=(.*)?)?$/, group)
        if (RSTART) {
            Option["proxy"] = group[2] ?
                (group[3] ? group[3] : Option["proxy"]) :
                ARGV[++pos]
            continue
        }

        # -I, -interactive
        match(ARGV[pos], /^--?(int(e(r(a(c(t(i(ve?)?)?)?)?)?)?)?|I)$/)
        if (RSTART) {
            Option["interactive"] = 1
            continue
        }

        # -no-rlwrap
        match(ARGV[pos], /^--?no-rlwrap/)
        if (RSTART) {
            Option["no-rlwrap"] = 1
            continue
        }

        # -E, -emacs
        match(ARGV[pos], /^--?(emacs|E)$/)
        if (RSTART) {
            Option["emacs"] = 1
            continue
        }

        # -prompt [prompt_string]
        match(ARGV[pos], /^--?prompt(=(.*)?)?$/, group)
        if (RSTART) {
            Option["prompt"] = group[1] ?
                (group[2] ? group[2] : Option["prompt"]) :
                ARGV[++pos]
            continue
        }

        # -prompt-color [color_code]
        match(ARGV[pos], /^--?prompt-color(=(.*)?)?$/, group)
        if (RSTART) {
            Option["prompt-color"] = group[1] ?
                (group[2] ? group[2] : Option["prompt-color"]) :
                ARGV[++pos]
            continue
        }

        # -i [file], -input [file]
        match(ARGV[pos], /^--?i(n(p(ut?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["input"] = group[4] ?
                (group[5] ? group[5] : Option["input"]) :
                ARGV[++pos]
            continue
        }

        # -o [file], -output [file]
        match(ARGV[pos], /^--?o(u(t(p(ut?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["output"] = group[5] ?
                (group[6] ? group[6] : Option["output"]) :
                ARGV[++pos]
            continue
        }

        # -l [code], -lang [code]
        match(ARGV[pos], /^--?l(a(ng?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["hl"] = group[3] ?
                (group[4] ? group[4] : Option["hl"]) :
                ARGV[++pos]
            continue
        }

        # -s [code], -source [code]
        match(ARGV[pos], /^--?s(o(u(r(ce?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["sl"] = group[5] ?
                (group[6] ? group[6] : Option["sl"]) :
                ARGV[++pos]
            continue
        }

        # -t [codes], -target [codes]
        match(ARGV[pos], /^--?t(a(r(g(et?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            if (group[5]) {
                if (group[6]) split(group[6], Option["tl"], "+")
            } else
                split(ARGV[++pos], Option["tl"], "+")
            continue
        }

        # Shortcut format
        # '[code]:[code]+...' or '[code]=[code]+...'
        match(ARGV[pos], /^[{([]?([[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?)?(:|=)((@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?\+)*(@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?)?)[})\]]?$/, group)
        if (RSTART) {
            if (group[1]) Option["sl"] = group[1]
            if (group[4]) split(group[4], Option["tl"], "+")
            continue
        }

        # --
        match(ARGV[pos], /^--$/)
        if (RSTART) {
            ++pos # skip the end-of-options option
            break # no more option from here
        }

        break # no more option from here
    }

    # Option parsing finished
    postInit()

    if (Option["interactive"] && !Option["no-rlwrap"]) {
        # Interactive mode
        initRlwrap() # initialize Rlwrap

        if (Rlwrap && (ENVIRON["TRANS_PROGRAM"] || fileExists(EntryPoint))) {
            command = Rlwrap " " Gawk " " (ENVIRON["TRANS_PROGRAM"] ?
                                           "\"${TRANS_PROGRAM}\"" :
                                           "-f " EntryPoint) " -" \
                " -no-rlwrap" # be careful - never fork Rlwrap recursively!
            for (i = 1; i < length(ARGV); i++)
                if (ARGV[i])
                    command = command " " parameterize(ARGV[i])

            if (!system(command))
                exit # child process finished, exit
            else
                ; # skip
        } else
            ; # skip

    } else if (!Option["interactive"] && !Option["no-rlwrap"] && Option["emacs"]) {
        # Emacs interface
        Emacs = "emacs"

        if (ENVIRON["TRANS_PROGRAM"] || fileExists(EntryPoint)) {
            params = ""
            for (i = 1; i < length(ARGV); i++)
                if (ARGV[i])
                    params = params " " (parameterize(ARGV[i], "\""))
            if (ENVIRON["TRANS_PROGRAM"]) {
                el = "(progn (setq trans-program (getenv \"TRANS_PROGRAM\")) " \
                    "(setq explicit-shell-file-name \"" Gawk "\") " \
                    "(setq explicit-" Gawk "-args (cons trans-program '(\"-\" \"-I\" \"-no-rlwrap\"" params "))) " \
                    "(command-execute 'shell) (rename-buffer \"" Name "\"))"
            } else {
                el = "(progn (setq explicit-shell-file-name \"" Gawk "\") " \
                    "(setq explicit-" Gawk "-args '(\"-f\" \"" EntryPoint "\" \"--\" \"-I\" \"-no-rlwrap\"" params ")) " \
                    "(command-execute 'shell) (rename-buffer \"" Name "\"))"
            }
            command = Emacs " --eval " parameterize(el)

            if (!system(command))
                exit # child process finished, exit
            else
                Option["interactive"] = 1 # skip
        } else
            Option["interactive"] = 1 # skip
    }

    if (Option["play"]) {
        # Initialize audio player or speech synthesizer
        if (!Option["player"]) {
            initAudioPlayer()
            Option["player"] = AudioPlayer ? AudioPlayer : Option["player"]
            if (!Option["player"])
                initSpeechSynthesizer()
        }

        if (!Option["player"] && !SpeechSynthesizer) {
            w("[WARNING] No available audio player or speech synthesizer is found.")
            Option["play"] = 0
        }
    }

    if (Option["interactive"]) {
        print AnsiCode["bold"] AnsiCode[tolower(Option["prompt-color"])] getVersion() AnsiCode[0] > "/dev/stderr"
        print AnsiCode[tolower(Option["prompt-color"])] "(:q to quit)" AnsiCode[0] > "/dev/stderr"
    }

    # Initialize browser
    if (!Option["browser"]) {
        "xdg-mime query default text/html 2>/dev/null" |& getline Option["browser"]
        match(Option["browser"], "(.*).desktop$", group)
        Option["browser"] = group[1]
    }

    # Disable ANSI SGR (Select Graphic Rendition) codes if required
    if (Option["no-ansi"])
        delete AnsiCode

    if (pos < ARGC) {
        # More parameters

        # Translate the remaining parameters
        for (i = pos; i < ARGC; i++) {
            # Verbose mode: separator between sources
            if (Option["verbose"] && i > pos)
                print replicate("═", Option["width"])

            translate(ARGV[i], 1) # inline mode
        }

        # If input not specified, we're done
    } else {
        # No more parameter besides options

        # If input not specified, use stdin
        if (!Option["input"]) Option["input"] = "/dev/stdin"
    }

    # If input specified, start translating
    if (Option["input"])
        translateMain()

    exit ExitCode
}

####################################################################
# Main.awk                                                         #
####################################################################

# Detect gawk version.
function initGawk(    group) {
    Gawk = "gawk"
    GawkVersion = PROCINFO["version"]

    split(PROCINFO["version"], group, ".")
    if (group[1] < 4) {
        e("[ERROR] Oops! Your gawk (version " GawkVersion ") appears to be too old.\nYou need at least gawk 4.0.0 to run this program.")
        exit 1
    }
}

# Pre-initialization (before option parsing).
function preInit() {
    initGawk()          #<< AnsiCode

    # Languages
    initBiDi()
    initLocale()
    initLocaleDisplay() #<< Locale, BiDi
    initUserLang()      #<< Locale

    RS = "\n"

    ExitCode = 0

    Option["debug"] = 0

    Option["verbose"] = 1
    Option["width"] = ENVIRON["COLUMNS"] ? ENVIRON["COLUMNS"] : 64

    Option["browser"] = ENVIRON["BROWSER"]

    Option["play"] = 0
    Option["player"] = ENVIRON["PLAYER"]

    Option["proxy"] = ENVIRON["HTTP_PROXY"] ? ENVIRON["HTTP_PROXY"] : ENVIRON["http_proxy"]

    Option["interactive"] = 0
    Option["no-rlwrap"] = 0
    Option["emacs"] = 0
    Option["prompt"] = ENVIRON["TRANS_PS"] ? ENVIRON["TRANS_PS"] : "%s>"
    Option["prompt-color"] = ENVIRON["TRANS_PS_COLOR"] ? ENVIRON["TRANS_PS_COLOR"] : "default"

    Option["input"] = ""
    Option["output"] = "/dev/stdout"

    Option["hl"] = ENVIRON["HOME_LANG"] ? ENVIRON["HOME_LANG"] : UserLang
    Option["sl"] = ENVIRON["SOURCE_LANG"] ? ENVIRON["SOURCE_LANG"] : "auto"
    Option["tl"][1] = ENVIRON["TARGET_LANG"] ? ENVIRON["TARGET_LANG"] : UserLang
}

# Post-initialization (after option parsing).
function postInit() {
    # Translate
    initHttpService()
}

# Main entry point.
BEGIN {
    preInit()

    pos = 0
    while (ARGV[++pos]) {
        # -, -no-op
        match(ARGV[pos], /^-(-?no-op)?$/)
        if (RSTART) continue

        # -V, -version
        match(ARGV[pos], /^--?(vers(i(on?)?)?|V)$/)
        if (RSTART) {
            print getVersion()
            print
            printf("%-22s%s\n", "gawk (GNU Awk)", PROCINFO["version"])
            printf("%s\n", FriBidi ? FriBidi : "fribidi (GNU FriBidi) [NOT INSTALLED]")
            printf("%-22s%s\n", "User Language", Locale[getCode(UserLang)]["name"] " (" show(Locale[getCode(UserLang)]["endonym"]) ")")
            exit
        }

        # -H, -h, -help
        match(ARGV[pos], /^--?(h(e(lp?)?)?|H)$/)
        if (RSTART) {
            print getHelp()
            exit
        }

        # -M, -m, -manual
        match(ARGV[pos], /^--?(m(a(n(u(al?)?)?)?)?|M)$/)
        if (RSTART) {
            if (ENVIRON["TRANS_MANPAGE"])
                system("echo -E \"${TRANS_MANPAGE}\" | " \
                       "groff -Wall -mtty-char -mandoc -Tutf8 -Dutf8 -rLL=${COLUMNS}n -rLT=${COLUMNS}n | " \
                       (system("most 2>/dev/null") ?
                        "less -s -P\"\\ \\Manual page " Command "(1) line %lt (press h for help or q to quit)\"" :
                        "most -Cs"))
            else
                print getHelp()
            exit
        }

        # -r, -reference
        match(ARGV[pos], /^--?r(e(f(e(r(e(n(ce?)?)?)?)?)?)?)?$/)
        if (RSTART) {
            print getReference("endonym")
            exit
        }

        # -R, -reference-english
        match(ARGV[pos], /^--?(reference-(e(n(g(l(i(sh?)?)?)?)?)?)?|R)$/)
        if (RSTART) {
            print getReference("name")
            exit
        }

        # -d, -debug
        match(ARGV[pos], /^--?d(e(b(ug?)?)?)?$/)
        if (RSTART) {
            Option["debug"] = 1
            continue
        }

        # -v, -verbose
        match(ARGV[pos], /^--?v(e(r(b(o(se?)?)?)?)?)?$/)
        if (RSTART) {
            Option["verbose"] = 1 # default value
            continue
        }

        # -b, -brief
        match(ARGV[pos], /^--?b(r(i(ef?)?)?)?$/)
        if (RSTART) {
            Option["verbose"] = 0
            continue
        }

        # -no-ansi
        match(ARGV[pos], /^--?no-ansi/)
        if (RSTART) {
            Option["no-ansi"] = 1
            continue
        }

        # -w [num], -width [num]
        match(ARGV[pos], /^--?w(i(d(th?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["width"] = group[4] ?
                (group[5] ? group[5] : Option["width"]) :
                ARGV[++pos]
            continue
        }

        # -browser [program]
        match(ARGV[pos], /^--?browser(=(.*)?)?$/, group)
        if (RSTART) {
            Option["browser"] = group[1] ?
                (group[2] ? group[2] : Option["browser"]) :
                ARGV[++pos]
            continue
        }

        # -p, -play
        match(ARGV[pos], /^--?p(l(ay?)?)?$/)
        if (RSTART) {
            Option["play"] = 1
            continue
        }

        # -player [program]
        match(ARGV[pos], /^--?player(=(.*)?)?$/, group)
        if (RSTART) {
            Option["play"] = 1
            Option["player"] = group[1] ?
                (group[2] ? group[2] : Option["player"]) :
                ARGV[++pos]
            continue
        }

        # -x [proxy], -proxy [proxy]
        match(ARGV[pos], /^--?(proxy|x)(=(.*)?)?$/, group)
        if (RSTART) {
            Option["proxy"] = group[2] ?
                (group[3] ? group[3] : Option["proxy"]) :
                ARGV[++pos]
            continue
        }

        # -I, -interactive
        match(ARGV[pos], /^--?(int(e(r(a(c(t(i(ve?)?)?)?)?)?)?)?|I)$/)
        if (RSTART) {
            Option["interactive"] = 1
            continue
        }

        # -no-rlwrap
        match(ARGV[pos], /^--?no-rlwrap/)
        if (RSTART) {
            Option["no-rlwrap"] = 1
            continue
        }

        # -E, -emacs
        match(ARGV[pos], /^--?(emacs|E)$/)
        if (RSTART) {
            Option["emacs"] = 1
            continue
        }

        # -prompt [prompt_string]
        match(ARGV[pos], /^--?prompt(=(.*)?)?$/, group)
        if (RSTART) {
            Option["prompt"] = group[1] ?
                (group[2] ? group[2] : Option["prompt"]) :
                ARGV[++pos]
            continue
        }

        # -prompt-color [color_code]
        match(ARGV[pos], /^--?prompt-color(=(.*)?)?$/, group)
        if (RSTART) {
            Option["prompt-color"] = group[1] ?
                (group[2] ? group[2] : Option["prompt-color"]) :
                ARGV[++pos]
            continue
        }

        # -i [file], -input [file]
        match(ARGV[pos], /^--?i(n(p(ut?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["input"] = group[4] ?
                (group[5] ? group[5] : Option["input"]) :
                ARGV[++pos]
            continue
        }

        # -o [file], -output [file]
        match(ARGV[pos], /^--?o(u(t(p(ut?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["output"] = group[5] ?
                (group[6] ? group[6] : Option["output"]) :
                ARGV[++pos]
            continue
        }

        # -l [code], -lang [code]
        match(ARGV[pos], /^--?l(a(ng?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["hl"] = group[3] ?
                (group[4] ? group[4] : Option["hl"]) :
                ARGV[++pos]
            continue
        }

        # -s [code], -source [code]
        match(ARGV[pos], /^--?s(o(u(r(ce?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            Option["sl"] = group[5] ?
                (group[6] ? group[6] : Option["sl"]) :
                ARGV[++pos]
            continue
        }

        # -t [codes], -target [codes]
        match(ARGV[pos], /^--?t(a(r(g(et?)?)?)?)?(=(.*)?)?$/, group)
        if (RSTART) {
            if (group[5]) {
                if (group[6]) split(group[6], Option["tl"], "+")
            } else
                split(ARGV[++pos], Option["tl"], "+")
            continue
        }

        # Shortcut format
        # '[code]:[code]+...' or '[code]=[code]+...'
        match(ARGV[pos], /^[{([]?([[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?)?(:|=)((@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?\+)*(@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]])?)?)[})\]]?$/, group)
        if (RSTART) {
            if (group[1]) Option["sl"] = group[1]
            if (group[4]) split(group[4], Option["tl"], "+")
            continue
        }

        # --
        match(ARGV[pos], /^--$/)
        if (RSTART) {
            ++pos # skip the end-of-options option
            break # no more option from here
        }

        break # no more option from here
    }

    # Option parsing finished
    postInit()

    if (Option["interactive"] && !Option["no-rlwrap"]) {
        # Interactive mode
        initRlwrap() # initialize Rlwrap

        if (Rlwrap && (ENVIRON["TRANS_PROGRAM"] || fileExists(EntryPoint))) {
            command = Rlwrap " " Gawk " " (ENVIRON["TRANS_PROGRAM"] ?
                                           "\"${TRANS_PROGRAM}\"" :
                                           "-f " EntryPoint) " -" \
                " -no-rlwrap" # be careful - never fork Rlwrap recursively!
            for (i = 1; i < length(ARGV); i++)
                if (ARGV[i])
                    command = command " " parameterize(ARGV[i])

            if (!system(command))
                exit # child process finished, exit
            else
                ; # skip
        } else
            ; # skip

    } else if (!Option["interactive"] && !Option["no-rlwrap"] && Option["emacs"]) {
        # Emacs interface
        Emacs = "emacs"

        if (ENVIRON["TRANS_PROGRAM"] || fileExists(EntryPoint)) {
            params = ""
            for (i = 1; i < length(ARGV); i++)
                if (ARGV[i])
                    params = params " " (parameterize(ARGV[i], "\""))
            if (ENVIRON["TRANS_PROGRAM"]) {
                el = "(progn (setq trans-program (getenv \"TRANS_PROGRAM\")) " \
                    "(setq explicit-shell-file-name \"" Gawk "\") " \
                    "(setq explicit-" Gawk "-args (cons trans-program '(\"-\" \"-I\" \"-no-rlwrap\"" params "))) " \
                    "(command-execute 'shell) (rename-buffer \"" Name "\"))"
            } else {
                el = "(progn (setq explicit-shell-file-name \"" Gawk "\") " \
                    "(setq explicit-" Gawk "-args '(\"-f\" \"" EntryPoint "\" \"--\" \"-I\" \"-no-rlwrap\"" params ")) " \
                    "(command-execute 'shell) (rename-buffer \"" Name "\"))"
            }
            command = Emacs " --eval " parameterize(el)

            if (!system(command))
                exit # child process finished, exit
            else
                Option["interactive"] = 1 # skip
        } else
            Option["interactive"] = 1 # skip
    }

    if (Option["play"]) {
        # Initialize audio player or speech synthesizer
        if (!Option["player"]) {
            initAudioPlayer()
            Option["player"] = AudioPlayer ? AudioPlayer : Option["player"]
            if (!Option["player"])
                initSpeechSynthesizer()
        }

        if (!Option["player"] && !SpeechSynthesizer) {
            w("[WARNING] No available audio player or speech synthesizer is found.")
            Option["play"] = 0
        }
    }

    if (Option["interactive"]) {
        print AnsiCode["bold"] AnsiCode[tolower(Option["prompt-color"])] getVersion() AnsiCode[0] > "/dev/stderr"
        print AnsiCode[tolower(Option["prompt-color"])] "(:q to quit)" AnsiCode[0] > "/dev/stderr"
    }

    # Initialize browser
    if (!Option["browser"]) {
        "xdg-mime query default text/html 2>/dev/null" |& getline Option["browser"]
        match(Option["browser"], "(.*).desktop$", group)
        Option["browser"] = group[1]
    }

    # Disable ANSI SGR (Select Graphic Rendition) codes if required
    if (Option["no-ansi"])
        delete AnsiCode

    if (pos < ARGC) {
        # More parameters

        # Translate the remaining parameters
        for (i = pos; i < ARGC; i++) {
            # Verbose mode: separator between sources
            if (Option["verbose"] && i > pos)
                print replicate("═", Option["width"])

            translate(ARGV[i], 1) # inline mode
        }

        # If input not specified, we're done
    } else {
        # No more parameter besides options

        # If input not specified, use stdin
        if (!Option["input"]) Option["input"] = "/dev/stdin"
    }

    # If input specified, start translating
    if (Option["input"])
        translateMain()

    exit ExitCode
}


Fixed comments at beginning of program

Fixed comments at beginning of program

#
# generate_all
#
# - input two seperate data files and output transliterated characters
#
# file1 format is "hexnum chars" where hexnum = hex entry index, char = "on" led segmemts
# file2 consists a index and a text string
# file3 is a template file for the output of the text strings after translation
#  into an LED segment pattern.
#  This output is then included in the source stream for complilation
#
# file1 converts raw led segment letters to a translated hex number
# which is stored in an array with the characters hex number being the index
#
# file1:
#   0x30    abcdef
#   0x31    bc
#   0x32    abdeg
#   ... repeats for 127 chars total
#
# file2:
#
#    <41>  SEt,_
#    <42>  bEE,P
#
# Where <41> is the pattern used for matching in the output template file.
#
# file3:
#
#  #if DIGIT_3_FLIP
#      <4F1>
#      <4F2>
#
# This template has <4F1> replaced with the hex code for string <41> with the character rotated
# (flipped) 180 degrees. In other locations, you will see the index markers:
#
#  #else
#      <4N1>
#      <4N2>
#
# Where the "N" character in the marker means do not flip or rotate the character pattern
# This is only needed in the third digit position due to lazy hardware engineers.
#
# The output from this GAW program thus becomes:
#
#  #if DIGIT_3_FLIP
#      0x92,0x86,0xB8,0xFF,       // SEt_
#      0x83,0x86,0xB0,0x8C,       // bEEP
#
# and lower in the listing:
#
#  #else
#      0x92,0x86,0x87,0xFF,       // SEt
#      0x83,0x86,0x86,0x8C,       // bEEP
#
# Note the difference in the value of the third hex number, this is
# the "flipped" LED segment pattern
#
BEGIN {

	while (getline <"segTable/segment_list.txt" > 0){

    if (match($0,/^#/)) # skip comment line
      continue

    if ( $2 == ";" ) {
      ledValueNorm[ hexToString($1 "") ] = "0xFF"
      ledValueFlip[ hexToString($1 "") ] = "0xFF"
    }
    if ( $2 ~ /[a-g]+/ ) {
      val  = 0;
      for ( i = 1; i <= length($2); i++) {
          c = substr($2,i,1)
          if ( c == "a" ) val += 1
          if ( c == "b" ) val += 2
          if ( c == "c" ) val += 4
          if ( c == "d" ) val += 8
          if ( c == "e" ) val += 16
          if ( c == "f" ) val += 32
          if ( c == "g" ) val += 64
          if ( c == "h" ) val += 128
      }
      s = ""
      if ( val >= 128 ){ s = s "1"; val -= 128 } else { s = s "0"}
      if ( val >=  64 ){ s = s "1"; val -=  64 } else { s = s "0"}
      if ( val >=  32 ){ s = s "1"; val -=  32 } else { s = s "0"}
      if ( val >=  16 ){ s = s "1"; val -=  16 } else { s = s "0"}
      if ( val >=   8 ){ s = s "1"; val -=   8 } else { s = s "0"}
      if ( val >=   4 ){ s = s "1"; val -=   4 } else { s = s "0"}
      if ( val >=   2 ){ s = s "1"; val -=   2 } else { s = s "0"}
      if ( val >=   1 ){ s = s "1"; val -=   1 } else { s = s "0"}

    	b01 = substr(s,8,1)         # get each bit in order
    	b02 = substr(s,7,1)
    	b04 = substr(s,6,1)
    	b08 = substr(s,5,1)
    	b10 = substr(s,4,1)
    	b20 = substr(s,3,1)
    	b40 = substr(s,2,1)
    	b80 = substr(s,1,1)
    	#
    	# the bit reorder is here:
      #
      # inverted logic here!
      #
      val = 0
      if ( b80 == "0" ){ val += 128 }
      if ( b40 == "0" ){ val +=  64 }
      if ( b20 == "0" ){ val +=  32 }
      if ( b10 == "0" ){ val +=  16 }
      if ( b08 == "0" ){ val +=   8 }
      if ( b04 == "0" ){ val +=   4 }
      if ( b02 == "0" ){ val +=   2 }
      if ( b01 == "0" ){ val +=   1 }
      ledValueNorm[ hexToString($1 "") ] = sprintf("0x%02X",val)
      #
      # inverted logic here!
      #
      val = 0
      if ( b80 == "0" ){ val += 128 }
      if ( b40 == "0" ){ val +=  64 }
      if ( b04 == "0" ){ val +=  32 }
      if ( b02 == "0" ){ val +=  16 }
      if ( b01 == "0" ){ val +=   8 }
      if ( b20 == "0" ){ val +=   4 }
      if ( b10 == "0" ){ val +=   2 }
      if ( b08 == "0" ){ val +=   1 }
      ledValueFlip[ hexToString($1 "") ] = sprintf("0x%02X",val)
      }
  } # end of file 1

	while (getline < "segTable/text_strings.txt" > 0) {

    if (match($0,/^#/)) # skip comment line
      continue

      if (NF == 2) {
        if ( match($1,/[0-9]+/) )
          text_string[substr($1,RSTART,RLENGTH)] = $2
    }
  } # end file text_strings.txt

  printf("// ----------------------------------------------------------------\n")
  printf("// ----------------------------------------------------------------\n")
  printf("// ------    This file was generated by the make process     ------\n")
  printf("// ------ Do not edit this file as your changes will be lost ------\n")
  printf("// ------     with the next invocation of \"make led\"         ------\n")
  printf("// ----------------------------------------------------------------\n")
  printf("// ----------------------------------------------------------------\n")

	while (getline < "segTable/codeTemplate.txt" > 0) {

    if (match($1,/<[234][NF][0-9]+>/)) {
      sIndex = $1
      gsub(/[<>]/,"",sIndex)
      gsub(/[NF]/,"",sIndex)
      orientation = substr($1,3,1)
      gen_string = text_string[sIndex]

      # handle decimal point in text string
      decimal_loc = index(gen_string,".")
      if ( decimal_loc ){
        # remove actual decimal from text
        decimal_loc--
        gsub(/\./,"",gen_string)
      }

      # handle flip character escaped code
      flip_loc = index(gen_string,",")
      if ( flip_loc ){
        # remove escape code from text
        flip_loc--
        gsub(/,/,"",gen_string)
      }

      rc = "" # start with empty string
      # now generate each character
      for (i =1; i <= length(gen_string); i++) {
        ci = substr(gen_string,i,1)

        if ( orientation == "F" && i == flip_loc )
          tc = ledValueFlip[ci]
         else
          tc = ledValueNorm[ci]

        # handle decimal point if at that character
        if (i == decimal_loc){
          tc = add_decimal(tc)
        }

      # now concatenate everything into one string each pass through
      rc = rc tc ","
      } #end for of each character

      # now replace placeholder with text
      gsub(/<[0-9][NF][0-9]+>/,rc)
      } # end if $1 matches pattern <2 3 or 4>

    if (match($1,/<[1][NF][0-9]+>/)) {
      # here when we have single "0-9" substitution
      sIndex = substr($1,4,1)
      orientation = substr($1,3,1)
      gen_string = text_string[sIndex]
      if ( orientation == "N" )
        rc = ledValueNorm[sIndex] ","
      else
        rc = ledValueFlip[sIndex] ","
      gsub(/<[0-9][NF][0-9]+>/,rc)
    }

    printf($0 "\n") # the the source, possibly modified
  } # end file text_strings.txt

} # end of pgm

#
# -------------------------------------------------------------------
#
function add_decimal(hexchars)
{
    # hexchars = "0x4F"
    msb = substr(hexchars,3,1)
    lsb = substr(hexchars,4,1)
    val = 0
    if ( msb == "F" ){ val += 240 }
    if ( msb == "E" ){ val += 224 }
    if ( msb == "D" ){ val += 208 }
    if ( msb == "C" ){ val += 192 }
    if ( msb == "B" ){ val += 176 }
    if ( msb == "A" ){ val += 160 }
    if ( msb == "9" ){ val += 144 }
    if ( msb == "8" ){ val += 128 }
    if ( msb == "7" ){ val += 112 }
    if ( msb == "6" ){ val +=  96 }
    if ( msb == "5" ){ val +=  80 }
    if ( msb == "4" ){ val +=  64 }
    if ( msb == "3" ){ val +=  48 }
    if ( msb == "2" ){ val +=  32 }
    if ( msb == "1" ){ val +=  16 }
    if ( lsb == "F" ){ val +=  15 }
    if ( lsb == "E" ){ val +=  14 }
    if ( lsb == "D" ){ val +=  13 }
    if ( lsb == "C" ){ val +=  12 }
    if ( lsb == "B" ){ val +=  11 }
    if ( lsb == "A" ){ val +=  10 }
    if ( lsb == "9" ){ val +=   9 }
    if ( lsb == "8" ){ val +=   8 }
    if ( lsb == "7" ){ val +=   7 }
    if ( lsb == "6" ){ val +=   6 }
    if ( lsb == "5" ){ val +=   5 }
    if ( lsb == "4" ){ val +=   4 }
    if ( lsb == "3" ){ val +=   3 }
    if ( lsb == "2" ){ val +=   2 }
    if ( lsb == "1" ){ val +=   1 }
    if (val >= 128) val -= 128
    return sprintf("0x%02X",val)
}
#
# -------------------------------------------------------------------
#
function hexToString(hexchars)
{
    # hexchars = "0x4F"
    msb = substr(hexchars,3,1)
    lsb = substr(hexchars,4,1)
    val = 0
    if ( msb == "F" ){ val += 240 }
    if ( msb == "E" ){ val += 224 }
    if ( msb == "D" ){ val += 208 }
    if ( msb == "C" ){ val += 192 }
    if ( msb == "B" ){ val += 176 }
    if ( msb == "A" ){ val += 160 }
    if ( msb == "9" ){ val += 144 }
    if ( msb == "8" ){ val += 128 }
    if ( msb == "7" ){ val += 112 }
    if ( msb == "6" ){ val +=  96 }
    if ( msb == "5" ){ val +=  80 }
    if ( msb == "4" ){ val +=  64 }
    if ( msb == "3" ){ val +=  48 }
    if ( msb == "2" ){ val +=  32 }
    if ( msb == "1" ){ val +=  16 }
    if ( lsb == "F" ){ val +=  15 }
    if ( lsb == "E" ){ val +=  14 }
    if ( lsb == "D" ){ val +=  13 }
    if ( lsb == "C" ){ val +=  12 }
    if ( lsb == "B" ){ val +=  11 }
    if ( lsb == "A" ){ val +=  10 }
    if ( lsb == "9" ){ val +=   9 }
    if ( lsb == "8" ){ val +=   8 }
    if ( lsb == "7" ){ val +=   7 }
    if ( lsb == "6" ){ val +=   6 }
    if ( lsb == "5" ){ val +=   5 }
    if ( lsb == "4" ){ val +=   4 }
    if ( lsb == "3" ){ val +=   3 }
    if ( lsb == "2" ){ val +=   2 }
    if ( lsb == "1" ){ val +=   1 }
    return sprintf("%c",val)
}

#
# generate_all
#
# - input two seperate data files and output transliterated characters
#
# file1 format is "hexnum chars" where hexnum = hex entry index, char = "on" led segmemts
# file2 consists a stream of "abcdefgh" char lists
#
# file1 converts raw led segment letters to a translated hex number
# which is stored in an array with the characters hex number being the index
#
# file1:
#   0x30    abcdef
#   0x31    bc
#   0x32    abdeg
#   ... repeats for 127 chars total
#
# file2:
#   CL
#   AL
#   BEEP
#
# output:
#   CL      0x31,0x4A   // CL
#   AL      0x37,0x48   // AL
#   BEEP    0x6A,0x88,0x9F,0x4C // BEEP
#
BEGIN {

	while (getline <"segTable/segment_list.txt" > 0){

    if (match($0,/^#/)) # skip comment line
      continue

    if ( $2 == ";" ) {
      ledValueNorm[ hexToString($1 "") ] = "0xFF"
      ledValueFlip[ hexToString($1 "") ] = "0xFF"
    }
    if ( $2 ~ /[a-g]+/ ) {
      val  = 0;
      for ( i = 1; i <= length($2); i++) {
          c = substr($2,i,1)
          if ( c == "a" ) val += 1
          if ( c == "b" ) val += 2
          if ( c == "c" ) val += 4
          if ( c == "d" ) val += 8
          if ( c == "e" ) val += 16
          if ( c == "f" ) val += 32
          if ( c == "g" ) val += 64
          if ( c == "h" ) val += 128
      }
      s = ""
      if ( val >= 128 ){ s = s "1"; val -= 128 } else { s = s "0"}
      if ( val >=  64 ){ s = s "1"; val -=  64 } else { s = s "0"}
      if ( val >=  32 ){ s = s "1"; val -=  32 } else { s = s "0"}
      if ( val >=  16 ){ s = s "1"; val -=  16 } else { s = s "0"}
      if ( val >=   8 ){ s = s "1"; val -=   8 } else { s = s "0"}
      if ( val >=   4 ){ s = s "1"; val -=   4 } else { s = s "0"}
      if ( val >=   2 ){ s = s "1"; val -=   2 } else { s = s "0"}
      if ( val >=   1 ){ s = s "1"; val -=   1 } else { s = s "0"}

    	b01 = substr(s,8,1)         # get each bit in order
    	b02 = substr(s,7,1)
    	b04 = substr(s,6,1)
    	b08 = substr(s,5,1)
    	b10 = substr(s,4,1)
    	b20 = substr(s,3,1)
    	b40 = substr(s,2,1)
    	b80 = substr(s,1,1)
    	#
    	# the bit reorder is here:
      #
      # inverted logic here!
      #
      val = 0
      if ( b80 == "0" ){ val += 128 }
      if ( b40 == "0" ){ val +=  64 }
      if ( b20 == "0" ){ val +=  32 }
      if ( b10 == "0" ){ val +=  16 }
      if ( b08 == "0" ){ val +=   8 }
      if ( b04 == "0" ){ val +=   4 }
      if ( b02 == "0" ){ val +=   2 }
      if ( b01 == "0" ){ val +=   1 }
      ledValueNorm[ hexToString($1 "") ] = sprintf("0x%02X",val)
      #
      # inverted logic here!
      #
      val = 0
      if ( b80 == "0" ){ val += 128 }
      if ( b40 == "0" ){ val +=  64 }
      if ( b04 == "0" ){ val +=  32 }
      if ( b02 == "0" ){ val +=  16 }
      if ( b01 == "0" ){ val +=   8 }
      if ( b20 == "0" ){ val +=   4 }
      if ( b10 == "0" ){ val +=   2 }
      if ( b08 == "0" ){ val +=   1 }
      ledValueFlip[ hexToString($1 "") ] = sprintf("0x%02X",val)
      }
  } # end of file 1

	while (getline < "segTable/text_strings.txt" > 0) {

    if (match($0,/^#/)) # skip comment line
      continue

      if (NF == 2) {
        if ( match($1,/[0-9]+/) )
          text_string[substr($1,RSTART,RLENGTH)] = $2
    }
  } # end file text_strings.txt

  printf("// ----------------------------------------------------------------\n")
  printf("// ----------------------------------------------------------------\n")
  printf("// ------    This file was generated by the make process     ------\n")
  printf("// ------ Do not edit this file as your changes will be lost ------\n")
  printf("// ------     with the next invocation of \"make led\"         ------\n")
  printf("// ----------------------------------------------------------------\n")
  printf("// ----------------------------------------------------------------\n")

	while (getline < "segTable/codeTemplate.txt" > 0) {

    if (match($1,/<[234][NF][0-9]+>/)) {
      sIndex = $1
      gsub(/[<>]/,"",sIndex)
      gsub(/[NF]/,"",sIndex)
      orientation = substr($1,3,1)
      gen_string = text_string[sIndex]

      # handle decimal point in text string
      decimal_loc = index(gen_string,".")
      if ( decimal_loc ){
        # remove actual decimal from text
        decimal_loc--
        gsub(/\./,"",gen_string)
      }

      # handle flip character escaped code
      flip_loc = index(gen_string,",")
      if ( flip_loc ){
        # remove escape code from text
        flip_loc--
        gsub(/,/,"",gen_string)
      }

      rc = "" # start with empty string
      # now generate each character
      for (i =1; i <= length(gen_string); i++) {
        ci = substr(gen_string,i,1)

        if ( orientation == "F" && i == flip_loc )
          tc = ledValueFlip[ci]
         else
          tc = ledValueNorm[ci]

        # handle decimal point if at that character
        if (i == decimal_loc){
          tc = add_decimal(tc)
        }

      # now concatenate everything into one string each pass through
      rc = rc tc ","
      } #end for of each character

      # now replace placeholder with text
      gsub(/<[0-9][NF][0-9]+>/,rc)
      } # end if $1 matches pattern <2 3 or 4>

    if (match($1,/<[1][NF][0-9]+>/)) {
      # here when we have single "0-9" substitution
      sIndex = substr($1,4,1)
      orientation = substr($1,3,1)
      gen_string = text_string[sIndex]
      if ( orientation == "N" )
        rc = ledValueNorm[sIndex] ","
      else
        rc = ledValueFlip[sIndex] ","
      gsub(/<[0-9][NF][0-9]+>/,rc)
    }

    printf($0 "\n") # the the source, possibly modified
  } # end file text_strings.txt

} # end of pgm

#
# -------------------------------------------------------------------
#
function add_decimal(hexchars)
{
    # hexchars = "0x4F"
    msb = substr(hexchars,3,1)
    lsb = substr(hexchars,4,1)
    val = 0
    if ( msb == "F" ){ val += 240 }
    if ( msb == "E" ){ val += 224 }
    if ( msb == "D" ){ val += 208 }
    if ( msb == "C" ){ val += 192 }
    if ( msb == "B" ){ val += 176 }
    if ( msb == "A" ){ val += 160 }
    if ( msb == "9" ){ val += 144 }
    if ( msb == "8" ){ val += 128 }
    if ( msb == "7" ){ val += 112 }
    if ( msb == "6" ){ val +=  96 }
    if ( msb == "5" ){ val +=  80 }
    if ( msb == "4" ){ val +=  64 }
    if ( msb == "3" ){ val +=  48 }
    if ( msb == "2" ){ val +=  32 }
    if ( msb == "1" ){ val +=  16 }
    if ( lsb == "F" ){ val +=  15 }
    if ( lsb == "E" ){ val +=  14 }
    if ( lsb == "D" ){ val +=  13 }
    if ( lsb == "C" ){ val +=  12 }
    if ( lsb == "B" ){ val +=  11 }
    if ( lsb == "A" ){ val +=  10 }
    if ( lsb == "9" ){ val +=   9 }
    if ( lsb == "8" ){ val +=   8 }
    if ( lsb == "7" ){ val +=   7 }
    if ( lsb == "6" ){ val +=   6 }
    if ( lsb == "5" ){ val +=   5 }
    if ( lsb == "4" ){ val +=   4 }
    if ( lsb == "3" ){ val +=   3 }
    if ( lsb == "2" ){ val +=   2 }
    if ( lsb == "1" ){ val +=   1 }
    if (val >= 128) val -= 128
    return sprintf("0x%02X",val)
}
#
# -------------------------------------------------------------------
#
function hexToString(hexchars)
{
    # hexchars = "0x4F"
    msb = substr(hexchars,3,1)
    lsb = substr(hexchars,4,1)
    val = 0
    if ( msb == "F" ){ val += 240 }
    if ( msb == "E" ){ val += 224 }
    if ( msb == "D" ){ val += 208 }
    if ( msb == "C" ){ val += 192 }
    if ( msb == "B" ){ val += 176 }
    if ( msb == "A" ){ val += 160 }
    if ( msb == "9" ){ val += 144 }
    if ( msb == "8" ){ val += 128 }
    if ( msb == "7" ){ val += 112 }
    if ( msb == "6" ){ val +=  96 }
    if ( msb == "5" ){ val +=  80 }
    if ( msb == "4" ){ val +=  64 }
    if ( msb == "3" ){ val +=  48 }
    if ( msb == "2" ){ val +=  32 }
    if ( msb == "1" ){ val +=  16 }
    if ( lsb == "F" ){ val +=  15 }
    if ( lsb == "E" ){ val +=  14 }
    if ( lsb == "D" ){ val +=  13 }
    if ( lsb == "C" ){ val +=  12 }
    if ( lsb == "B" ){ val +=  11 }
    if ( lsb == "A" ){ val +=  10 }
    if ( lsb == "9" ){ val +=   9 }
    if ( lsb == "8" ){ val +=   8 }
    if ( lsb == "7" ){ val +=   7 }
    if ( lsb == "6" ){ val +=   6 }
    if ( lsb == "5" ){ val +=   5 }
    if ( lsb == "4" ){ val +=   4 }
    if ( lsb == "3" ){ val +=   3 }
    if ( lsb == "2" ){ val +=   2 }
    if ( lsb == "1" ){ val +=   1 }
    return sprintf("%c",val)
}


cellify tweaks

cellify tweaks

# cell-ify-eparams.awk
#
# columns 12 to 72 should be cellified: jot -s "," `expr 71 - 12 + 1` 12
#
#
# Parameters:
#    cellify:     What columns?     comma-separated list of column indexes to cellify. e.g. 65,66,67,68,69
#                                     hint: use `jot -s "," 5 65` or seq
#
#    label_up:    Primary label?
#
#    up_object:   Primary object?   Object of up value. If '.', use ov:csvHeader as a literal. If ':', use ov:csvHeader as a resource.
#
#    up_range:    Primary object?   Object of up value
#
#    out_range:   ? e.g. Type of out value.                                        e.g. xsd:gYear
#
#    labels_up:   What range?       comma-separated list of secondary predicate labels.
#
# Example:
#      conversion:enhance [
#         ov:csvCol         65;
#         ov:csvHeader     "BAR00";
#         conversion:label "BAR00";
#         conversion:range  todo:Literal;
#      ];
#
# (params: )
#
#      conversion:enhance [
#          ov:csvCol         65;
#          ov:csvHeader     "BAR00";
#          conversion:label "Year";                      # WAS: BAR00
#          conversion:object "2000"^^xsd:gYear;          # new: value represented by column header
#          conversion:range  rdfs:decimal;               # WAS: todo:Literal
#       ];
#       conversion:enhance [                             # new:
#          ov:csvCol         65;                         # new:
#          conversion:predicate "Place";                 # new:
#          conversion:object    "Bar";                   # new:
#       ];                                               # new:
#
# Example usage:
#
#    (input)
#
#    conversion:enhance [
#       ov:csvCol         12;
#       ov:csvHeader     "Sum_WORK90";
#       conversion:label "Sum_WORK90";
#       conversion:range  todo:Literal;
#    ];
#
#    cat cities-pc-cnty.csv.e1.params.ttl | awk -f $CSV2RDF4LOD_HOME/bin/util/cell-ify-eparams.awk -v cellify=`jot -s "," 60 12` -v label_up="Year" -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue
#
#    (output)
#
#    conversion:enhance [
#       ov:csvCol         12;
#       ov:csvHeader     "Sum_WORK90";
#       a scovo:Item;                                               # :
#       conversion:label  "Year";                                   # : was "Sum_WORK90";
#       conversion:object ""^^xsd:gYear;                            # :
#       conversion:range  xsd:decimal;                              # : was todo:Literal;
#    ];
#    conversion:enhance [                                           # :
#       ov:csvCol            12;                                    # :
#       conversion:predicate "Venue";                               # :
#       conversion:object    "";                                    # :
#    ];                                                             # :
#
# NOTE: The conversion:objects must still be populated.

BEGIN {
   PADDING = 70;

   num_cells = split(cellify,cell_column,",");
   for(i=1; i<=num_cells; i++) {
      c = cell_column[i];
      a_cell[c] = "true";
   }
   num_labels_up = split(labels_up,secondaryPs,",");

   in_cell_enhancement = "false";
}

$1 == "ov:csvCol" && in_cell_enhancement ==  "false" {
   column=$2;
   gsub(/;/,"",column);
   gsub(/\"/,"",column);
   if( a_cell[column] == "true" ) {
      in_cell_enhancement = "true";
   }
}

function annotate(pre,pad,annotation)
{
   line=pre;
   spaces="";
   for(i=1; i<(pad-length(line)); i++) {
      spaces=spaces" ";
   }
   return sprintf("%s%s# : %s",line,spaces,annotation);
}

in_cell_enhancement == "true" {
   if( $1 == "ov:csvCol" ) {
      lastCol=$2;
      gsub(/;/,"",lastCol);
      gsub(/\"/,"",lastCol);
   }
   line=$0;

   if( length(label_up) > 0 && $1 == "conversion:label" || $1 == "#conversion:label" ) {
      print annotate("         conversion:label  \""label_up"\";",PADDING,"was "$2);
   }else if( length(out_range) > 0 && $1 == "conversion:range" ) {
      print annotate("         conversion:range  "out_range";",PADDING,"was "$2);
   }else if( $1 == "];" ) {
      print $0
      for(i=1; i<=num_labels_up; i++) {
          what=sprintf("         conversion:predicate \"%s\";",secondaryPs[i]);
         print annotate(        "      conversion:enhance [",PADDING,"");
         print annotate(        "         ov:csvCol            "lastCol";",PADDING,"");
         print annotate(what ,PADDING,"");
         print annotate(        "         conversion:object    \"\";",PADDING,"");
         print annotate(        "      ];",PADDING,"");
      }
   }else {
      print
   }

   if( $1 == "ov:csvHeader" ) {
      current_header=$2; # Old approach missed header after first space.
      current_header=$0; gsub(/^[^"]*"/,"",current_header);
                         gsub(/".*$/,   "",current_header);
      gsub(/"/,"",current_header);
      gsub(/;/,"",current_header);
      print annotate("         a scovo:Item;",PADDING,"");
      print annotate("         a qb:Observation;",PADDING,"");
   }
   if( length(label_up) > 0 && ( $1 == "conversion:label" || $1 == "#conversion:label" ) ) {
      datatype = length(up_range) > 0 ? "^^"up_range : "";
      if( up_object == ":" ) {
         print annotate("         conversion:object :"current_header";",PADDING,"");
      }else if( up_object == "." ) {
         print annotate("         conversion:object \""current_header"\""datatype";",PADDING,"");
      }else {
         print annotate("         conversion:object \""up_object"\""datatype";",PADDING,"");
      }
   }
}

{
   if( in_cell_enhancement == "true" && $1 == "];" ) {
      in_cell_enhancement = "false";
   }else if( in_cell_enhancement == "false" ) {
      print $0
   }
}

END {
   #if( num_cells == 0 ) {
      print "# params:"
      print "#   -v cellify=`jot -s \",\" 5 10` -v label_up=Year -v up_object={. : Blah} -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue,Another,YAnother"
      print "#   -v cellify=`echo \"\" | awk '{for(i=5;i<=10;i++){printf(\",%s\",i)}}'` -v label_up=Year -v up_object=Blah -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue,Another,YAnother"
   #}
}

# cell-ify-eparams.awk
#
# columns 12 to 72 should be cellified: jot -s "," `expr 71 - 12 + 1` 12
#
#
# Parameters:
#    cellify:     What columns?     comma-separated list of column indexes to cellify. e.g. 65,66,67,68,69
#                                     hint: use `jot -s "," 5 65` or seq
#
#    label_up:    Primary label?
#
#    up_object:   Primary object?   Object of up value. If '.', use ov:csvHeader as a literal. If ':', use ov:csvHeader as a resource.
#
#    up_range:    Primary object?   Object of up value
#
#    out_range:   ? e.g. Type of out value.                                        e.g. xsd:gYear
#
#    labels_up:   What range?       comma-separated list of secondary predicate labels.
#
# Example:
#      conversion:enhance [
#         ov:csvCol         65;
#         ov:csvHeader     "BAR00";
#         conversion:label "BAR00";
#         conversion:range  todo:Literal;
#      ];
#
# (params: )
#
#      conversion:enhance [
#          ov:csvCol         65;
#          ov:csvHeader     "BAR00";
#          conversion:label "Year";                      # WAS: BAR00
#          conversion:object "2000"^^xsd:gYear;          # new: value represented by column header
#          conversion:range  rdfs:decimal;               # WAS: todo:Literal
#       ];
#       conversion:enhance [                             # new:
#          ov:csvCol         65;                         # new:
#          conversion:predicate "Place";                 # new:
#          conversion:object    "Bar";                   # new:
#       ];                                               # new:
#
# Example usage:
#
#    (input)
#
#    conversion:enhance [
#       ov:csvCol         12;
#       ov:csvHeader     "Sum_WORK90";
#       conversion:label "Sum_WORK90";
#       conversion:range  todo:Literal;
#    ];
#
#    cat cities-pc-cnty.csv.e1.params.ttl | awk -f $CSV2RDF4LOD_HOME/bin/util/cell-ify-eparams.awk -v cellify=`jot -s "," 60 12` -v label_up="Year" -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue
#
#    (output)
#
#    conversion:enhance [
#       ov:csvCol         12;
#       ov:csvHeader     "Sum_WORK90";
#       a scovo:Item;                                               # :
#       conversion:label  "Year";                                   # : was "Sum_WORK90";
#       conversion:object ""^^xsd:gYear;                            # :
#       conversion:range  xsd:decimal;                              # : was todo:Literal;
#    ];
#    conversion:enhance [                                           # :
#       ov:csvCol            12;                                    # :
#       conversion:predicate "Venue";                               # :
#       conversion:object    "";                                    # :
#    ];                                                             # :
#
# NOTE: The conversion:objects must still be populated.

BEGIN {
   PADDING = 70;

   num_cells = split(cellify,cell_column,",");
   for(i=1; i<=num_cells; i++) {
      c = cell_column[i];
      a_cell[c] = "true";
   }
   num_labels_up = split(labels_up,secondaryPs,",");

   in_cell_enhancement = "false";
}

$1 == "ov:csvCol" && in_cell_enhancement ==  "false" {
   column=$2;
   gsub(/;/,"",column);
   gsub(/\"/,"",column);
   if( a_cell[column] == "true" ) {
      in_cell_enhancement = "true";
   }
}

function annotate(pre,pad,annotation)
{
   line=pre;
   spaces="";
   for(i=1; i<(pad-length(line)); i++) {
      spaces=spaces" ";
   }
   return sprintf("%s%s# : %s",line,spaces,annotation);
}

in_cell_enhancement == "true" {
   if( $1 == "ov:csvCol" ) {
      lastCol=$2;
      gsub(/;/,"",lastCol);
      gsub(/\"/,"",lastCol);
   }
   line=$0;

   if( length(label_up) > 0 && $1 == "conversion:label" || $1 == "#conversion:label" ) {
      print annotate("         conversion:label  \""label_up"\";",PADDING,"was "$2);
   }else if( length(out_range) > 0 && $1 == "conversion:range" ) {
      print annotate("         conversion:range  "out_range";",PADDING,"was "$2);
   }else if( $1 == "];" ) {
      print $0
      for(i=1; i<=num_labels_up; i++) {
          what=sprintf("         conversion:predicate \"%s\";",secondaryPs[i]);
         print annotate(        "      conversion:enhance [",PADDING,"");
         print annotate(        "         ov:csvCol            "lastCol";",PADDING,"");
         print annotate(what ,PADDING,"");
         print annotate(        "         conversion:object    \"\";",PADDING,"");
         print annotate(        "      ];",PADDING,"");
      }
   }else {
      print
   }

   if( $1 == "ov:csvHeader" ) {
      current_header=$2;
      gsub(/"/,"",current_header);
      gsub(/;/,"",current_header);
      print annotate("         a scovo:Item;",PADDING,"");
   }
   if( length(label_up) > 0 && $1 == "conversion:label" ) {
      datatype = length(up_range) > 0 ? "^^"up_range : "";
      if( up_object == ":" ) {
         print annotate("         conversion:object :"current_header";",PADDING,"");
      }else if( up_object == "." ) {
         print annotate("         conversion:object \""current_header"\""datatype";",PADDING,"");
      }else {
         print annotate("         conversion:object \""up_object"\""datatype";",PADDING,"");
      }
   }
}

{
   if( in_cell_enhancement == "true" && $1 == "];" ) {
      in_cell_enhancement = "false";
   }else if( in_cell_enhancement == "false" ) {
      print $0
   }
}

END {
   #if( num_cells == 0 ) {
      print "# params:"
      print "#   -v cellify=`jot -s \",\" 5 10` -v label_up=Year -v up_object={. : Blah} -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue,Another,YAnother"
      print "#   -v cellify=`echo \"\" | awk '{for(i=5;i<=10;i++){printf(\",%s\",i)}}'` -v label_up=Year -v up_object=Blah -v up_range=xsd:gYear -v out_range=xsd:decimal -v labels_up=Venue,Another,YAnother"
   #}
}


INTEGRATION: CWS localedata5 (1.4.36); FILE MERGED 2005/05/31 16:53:15 er 1.4.36.1: [NatNum#] is not a currency

#!/usr/bin/gawk -f
# Usage: gawk -f currency-check.awk *.xml
# Check any
# <FormatCode>...[$xxx-...]...</FormatCode>
# against every
# <CurrencySymbol>xxx</CurrencySymbol>
# definition of the same XML file and output symbols if no match was found.
# For formatindex="12" to formatindex="15" and for formatindex="17" it is
# checked if the used currency symbol is the usedInCompatibleFormatCodes
# currency symbol as it is needed by the number formatter.
# Also generates output if the generic currency symbol (UTF8 string 0xC2A4)
# is used instead of a real currency symbol.
# Author: Eike Rathke <er@openoffice.org>

BEGIN {
    file = ""
}

file != FILENAME {
    if ( file )
        checkIt()
    file = FILENAME
    line = 0
    nFormats = 0
    nSymbols = 0
    bSymbolDefault = 0
    bSymbolCompati = 0
    bFormatAuto = 0
    sReplaceFrom = ""
    sReplaceTo = ""
    sMatchReplace = ""
    sRefCurrencyFromLocale = ""
    crlf = 0
}

{
    ++line
    # If run under Unix a CrLf spoils ...$ line end checks. DOS line endings
    # are boo anyways.
    if ( /\x0D$/ )
    {
        print "Error: not Unix line ending in line " line
        crlf = 1
        exit(1)
    }
    if ( $1 ~ /^<LC_FORMAT$/ )
    {
        if ( $0 ~ /replaceFrom="\[CURRENCY\]"/ )
        {
            sReplaceFrom = "\\[CURRENCY\\]"
            sMatchReplace = "^<FormatCode>.*" sReplaceFrom
        }
        for ( j=2; j<=NF; ++j )
        {
            if ( $j ~ /^replaceTo="/ )
            {
                l = 12
                if ( $j ~ />$/ )
                    ++l
                if ( $j ~ /\/>$/ )
                    ++l
                sReplaceTo = substr( $j, 12, length($j)-l )
            }
        }
    }
    else if ( $1 ~ /^<FormatElement$/ )
    {
        if ( $0 ~ /usage="CURRENCY"/ )
        {
            if ( $0 ~ /formatindex="1[23457]"/ )
                bFormatAuto = 1
            else
                bFormatAuto = 0
        }
    }
    else if ( $0 ~ /^[[:blank:]]*<FormatCode>.*\[\$.*-[0-9a-fA-F]+\]/ ||
            (sMatchReplace && $0 ~ sMatchReplace ) )
    {
        if ( sReplaceFrom )
            gsub( sReplaceFrom, sReplaceTo )
        split( $0, arr, /<|>/ )
        split( arr[3], code, /(\[\$)|(-[0-9a-fA-F]+\])/ )
        for ( j in code )
        {
            if ( code[j] && code[j] !~ /\#|0|\[NatNum/ )
            {
                FormatLine[nFormats] = file " line " line
                FormatAuto[nFormats] = bFormatAuto
                Formats[nFormats++] = code[j]
            }
        }
        bFormatAuto = 0
    }
    else if ( $1 ~ /^<LC_CURRENCY$/ )
    {
        for ( j=2; j<=NF; ++j )
        {
            if ( $j ~ /^ref="/ )
            {
                l = 6
                if ( $j ~ />$/ )
                    ++l
                if ( $j ~ /\/>$/ )
                    ++l
                locale = substr( $j, 6, length($j)-l )
                sRefCurrencyFromLocale = file
                oldfile = file
                oldline = line
                file = locale ".xml"
                line = 0
                while ( (getline <file) > 0 )
                {
                    ++line
                    getCurrencyParams()
                }
                close( file )
                if ( !line )
                    print "ref locale not available: " file \
                        " (from " oldfile " line " oldline ")"
                file = oldfile
                line = oldline
                sRefCurrencyFromLocale = ""
            }
        }
    }
    else
        getCurrencyParams()
}

END {
    if ( file && !crlf )
        checkIt()
}

function getCurrencyParams() {
    if ( $1 ~ /^<Currency$/ )
    {
        if ( $0 ~ /default="true"/ )
            bSymbolDefault = 1
        else
            bSymbolDefault = 0
        if ( $0 ~ /usedInCompatibleFormatCodes="true"/ )
            bSymbolCompati = 1
        else
            bSymbolCompati = 0
    }
    else if ( $0 ~ /^[[:blank:]]*<CurrencySymbol>/ )
    {
        split( $0, arr, /<|>/ )
        if ( sRefCurrencyFromLocale )
            SymbolLine[nSymbols] = file " line " line \
                " (referenced from " sRefCurrencyFromLocale ")"
        else
            SymbolLine[nSymbols] = file " line " line
        SymbolDefault[nSymbols] = bSymbolDefault
        SymbolCompati[nSymbols] = bSymbolCompati
        Symbols[nSymbols++] = arr[3]
        bSymbolDefault = 0
        bSymbolCompati = 0
    }
}

function checkIt() {
    bad = 0
    for ( j=0; j<nFormats; ++j )
    {
        state = FormatInSymbol( Formats[j] )
        if ( Formats[j] == "\xc2\xa4" )
        {
            bad = 1
            print "    bad: `" Formats[j] "'   (" FormatLine[j] ")"
        }
        else if ( state == 0 )
        {
            bad = 1
            print "unknown: `" Formats[j] "'   (" FormatLine[j] ")"
        }
        else if ( FormatAuto[j] && state < 2 )
        {
            bad = 1
            print "badauto: `" Formats[j] "'   (" FormatLine[j] ")"
        }
    }
    if ( bad )
    {
        for ( j=0; j<nSymbols; ++j )
        {
            bDef = 0
            if ( Symbols[j] == "\xc2\xa4" )
                print "def bad: `" Symbols[j] "'   (" SymbolLine[j] ")"
            if ( SymbolDefault[j] )
            {
                bDef = 1
                print "default: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( SymbolCompati[j] )
            {
                bDef = 1
                print "compati: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( !bDef )
                print "defined: `" Symbols[j] "'   (" SymbolLine[j] ")"
        }
    }
    else
    {
        bHasDefault = 0
        bHasCompati = 0
        for ( j=0; j<nSymbols; ++j )
        {
            if ( Symbols[j] == "\xc2\xa4" )
            {
                bad = 1
                print "def bad: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( SymbolDefault[j] )
            {
                if ( !bHasDefault )
                    bHasDefault = 1
                else
                {
                    bad = 1
                    print "dupe default: `" Symbols[j] "'   (" SymbolLine[j] ")"
                }
            }
            if ( SymbolCompati[j] )
            {
                if ( !bHasCompati )
                    bHasCompati = 1
                else
                {
                    bad = 1
                    print "dupe compati: `" Symbols[j] "'   (" SymbolLine[j] ")"
                }
            }
        }
        if ( !bHasDefault )
        {
            bad = 1
            print "  no default: (" file ")"
        }
        if ( !bHasCompati )
        {
            bad = 1
            print "  no compati: (" file ")"
        }
    }
    if ( bad )
        print ""
}

function FormatInSymbol( format ) {
    for ( nSym=0; nSym<nSymbols; ++nSym )
    {
        if ( format == Symbols[nSym] )
        {
            if ( SymbolCompati[nSym] )
                return 2
            else
                return 1
        }
    }
    return 0
}

# vim: ts=4 sw=4 expandtab

#!/usr/bin/gawk -f
# Usage: gawk -f currency-check.awk *.xml
# Check any
# <FormatCode>...[$xxx-...]...</FormatCode>
# against every
# <CurrencySymbol>xxx</CurrencySymbol>
# definition of the same XML file and output symbols if no match was found.
# For formatindex="12" to formatindex="15" and for formatindex="17" it is
# checked if the used currency symbol is the usedInCompatibleFormatCodes
# currency symbol as it is needed by the number formatter.
# Also generates output if the generic currency symbol (UTF8 string 0xC2A4)
# is used instead of a real currency symbol.
# Author: Eike Rathke <er@openoffice.org>

BEGIN {
    file = ""
}

file != FILENAME {
    if ( file )
        checkIt()
    file = FILENAME
    line = 0
    nFormats = 0
    nSymbols = 0
    bSymbolDefault = 0
    bSymbolCompati = 0
    bFormatAuto = 0
    sReplaceFrom = ""
    sReplaceTo = ""
    sMatchReplace = ""
    sRefCurrencyFromLocale = ""
    crlf = 0
}

{
    ++line
    # If run under Unix a CrLf spoils ...$ line end checks. DOS line endings
    # are boo anyways.
    if ( /\x0D$/ )
    {
        print "Error: not Unix line ending in line " line
        crlf = 1
        exit(1)
    }
    if ( $1 ~ /^<LC_FORMAT$/ )
    {
        if ( $0 ~ /replaceFrom="\[CURRENCY\]"/ )
        {
            sReplaceFrom = "\\[CURRENCY\\]"
            sMatchReplace = "^<FormatCode>.*" sReplaceFrom
        }
        for ( j=2; j<=NF; ++j )
        {
            if ( $j ~ /^replaceTo="/ )
            {
                l = 12
                if ( $j ~ />$/ )
                    ++l
                if ( $j ~ /\/>$/ )
                    ++l
                sReplaceTo = substr( $j, 12, length($j)-l )
            }
        }
    }
    else if ( $1 ~ /^<FormatElement$/ )
    {
        if ( $0 ~ /usage="CURRENCY"/ )
        {
            if ( $0 ~ /formatindex="1[23457]"/ )
                bFormatAuto = 1
            else
                bFormatAuto = 0
        }
    }
    else if ( $0 ~ /^[[:blank:]]*<FormatCode>.*\[\$.*-[0-9a-fA-F]+\]/ ||
            (sMatchReplace && $0 ~ sMatchReplace ) )
    {
        if ( sReplaceFrom )
            gsub( sReplaceFrom, sReplaceTo )
        split( $0, arr, /<|>/ )
        split( arr[3], code, /(\[\$)|(-[0-9a-fA-F]+\])/ )
        for ( j in code )
        {
            if ( code[j] && code[j] !~ /\#|0/ )
            {
                FormatLine[nFormats] = file " line " line
                FormatAuto[nFormats] = bFormatAuto
                Formats[nFormats++] = code[j]
            }
        }
        bFormatAuto = 0
    }
    else if ( $1 ~ /^<LC_CURRENCY$/ )
    {
        for ( j=2; j<=NF; ++j )
        {
            if ( $j ~ /^ref="/ )
            {
                l = 6
                if ( $j ~ />$/ )
                    ++l
                if ( $j ~ /\/>$/ )
                    ++l
                locale = substr( $j, 6, length($j)-l )
                sRefCurrencyFromLocale = file
                oldfile = file
                oldline = line
                file = locale ".xml"
                line = 0
                while ( (getline <file) > 0 )
                {
                    ++line
                    getCurrencyParams()
                }
                close( file )
                if ( !line )
                    print "ref locale not available: " file \
                        " (from " oldfile " line " oldline ")"
                file = oldfile
                line = oldline
                sRefCurrencyFromLocale = ""
            }
        }
    }
    else
        getCurrencyParams()
}

END {
    if ( file && !crlf )
        checkIt()
}

function getCurrencyParams() {
    if ( $1 ~ /^<Currency$/ )
    {
        if ( $0 ~ /default="true"/ )
            bSymbolDefault = 1
        else
            bSymbolDefault = 0
        if ( $0 ~ /usedInCompatibleFormatCodes="true"/ )
            bSymbolCompati = 1
        else
            bSymbolCompati = 0
    }
    else if ( $0 ~ /^[[:blank:]]*<CurrencySymbol>/ )
    {
        split( $0, arr, /<|>/ )
        if ( sRefCurrencyFromLocale )
            SymbolLine[nSymbols] = file " line " line \
                " (referenced from " sRefCurrencyFromLocale ")"
        else
            SymbolLine[nSymbols] = file " line " line
        SymbolDefault[nSymbols] = bSymbolDefault
        SymbolCompati[nSymbols] = bSymbolCompati
        Symbols[nSymbols++] = arr[3]
        bSymbolDefault = 0
        bSymbolCompati = 0
    }
}

function checkIt() {
    bad = 0
    for ( j=0; j<nFormats; ++j )
    {
        state = FormatInSymbol( Formats[j] )
        if ( Formats[j] == "\xc2\xa4" )
        {
            bad = 1
            print "    bad: `" Formats[j] "'   (" FormatLine[j] ")"
        }
        else if ( state == 0 )
        {
            bad = 1
            print "unknown: `" Formats[j] "'   (" FormatLine[j] ")"
        }
        else if ( FormatAuto[j] && state < 2 )
        {
            bad = 1
            print "badauto: `" Formats[j] "'   (" FormatLine[j] ")"
        }
    }
    if ( bad )
    {
        for ( j=0; j<nSymbols; ++j )
        {
            bDef = 0
            if ( Symbols[j] == "\xc2\xa4" )
                print "def bad: `" Symbols[j] "'   (" SymbolLine[j] ")"
            if ( SymbolDefault[j] )
            {
                bDef = 1
                print "default: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( SymbolCompati[j] )
            {
                bDef = 1
                print "compati: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( !bDef )
                print "defined: `" Symbols[j] "'   (" SymbolLine[j] ")"
        }
    }
    else
    {
        bHasDefault = 0
        bHasCompati = 0
        for ( j=0; j<nSymbols; ++j )
        {
            if ( Symbols[j] == "\xc2\xa4" )
            {
                bad = 1
                print "def bad: `" Symbols[j] "'   (" SymbolLine[j] ")"
            }
            if ( SymbolDefault[j] )
            {
                if ( !bHasDefault )
                    bHasDefault = 1
                else
                {
                    bad = 1
                    print "dupe default: `" Symbols[j] "'   (" SymbolLine[j] ")"
                }
            }
            if ( SymbolCompati[j] )
            {
                if ( !bHasCompati )
                    bHasCompati = 1
                else
                {
                    bad = 1
                    print "dupe compati: `" Symbols[j] "'   (" SymbolLine[j] ")"
                }
            }
        }
        if ( !bHasDefault )
        {
            bad = 1
            print "  no default: (" file ")"
        }
        if ( !bHasCompati )
        {
            bad = 1
            print "  no compati: (" file ")"
        }
    }
    if ( bad )
        print ""
}

function FormatInSymbol( format ) {
    for ( nSym=0; nSym<nSymbols; ++nSym )
    {
        if ( format == Symbols[nSym] )
        {
            if ( SymbolCompati[nSym] )
                return 2
            else
                return 1
        }
    }
    return 0
}

# vim: ts=4 sw=4 expandtab


comments

comments

#! /usr/bin/awk -f
# ${DIPPER}/scripts/generate-URI_label.awk \
# ${DIPPER}/dipper/curie_map.yaml ${DIPPER}/translationtable/GLOBAL_TERMS.yaml

# Reconstitutes the label an URI has based on Dipper's mapping files.
# note: this relies on uninforced yaml quoting disipline

# in: curie_map.yaml    'pfx': 'buri'
NR == FNR && !/^#/{
	FS="'"
	a[$2]=$4
}

# in: GLOBAL_TERMS.yaml  "label": "curie",
NR != FNR && !/^#/{
	FS="\""
	split($4, t,":");
	if(t[1] in a)
		print a[t[1]] t[2] "\t" $2
}
# out: URI label

#! /usr/bin/awk -f
# generate-URI_label.awk
# ${DIPPER}/dipper/curie_map.yaml ${DIPPER}/translationtable/GLOBAL_TERMS.yaml

# Reconstitutes the label an URI has based on Dipper's mapping files.

# curie_map.yaml    'pfx': 'buri'
NR == FNR && !/^#/{
	FS="'"
	a[$2]=$4
}

# GLOBAL_TERMS.yaml  "label": "curie",
NR != FNR && !/^#/{
	FS="\""
	split($4, t,":");
	if(t[1] in a)
		print a[t[1]] t[2] "\t" $2
}