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

proc tixAutoMkIndex {dir args} {
    global errorCode errorInfo
    set oldDir [pwd]
    cd $dir
    set dir [pwd]
    append index "# Tcl autoload index file, version 2.0\n"
    append index "# This file is generated by the \"tixindex\" program,\n"
    append index "# *NOT* by the \"auto_mkindex\" command,\n"
    append index "# and sourced to set up indexing information for one or\n"
    append index "# more commands.  Typically each line is a command that\n"
    append index "# sets an element in the auto_index array, where the\n"
    append index "# element name is the name of a command and the value is\n"
    append index "# a script that loads the command.\n\n"
    foreach file [eval glob $args] {
	set f ""
	set error [catch {
	    set f [open $file]
	    while {[gets $f line] >= 0} {
		if [regexp {^tixClass[ 	]+([^ 	]*)} $line match className] {
		    append index "set [list auto_index($className)]"
		    append index " \"source {\$dir/$file}\"\n"
		    append index "set [list auto_index($className:AutoLoad)]"
		    append index " \"source {\$dir/$file}\"\n"
		    set isClass($className) 1
		}
		if [regexp {^tixWidgetClass[ 	]+([^ 	]*)} $line match className] {
		    append index "set [list auto_index($className)]"
		    append index " \"source {\$dir/$file}\"\n"
		    append index "set [list auto_index($className:AutoLoad)]"
		    append index " \"source {\$dir/$file}\"\n"
		    set isClass($className) 1
		}

		if [regexp {^proc[ 	]+([^ 	]*)} $line match procName] {
		    set prefix [lindex [split $procName :] 0]
		    if {![info exists isClass($prefix)]} {
			append index "set [list auto_index($procName)]"
			append index " \"source {\$dir/$file}\"\n"
		    }
		}
	    }
	    close $f
	} msg]
	if $error {
	    set code $errorCode
	    set info $errorInfo
	    catch {close $f}
	    cd $oldDir
	    error $msg $info $code
	}
    }
    set f [open tclIndex w]
    puts $f $index nonewline
    close $f
    cd $oldDir
}

if {$argv == {}} {
    eval tixAutoMkIndex . *.tcl
} else {
    eval tixAutoMkIndex . $argv
}
