#!/afs/ece/usr/tcl/bin/wish -f
# The next line is executed by most shells, but not Tcl \
wish $0 $*


# To run this program, you should make sure the top line reflects the location
# of wish on your system, and the following variables represent the locations
# of elsbeth and an rgb.txt file to look at.

# File with list of colors in format "[red][green][blue]	[name]"
set Color_File "/usr/lib/X11/rgb.txt"
# Location of Elsbeth source directory.
set Elsbeth_Dir [file dirname [file dirname [info script]]]

# Takes [-o starting_color] and [-a] as an optional argument. Any other
# arguments get passed to Elsbeth. If no starting color is given, defaults to
# first one in file. Tkcolors colors each line with its own color, until the end
# of the page. Scrolling the text re-does the coloring, so the screen is always
# full of colors. (this prevents the program from running out of colors.)
#
# if [-a] is called, then only els is invoked, not elsbeth.


if {[set index [lsearch $argv -o]] != -1} {
  set sc [expr $index + 1]
  set color_start [lindex $argv $sc]
  set argv [lreplace $argv $index $sc]
  incr argc -2
} else {set color_start ""}

if {[set index [lsearch $argv -a]] >= 0} {
  lappend argv $Color_File ; incr argc
  source $Elsbeth_Dir/bin/els
} else {
  lappend argv -a $Color_File
  incr argc 2
  source $Elsbeth_Dir/bin/elsbeth
}

wm title .syme1 "THColors"
wm iconname .syme1 "THC"
set Text .syme1.t

# Go to color specified by argv
if {($color_start != "")} {
  set char [string first "\t$color_start\n" [$Text get 1.0 end]]
  scan [$Text index "1.0 +$char chars"] "%d" color_line
} else {set color_line 1}
$Text mark set insert $color_line.0  ; $Text see insert
set top_line $color_line.0

proc allocate_colors {w} {
  scan [$w index @0,[winfo height $w]] "%d.%d" endline dummy
  set line [$w index @0,0]
  set limit [expr $endline - $line]
  for {set c 0} {$c <= $limit} {incr c} {
    set tabend "$line +[string last "\t" [$w get $line "$line lineend"]] chars +1 chars"
    set tabstart "$tabend -2 chars"
    set color [$w get $tabend "$tabend lineend"]
    $w tag add tag$c $tabstart $tabend
    $w tag add Color $tabstart $tabend
    $w tag configure tag$c -background $color
    set line [$w index "$line +1 line"]
}}

proc deallocate_colors {w} {
  set color_tags ""
  scan [$w index @0,[winfo height $w]] "%d.%d" endline dummy
  set line [$w index @0,0]
  set limit [expr $endline - $line]
  for {set c 0} {$c <= $limit} {incr c} {
    lappend color_tags tag$c
  }
  eval $w tag delete $color_tags
}

proc redo_colors_and_scroll {args} {
  global Text top_line frame
  if {[winfo exists .syme1.s]} {eval .syme1.s set $args}
  if {$top_line != [$Text index @0,0]} {
    set top_line [$Text index @0,0]
    deallocate_colors $Text
    allocate_colors $Text
}}

if {[set ycmd [$Text cget -yscrollcommand]] == ""} {set ycmd "# "} else {
  bind Text <Meta-q> {els_destroy_text %W}
}
$Text configure -yscrollcommand "redo_colors_and_scroll ; $ycmd"
allocate_colors $Text
