APFSJ = "165" # WBInclusions:APFS

# SubstitutionString("s" * "\\1" * t*)

using Dates

global HI_COLOR_PFX = "\033["
function HI_COLOR(clr)
    return HI_COLOR_PFX * string(clr) * ";1m"
end

global LO_GRAY     = HI_COLOR(30)
global HI_RED      = HI_COLOR(31)
global HI_GREEN    = HI_COLOR(32)
global HI_YELLOW   = HI_COLOR(33)
global HI_BLUE     = HI_COLOR(34)
global HI_MAGENTA  = HI_COLOR(35)
global HI_AQUA     = HI_COLOR(36)
global HI_WHITE    = HI_COLOR(37)
global HI_END      = HI_COLOR_PFX * "0m"

function hilite(clr, txt)
    return clr * string(txt) * HI_END
end

global UCK = 0
while UCK < 10
    try 
        global UTCoffset = Int32(round((Dates.value(now(UTC)) - Dates.value(now())) / (60 * 60 * 1000)))
        global UCK = 9999
    catch ex
        global UCK += 1
        s = string(ex)  
        if length(s) > 200
            s = s[1:200] * "..."
        end
        println("\n      " * hilite(HI_RED * "UTC Failure: " * string(typeof(ex)) * ".") * "\n");
    end
end

global SpellingBees = 102

global HILITE_TOHEX = Dict(
    0 => hilite(HI_AQUA, "."), 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 
    9 => "9", 10 => hilite(HI_AQUA, "A"), 11 => hilite(HI_AQUA, "B"), 12 => hilite(HI_AQUA, "C"), 
    13 => hilite(HI_AQUA, "D"), 14 => hilite(HI_AQUA, "E"), 15 => hilite(HI_AQUA, "F")
)

global TrackedScripts = ["Ascii", "Hexprint", "Sc9", "TzMulti", "BP", "NUBP", "del", "WBInclusions",
                         "WB", "WBafter", "WBupdate", "WBTree", "w/WBCount", "WBSearch",
                         "WBMap", "w/WBcompare", "WBheads", "WBW", "WBX", "WBY",
                         "WBZ", "WB_Transforms", "WBdiff", "ZZ", "WBM", "Quora", "C9images"]

function Duree(start, finish, x)    #  Duree(a, now()) = "0d 00h 35m 56s"
  a = div(tryparse(Int64,replace(string(finish - start), " milliseconds" => "")), 1000)
  days = div(a, 86400)
  rmdr = a - days * 86400
  hours = div(rmdr, 3600)
  mins = div(rmdr - hours * 3600, 60)
  secs = "00" * string(rmdr - mins * 60)
  mins = "00" * string(mins)
  hours = "00" * string(hours)
  return string(days) * "d " * 
         hours[length(hours) - 1 : length(hours)] * "h " * 
         mins[length(mins) - 1 : length(mins)] * "m " *
         secs[length(secs) - 1 : length(secs)] * "s"  
end
function Duree(start, finish)
  return replace(Duree(start, finish, "X"), r"m.*$" => "m")
end

global APtS_End = DateTime(2022,9,11,15,45)
global APtS_ET = "APtS(843) " * Duree(APtS_End, now())

function noww()
    dt = string(Dates.now())
    dtx = findfirst('T', dt)
    if dtx == nothing || length(dt) < 20 || dt[20] != '.'
        println("\n**** Date fuckup noww(): \"" * dt * "\" ****\n")
        exit(16)
    end
    return dt[1: dtx - 1] * " " * dt[dtx + 1: 19]
end

