include("WBInclusions")     # Not using noww() function here

global version = "029"

global fn = "w\\txts\\BP"
global displayCt = 16

global ARGZ = copy(ARGS)
global lenARGZ = length(ARGZ)

# Cheat against myself. NumberS are seeming to be too low.

if lenARGZ == 6
    global ARGZ = [string(max(parse(Int32, ARGZ[1]), parse(Int32, ARGZ[4]))), 
                   string(max(parse(Int32, ARGZ[2]), parse(Int32, ARGZ[5]))), 
                   string(max(parse(Int32, ARGZ[3]), parse(Int32, ARGZ[6])))]
    global lenARGZ = length(ARGZ)
end

global MAAAS = 0
global MAAAD = 0
global MINMINS = 99999
global MINMIND = 99999

struct ITEM
    s
    d
end

function pushDown(itm, arry)
    return append!([itm],arry[1:length(arry) - 1])
end       

global ThisDayTotS = 0
global ThisDayTotD = 0
global LenThisDay = 0
global IgnoredLines = 0
global EODs = Dict{String,Array{ITEM}}()

if lenARGZ == 0
    # Go to display current file contents
elseif lenARGZ == 1
    global displayCt = tryparse(Int32, ARGZ[1])
elseif lenARGZ != 3
    println("Wrong number arguments")
    exit(16)
else
    if !isfile(fn)
        close(open(fn, "w"))
    end 

    global nowwRaw = now()
    global nowww = string(nowwRaw)
    global nowww_HM = nowww[12:16]

    prev = split(RRead(fn, "asis"), "\n")
    lenPrev = length(prev)
    global lds = lenPrev
    if lenPrev > 0
        while true
            if prev[lds][3:12] != "          "
                break
            end
            global lds = lds - 1
        end
    end
    if length(ARGZ[1]) != 3 || length(ARGZ[2]) != 2 || !(length(ARGZ[3]) in [2,3]) 
        println("\nAsshole parameter length: ", ARGZ)
        exit(16)
    end

    global Join_ARGZ_Original = ARGZ[1] * " " * ARGZ[2] *        (length(ARGZ[3]) == 2 ? "  " : " ") * ARGZ[3] 
    global Join_ARGZ =          ARGZ[1] * " " * ARGZ[2] * "  " * (length(ARGZ[3]) == 2 ? ARGZ[3] : "99")

    if findfirst(r"^[12]\d{2} [56789]\d  [456789]\d$", Join_ARGZ) == nothing
        println("\nInput bad: ", ARGZ)
        exit(16)
    end

    cur = replace(nowww, r"T(.{5}).*" => s" \1") * "  " * Join_ARGZ_Original

    global doy = "000" * string(dayofyear(nowwRaw) + (cur[1:4] == "2024" ? 365 : 0))
    lenDoy = length(doy)
    global doy = "   " * doy[lenDoy - 3: lenDoy]

    if lenPrev == 0
        b = open(fn, "w")
        write(b, "  " * cur * doy)
    else
        b = open(fn, "a")
        if cur[1:10] == prev[lds][3:12] 
            write(b, "\n            " * cur[11:length(cur)] * doy)
        else
            write(b, "\n  " * cur * doy)
        end
    end
    close(b)
end

global all = []

linesIn = split(RRead(fn, "asis"), "\n")
for itm in linesIn
    if length(itm) < 1 || itm[1:1] == "#"
        global IgnoredLines += 1
        continue
    end
    push!(all, itm)            # push! inserts at the end not the beginning of the list
end 

global hiD = 0
global hiS = 0
global loD = 999
global loS = 999
global MaxMaxS = 0
global MaxMaxD = 0
global MinMinS = 999
global MinMinD = 999

global SQ32 = zeros(Int32,32)
global DQ32 = zeros(Int32,32)
global Qct = 0

lenAll = length(all)
global readings = ""
global lineNr = 1

global prevDoy = ""
function Doy(doy)
    if doy == prevDoy
        return "   "
    end
    global prevDoy = doy
    return doy
end
global TodOy = ""

for i = 0 : lenAll - 1
    nxt = all[lenAll - i]
    s = tryparse(Int32, nxt[21:23])
    d = tryparse(Int32, nxt[25:26])
    ThisDoy = nxt[34:37]
    if get(EODs,ThisDoy, ITEM("X", "X")) == ITEM("X", "X")
        EODs[ThisDoy] = [ITEM(s,d)]
    else 
        push!(EODs[ThisDoy], ITEM(s,d))
    end 
    Doy_OUT = Doy(ThisDoy)

#   +  2022-12-29 07:32  160 60 74  0363=

    if i < displayCt
        RT = ""
        RTX = ""
        if lineNr == 1
            RT = "LINE1"
            global Todoy = Doy_OUT
        elseif lineNr == 2 
            if Doy_OUT != "   " 
                RTX = "                          LINE2"
            else
                RT = "LINE2"
            end
        end
        global lineNr = lineNr + 1
        global readings *= RTX * (Doy_OUT == "   " ? "" : "\n") * "    " * nxt[21:32] * " " * nxt[14:18] * 
                    " " * (Doy_OUT == "   " ? "   " : LO_GRAY * Doy_OUT * HI_END) * RT * "\n"
        if s > hiS
            global hiS = s
        end
        if s < loS
            global loS = s
        end

        if d > hiD
            global hiD = d
        end
        if d < loD
            global loD = d
        end
    end


    if Qct < 32
        global SQ32 = pushDown(s,SQ32)
        global DQ32 = pushDown(d,DQ32)
        global Qct += 1
    end

    if Todoy == ThisDoy
        global ThisDayTotS += s
        global ThisDayTotD += d
        global LenThisDay += 1
    end
