package require shellfilter
interp alias {} a+ {} shellfilter::ansi::+

#lassign $argv head
set args [lassign $::argv target]
puts stdout "::argv  '$::argv'"
puts stdout "target:'$target' args:'$args'"
if {![string length $target]} {
    set target stdout
}
if {([llength $args] % 2) != 0} {
    puts stderr "Usage [info script] \[targetfile|stderr|stdout\] -format html|ansi"
    flush stderr
    error 1
}
set defaults [dict create \
    -format ansi\
    ]
    
set opts [dict merge $defaults $args]
set format [string tolower [dict get $opts -format]]

set known_formats [list "ansi" "html"]
foreach f $format {
    if {$f ni $known_formats} {
        puts stderr "Unrecognized -format $f"
        flush stderr
        error 2
    }
}

while { [gets stdin line] >= 0 } {
    lappend fileLines $line
    foreach word [regexp -all -inline {[A-Za-z0-9]+} $line] {
        dict incr wordcount [string tolower $word]
    }
}

if {$target in {stdout stderr}} {
    set fp $target
} else {
    set fp [open "$target" w]
}

if {"html" in $format} {
    puts $fp "<html>"
    puts $fp "<head><title>onlies</title></head>"
    puts $fp "<body>"
    foreach line $fileLines {
        set text "<pre>"
        set strLength [string length $line]
        for {set i 0} {$i < $strLength} {} {
            if {![string is alnum [string index $line $i]]} {
                append text [string index $line $i]
                incr i
            } else {
                set word [regexp -inline {[A-Za-z0-9]+} [string range $line $i end]]
                if {[dict exists $wordcount $word] && [dict get $wordcount $word] == 1} {
                    append text "<span style=background-color:yellow>" $word "</span>"
                } else {
                    append text $word
                }
                incr i [string length $word]
            }
        }
        append text "</pre>"
        puts $fp $text
    }
    puts $fp "</body>"
    puts $fp "</html>"
} 
if {"ansi" in $format} {
    set highlight [a+ yellow bold]
    foreach line $fileLines {
        set text ""
        set strLength [string length $line]
        for {set i 0} {$i < $strLength} {} {
            if {![string is alnum [string index $line $i]]} {
                append text [string index $line $i]
                incr i
            } else {
                set word [regexp -inline {[A-Za-z0-9]+} [string range $line $i end]]
                if {[dict exists $wordcount $word] && [dict get $wordcount $word] == 1} {
                    append text "$highlight" $word "[a+]"
                } else {
                    append text $word
                }
                incr i [string length $word]
            }
        }
        puts $fp $text
    }
}

    
if {$target ni {stdout stderr}} {
    close $fp
}