#!/usr/bin/expect --

proc traceproc {array element type} {
	upvar [set array]($element) var
	puts "new value of [set array]($element) is $var"
}
;#trace variable expect_out w traceproc
#exp_internal 1

proc begin_figure {} {
	puts "\\begin{flushleft}"
	#puts "\\begin{minipage}\[t\]{\\textwidth}"
	puts "\\hrulefill"
	puts ""
	#puts "\\vspace*{-4mm}"
	puts ""
}

proc end_figure {} {
	puts ""
	#puts "\\vspace*{-5mm}"
	puts ""
	puts "\\hrulefill"
	#puts "\\end{minipage}"
	puts "\\end{flushleft}"
}

proc process_cmd {c prompt result} {
	upvar $result res
	upvar $c cdd
	send "$cdd\r"
	log_user 0
	regsub -all "\n" $cdd "\r\n" x
	set cdd $x
	expect {
		timeout {puts "error: command: \n$cdd\n never echoed"; exit}
		"$cdd\r"
	}
	expect {
		timeout { puts "error: command: \n$cdd\n failed"; exit;} 
		-re "(.*)$prompt"
	}
	log_user 1
	set str $expect_out(1,string)
	#regsub -all  {[]#$%&~_^\\\{\}[]}  $str {\\&} x
	regsub -all  {[#$%&~_^\\\{\}]}  $str {\(\\&\)} x
	regsub -all  {[<>]}  $x {\(&\)} res
}

proc output_cmd {cd prompt outp} {
	puts "\\begin{alltt}"
	regsub -all  "\\\r"  $cd "" cx
	regsub -all  "\\\r"  $outp "" ox
	regsub   "\\\n$"  $ox "" ox2
	puts -nonewline "$prompt \{\\bf $cx \}"
	puts "\{\\em\{$ox2\} \}"
	puts "\\end{alltt}"
}

log_user 0
spawn /usr/local/bin/Link
set prompt "STk> "
set timeout 40
expect {
	timeout {puts "error: Link couldn't start up"; exit}
	-re ".*($prompt)"
}
set timeout 25
set output ""

# main loop

if { $argc > 0 } {
        set f [open [lindex $argv 0] r]
} else {
        set f stdin
}
set str [read $f]
set cmd ""
set cmd_ ""
set remainder ""
set echo_output "no"


while {1} {
        regexp {\@([^\@]*)\@} $str cmd_ cmd
        regsub {\@([^\@]*)\@} $str "" remainder
        set str $remainder
        if {[string compare $cmd "(bye)"] == 0} {
                break;
        } elseif {[string compare $cmd "#example"] == 0} {
		begin_figure
		set echo_output "yes"
        } elseif {[string compare $cmd "#endexample"] == 0} {
		end_figure
		set echo_output "no"
        } else {
		process_cmd cmd $prompt output
		if {[string compare $echo_output "yes"] == 0} {
			output_cmd $cmd $prompt $output
		}
        }
}


log_user 0

send "(bye)\r"