function RRead(nm, options)
    a = open(nm, "r")
    b = read(a)
    close(a)
    lco = lowercase(options)
    if lco == "raw"
        return b
    end
    tot127 = 0
    first127 = -1
    gotDOS = false
    lowBAD = -1
    firstLowBAD = -1
    ix = 0
    for c in b
        if c > 127
            if first127 == -1
                first127 = ix
            end 
            tot127 += 1
        elseif c < 32
            if c == 13   #  \x0d
                gotDOS = true
            elseif c != 10    # not \x0a below \x20 (space char) 
                if firstLowBAD == -1
                    firstLowBAD = ix
                end
                lowBAD += 1
            end    
        end
        ix += 1         
    end
    pfx = prefix = "\n\n"
    if tot127 > 0
        println(prefix, hilite(HI_RED, "    *** " * string(tot127) * " charcters > 127 found in " * nm * 
                " (" * string(first127) * ") ***"))
        prefix = "\n"
    end
    if lowBAD != -1
        println(prefix, hilite(HI_RED, "    *** " * string(lowBAD) * " BAD charcters < 32 found in " * nm * 
                " (" * string(firstLowBAD) * ") ***"))
        prefix = "\n"
    end
    if gotDOS
        println(prefix, hilite(HI_RED, "    *** DOS lineend(s) found in: " * nm * " ***"))
        prefix = "\n"
    end
    if pfx != prefix
        println("\n")
    end
    b = String(b)
    if lco == "asis" 
        return b
    end
    if lco == "clean"
        b = replace(b, "-->" => "``>")
        return replace(b, r"<!--[^`]+``>" => "<!-- COMMENT -->")
    end
    println("       RRead invalid options: \"", options, "\"")
    exit(16)
end

function formatDecimal(flt, dgts)
    a = string(round(flt, digits = dgts))
    b = findfirst(r"\.\d+", a)
    if b == nothing
        println("\n", hilite(HI_RED, "formatDecimal no period: \"" * string(flt) * "\"."))
        exit(16)
    end
    c = dgts - (b.stop - b.start)
    if c > 0
        a *= "0" ^ c
    end
    return a
end

function formatFixed(fixd)
    fx = string(fixd)
    a = ""
    punctuation = ""
    while (lenfx = length(fx)) > 3
        a = fx[lenfx - 2: lenfx] * punctuation * a
        punctuation = ","
        fx = fx[1:lenfx - 3]
    end
    if lenfx == 0
        return a
    end
    return fx * punctuation * a
end 

function getBackupNumber()
    bkupfn = "/ROM/BO/WBBKUPID"
    bkupid = open(bkupfn, "r")
    bkupnr = string(tryparse(Int64, readline(bkupid)) + 1)
    close(bkupid)
    bkupid = open(bkupfn, "w")
    write(bkupid, bkupnr * "\n")
    close(bkupid)
    verifi = RRead(bkupfn,"asis")
    if verifi != bkupnr * "\n"
        println("\n    " * hilite(HI_RED * bkupfn * " update catastrophic failure!") * "\n") 
        exit(16)
    end
    return bkupnr
end

#   length(findall(\"<span style=\\\"color:black;\\\">info@servantofthepeople.com</span>\", ax)


function wh(x)

#   "X \e[30;1m Y \e[0m Z" = "X " * LO_GRAY * " Y " * HI_END * " Z" 

    return replace(wh(), r"\e\[30;1m([wz])\e\[0m" =>
            s"<span style=\"font-weight:normal;\">\1</span>")
end

function wh()
    a1 = RRead("Z.txt", "asis")
    a1 = a1[findfirst("`",a1).start : length(a1)]
    global confirmeds = length(findall("| ", a1))
    global sents = length(findall("|+", a1))
    global zelenskys = 0
    
    for itm in ["9", "10", "11", "12"] 
        EMP("ax = RRead(\"Zelensky" * itm * ".html\", \"asis\");" * 
            "ax = ax[findfirst(r\"`[^`]+`\", ax)];" * 
            "global confirmeds += length(findall(\"&#62;\", ax));" * 
            "global sents += length(findall(\"THANK YOU FOR YOUR SUBMISSION!\", ax));" *
            "global zelenskys += length(findall(\"<span style=\\\"color:black;\\\">info@servantofthepeople.com</span>\", ax))")
    end

    return hilite(LO_GRAY, "w") * string(confirmeds) * "/" * string(sents)   * hilite(LO_GRAY, "z") * string(zelenskys)
end

# Equivalent of APL eval()
function EMP(txt)
    #println("EMP: [", txt, "]")
    if typeof(txt) != String
        println("EMP parameter not String: [", txt, "]")
        return nothing
    end
    return(eval(Meta.parse(txt)))::Any
end