end

function hilite(nbr, clr)
    nbrS = string(nbr)
    return replace(readings, "X" * nbrS => "X" * clr * nbrS * HI_END)
end

global readings = replace(readings, r"\n    ([0-9]{3}) " => s"\nX\1X")

function fmtItm(num)
    a = "        " * string(round(num, digits = 1))
    lena = length(a)
    return a[lena - 4: lena]
end

HI_ = HI_RED
LO_ = HI_AQUA

global readings = hilite(hiS, HI_)
global readings = hilite(hiD, HI_)

global readings = hilite(loS, LO_)
global readings = hilite(loD, LO_)

avgS = formatDecimal(sum(SQ32) / Qct, 2)
avgD = formatDecimal(sum(DQ32) / Qct, 2)

dd = fmtItm(ThisDayTotS / LenThisDay) * fmtItm(ThisDayTotD / LenThisDay)

readings = replace(readings, "LINE1" => "   "  * dd * "    d: " * HI_ * "MAAAS" * " "  * "MAAAD" * HI_END * "  %%S%%   i: " *  avgS )
readings = replace(readings, "LINE2" => "                     " * LO_ * "MINMINS" * " "  * "MINMIND" * HI_END * "   %%D%%       " *  avgD *  
            "   ( " * formatFixed(string(length(all))) * LO_GRAY *  " #:" * string(IgnoredLines) * ".  " *
                    formatFixed(stat("w/txts/BP").size) * " v" * version * HI_END * " )")

# This was just too goddamned much no-fucking work!
shit = Regex("(\\d{4})" * "(\\033\\[0m\\n)" )
readings = replace(readings, shit => s"\1Y\2")
x = findall(r"\d{4}Y", readings)
global fux = Dict()
for itm in x
    ri = readings[itm]
    rim = EODs[ri[1:4]]
    s = 0
    d = 0
    for itm2 in rim
        s += itm2.s
        d += itm2.d
    end
    lenRI = length(rim)
    aaa = string(round(s/lenRI, digits = 1)) * " " * string(round(d/lenRI, digits = 1 ))
    global fux[ri] = ri[1:4] * "   " * aaa
end
for f in keys(fux)  
    global readings = replace(readings,f => fux[f], count = 1)
end

#println("\n    " * HI_ * string(MaxMaxS) * " "  * string(MaxMaxD) * HI_END)
#println("    " * LO_ * string(MinMinS) * " "  * string(MinMinD) * HI_END * 
#            "      (" * string(length(all)) * LO_GRAY *  " #" * string(IgnoredLines) * HI_END * ")")

EODkeys = []
global data = ""
k = []
for kk in keys(EODs)
    push!(EODkeys, String(kk))
end
global prevDT = ""
X = sort(EODkeys, rev=true)

global Rct = 0
global SR32 = zeros(Float64,32)
global DR32 = zeros(Float64,32)

#print(replace(readings, r"X([^X]+)X" => s"    \1 "))

for itm in X
    s = 0.0
    d = 0.0
    for itm2 in EODs[itm]
        s += itm2.s
        d += itm2.d
    end
    len = length(EODs[itm])
    dt = replace(string(Day(tryparse(Int32, itm) - 1) + Date("2023")), "-" => ".")
    if dt[1:5] == prevDT
        dt = "     " * dt[6:length(dt)]
    else
        global prevDT = dt[1:5]
    end

    if Rct <32


        for itm2 in EODs[itm]
            if itm2.s > MAAAS 
                global MAAAS = itm2.s
            end
            if itm2.s < MINMINS 
                global MINMINS = itm2.s
            end
            if itm2.d > MAAAD 
                global MAAAD = itm2.d
            end
            if itm2.d < MINMIND 
                global MINMIND = itm2.d
            end
        end

        global SR32 = pushDown(s/len,SR32)
        global DR32 = pushDown(d/len,DR32)
        global Rct += 1
    end

    global data *= "    " * dt *
                 "   " * string(round(s/ len, digits = 1)) * "  " * string(round(d / len, digits = 1)) * "\n"
end

#println("S: ", SR32, "\nD: ", DR32, "\nct: ", Rct)

S = formatDecimal(sum(SR32)/ Rct, 2)
D = formatDecimal(sum(DR32)/ Rct, 2)

for itm in ("MAAAS", "MAAAD" , "MINMINS", "MINMIND")
    EMP("global readings = replace(readings, \"" * itm * "\" => string(" * itm * "))")
end    

a = open("BP.txt", "w")
write(a, data)
close(a)

#println("   avgS: " , avgS, ".  avgD: ", avgD, "'")

global readings = replace(readings, "%%S%%" => S)
global readings = replace(readings, "%%D%%" => D)

print(replace(readings, r"X([^X]+)X" => s"    \1 "))

