#!/bin/sh
# the next line restarts using the interpreter \
exec tclsh "$0" "$@"

set package [lindex $argv 0]
set contentsVariable [lindex $argv 1]
set dataVariable [lindex $argv 2]

# remove paragraph tags that follow a closing header tag since that generates in an extra ugly new line:
regsub -all {(</[hH]\d>\s*)<p>} [read stdin] {\1} data
set lines [split $data \n]

# first gather contents section
set index 0
foreach line $lines {
    incr index
    if {[string match {*<!-- beginning of contents -->*} $line]} break
}
if {[string length $package] > 0} {
    if {\
        ([info exists ::env(LC_ALL)] && [string match ja* $::env(LC_ALL)]) ||\
        ([info exists ::env(LANG)] && [string match ja* $::env(LANG)])\
    } {
        puts "package provide $package-ja 1.0"
    } else {
        puts "package provide $package 1.0"
    }
}
puts "set $contentsVariable \{"
puts <html><body>
foreach line [lrange $lines $index end] {
    incr index
    if {[string match {*<!-- end of contents -->*} $line]} break
    puts $line
}
puts "</body></html>}"

# then collect remaining data
puts "set $dataVariable \{"
puts <body><html>
foreach line [lrange $lines $index end] {
    puts $line
}
puts \}
