#!/usr/bin/env tclsh
# vim:se syn=tcl:

set filename [lindex $argv 0]
set f [open $filename]

# Read the file looking for command definitions
set lines {}
set commands {}
array set cdict {}
set c 0

while {[gets $f buf] >= 0} {
	if {[string match "~~*" $buf]} {
		if {[string match "*: *" $prev]} {
			incr c
			set target cmd_$c
			set lines [linsert $lines end-1 "\[\[$target\]\]"]
			set prevlist [split $prev ", "]
		} else {
			set target _[string map {:: _} $prev]
			set prevlist [list $prev]
		}
		foreach cmd $prevlist {
			set cmd [string trim $cmd :]
			if {[regexp {^[a-z.:]+$} $cmd]} {
				lappend commands [list $cmd $target]
				set cdict($cmd) $target
			}
		}
	}
	lappend lines $buf
	set prev $buf
}
close $f

# Build the command index in the list: $index
lappend index {[frame="none",grid="none"]}
lappend index {|=========================}
set i 0
set row {}
foreach command [lsort $commands] {
	lassign $command cmd target

	append row "|<<$target,*`$cmd`*>> "
	incr i
	if {$i % 8 == 0} {
		lappend index $row
		set row {}
	}
}
while {$i % 8 != 0} {
	incr i
	append row "| "
}
lappend index $row
lappend index {|=========================}

# Map all `cmd` to <<$target,`cmd`>>
set mapping {}
foreach c [array names cdict] {
	lappend mapping `$c` <<$cdict($c),*`$c`*>>
	lappend mapping "`$c " "<<$cdict($c),*`$c`*>> `"
}

# And the command index
lappend mapping @INSERTINDEX@ [join $index \n]

# Output the result
foreach line $lines {
	if {[string first ` $line] >= 0 || [string first @ $line] >= 0} {
		puts [string map $mapping $line]
	} else {
		puts $line
	}
}
