# Takes a doctools generated idx file and creates a htf index page.

# Define the commands to implement the commands in the file

proc index_begin args {}
proc index_end args {}
proc key keyword {
    set ::current_keyword $keyword
    return
}
proc manpage {filename description} {
    set filename [file rootname $filename].html
    set char [string toupper [string index $::current_keyword 0]]
    lappend ::index($char) [list $::current_keyword $filename $description]
    return ""
}

proc write_index_entry {entry} {
    foreach {keyword filename description} $entry break
    if {$description eq ""} {
        set description $keyword
    }
    set href [string map {" " ""} $keyword]; # Remove spaces
    puts "<tr><td>$keyword</td><td><a href='$filename#$href'>$description</a></td></tr>\n"
}

#
# Processing being here
#

# Array indexed by alphabet
array set index {}

# Open the first argument as a index file generated by dtp
set fd [open [lindex $argv 0]]
set data [read $fd]
close $fd


# Eval the file - should really be in a safe interpreter! TBD
subst $data

# Header
puts "<h2>Index</h2>"

# Write shortcut links to alphabets
puts "<p>"
foreach c [split ABCDEFGHIJKLMNOPQRSTUVWXYZ ""] {
    puts "<a href='#$c'>$c</a> "
}
puts "</p>"

# Write the entries in the index
puts "<table summary='Index' class='index'>"
# puts "<colgroup><col class='indexkeyword'/><col class='indexlink'/></colgroup>"
foreach c [split ABCDEFGHIJKLMNOPQRSTUVWXYZ ""] {
    puts "<tr><td>&nbsp;</td></tr>"
    puts "<tr><td><a name='$c'><span class='indexsection'>$c</span></a></td></tr>"
    puts "<tr><td>&nbsp;</td></tr>"
    if {[info exists index($c)]} {
        foreach entry $index($c) {
            write_index_entry $entry
        }
    }
}
puts "</table>"


