#! /usr/bin/tclsh

set rows 0
set cols 0

set infile [open $argv r]
set outfile [open ${argv}.tei w]

proc output { text } {
    global outfile
    puts -nonewline $outfile $text
}

proc waitFor { pattern } {
    global infile
    while { 1 } {
	set line [gets $infile]
	if { [regexp -- $pattern $line ignored paren] } {
	    return $paren
	}
	if { [eof $infile] } {
	    puts stderr "Unexpected end of file; $pattern was expected"
	    exit 1
	}
    }
}
    
proc repeat { string n } {
    set ret $string
    while { $n > 1 } {
	append ret $string
	incr n -1
    }
    return $ret
}

proc doTable {} {
    waitFor "Table \{"
    global rows cols
    set rows [waitFor ".*NumberOfRows \(\[0-9\]+\).*"]
    set cols [waitFor ".*NumberOfColumns \(\[0-9\]+\).*"]

    doColumnAttrs
    
    output "<table cols='$cols' [doColumnAttrs]>\n"
    for {set row 0} {$row < $rows} {incr row} doRow
    output "\n</table>\n"
}

proc doColumnAttrs {} {
    set rend {}
    global infile cols
    set pos [tell $infile]
    if { $pos == -1 } {
	puts stderr "***WARNING: can't seek, cell alignment might be wrong"
	append rend "[repeat j $cols]"
    } else {
	for {set col 0} {$col < $cols} {incr col} {
	    waitFor "Column $col \{"
	    global cellRend
	    append rend [string range \
			     [string tolower [waitFor ".*Alignment \(\[^ \]*\)"]] \
			     0 0]
	}
	seek $infile $pos
    }
    return " rend='$rend'"
}

proc doRow {} {
    set rowNumber [waitFor "Row \(\[0-9\]+\).*"]
    output "\t<row>\n"
    set cols [waitFor ".*NumberOfCells \(\[0-9\]+\).*"]
    for {set col 0} {$col < $cols} {incr col} {
	set cellText [waitFor ".*Text \"\(.*\)\".*"]
	output "\t\t<cell>$cellText</cell>\n"
    }
    output "\t</row>\n"
}

# -----------

doTable

#Local variables:
#mode: tcl
#End:
