#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"
#generate final tcl/tk script as follows
# 1. write start lines as above
# 2. write version using first arg
# 3. copy everything from second argument (the tcl file)
# 4. append the man file (after conversion) using third argument

# 1. start lines
puts "#!/bin/sh"
puts "# the next line restarts using wish \\"
puts "exec wish \"\$0\" \"\$@\""

# 2. version info
set input [ open [ lindex $argv 0 ] "r" ]
set version [ gets $input ]
close $input
puts "set TKAlbumVersion \"$version\""

# 3. the tcl file 
set input [ open [ lindex $argv 1 ] "r" ]
while { ! [ eof $input ] } {
    set line  [ gets $input ]
    if { [ eof $input ] } {
       break
    }
    puts $line
}
close $input

#4. append the man file 
set input [ open "| man -l [ lindex $argv 2 ] -Tascii" ]
puts "proc FillManualPage \{ w \} \{"
puts "\$w.text tag configure bold -font \{Courier 12 bold\}"
puts "\$w.text tag configure underline -underline on"
puts "\$w.text insert end \{"
set counter 0
while { ! [ eof $input ] } {
    set line  [ gets $input ]
    if { [ string first "\b" $line ] == -1 } {
	puts "$line"
    } else {
	set ix [ string first "\b" $line ] 
	while { $ix != -1 } {
	    puts "[string range $line 0 [ expr $ix - 2 ]]\}"
	    set line [ string range $line [ expr $ix - 1 ] end ]
	    set word ""
	    if { [ string index $line 0 ] == "\_" } {
		while { [ string index $line 0 ] == "\_"  && \
			    [ string index $line 1 ] == "\b" } {
		    append word [ string index $line 2 ]
		    set line [ string range $line 3 end ]
		}
		puts "\$w.text  insert end \{$word\} underline"
	    } else {
		while { [ string index $line 1 ] == "\b" } {
		    append word [ string index $line 2 ]
		    set line [ string range $line 3 end ]
		}
		puts "\$w.text  insert end \{$word\} bold"
	    }
	    puts -nonewline "\$w.text insert end \{"
	    set ix [ string first "\b" $line ] 
	}
	puts "$line"
    }
    incr counter
}
puts "\}\}"
exit


