#!/usr/bin/tclsh

if {$argc != 2} {
    puts "Usage: [file tail [info script]] <input sgml file> <output messages>"
    exit
}

set ifile [lindex $argv 0]
set ofile [lindex $argv 1]

# read SGML file
set buff [exec cat $ifile]
while {1} {
    # find target
    set from [string first "<" $buff]
    set to   [string first ">" $buff]
    if {$from == -1 || $to == -1} {break}
    regexp {<[!a-zA-Z]+} $buff name
    set name [string range $name 1 end]
    # skip this target up to end
    switch -- $name {
	verb {
	    # skip this target
	    if {![regexp -nocase -indices "</verb>" $buff indices]} {
		puts "Unclosed $name target"
		exit
	    }
	    set buff [string range $buff [expr [lindex $indices 1]+1] end]
	    continue
	}
    }
    set buff [string range $buff [expr $to+1] end]
    # find message
    set from [string first "<" $buff]
    if {$from != -1} {
	set message [string range $buff 0 [expr $from-1]]
	set lmessage [split $message "\n\t "]
	set message ""
	foreach item $lmessage {if {$item != ""} {lappend message $item}}
	set message [join $message " "]
	if {$message != ""} {
	    # change " symbols
	    set message [join [split $message "\""] "\\\""]
	    if {[string length $message] > 60} {
		set tmsg $message
		set message ""
		while {$tmsg != ""} {
		    if {[string length $tmsg] > 60} {
			set end  [string wordend $tmsg 60]
			set appd [string range $tmsg 0 $end]
			append message "\"[string trim $appd]\"\n"
			set tmsg [string range $tmsg [expr $end+1] end]
		    } {
			append message "\"[string trim $tmsg]\""
			set tmsg ""
		    }
		}
	    } {
		set message "\"$message\""
	    }
	    puts "msgid $message"
	    puts "msgstr \"\"\n"
	}
    }
}
