#!/bin/sh
#set -x
gen_c=init_ltcl.c
tmp_h=tmp_lctl.h
gen_h=ltcl.h
prefix=ltcl


C () {
    echo "$*" >> $gen_c
}
H () {
    echo "$*" >> $tmp_h
}

for i in $*; do
    case $i in
    -p) 
	gen_c=init_$2.c
	tmp_h=TMP.$2.h
	gen_h=$2.h
	prefix=$2
	shift 2
	;;
    --)
	shift
	break
	;;
    esac
done

rm -f $gen_c $gen_h

C "/* $gen_c : generated by build_cmd, do not edit */"

C ''
C "#include <stdio.h>"
C "#include <tkInt.h>"
C "#include <tcl.h>"
C "#include \"$gen_h\""
C ''

C 'int'
C init_"$prefix"\(interp\)
C 'Tcl_Interp *interp;'
C '{'

while read i; do
  if [ X"$i" != X ]; then
    set $i
    case "$1" in
    "extern"|"typedef")
	H "$i"
	;;
    "#include"*)
	H "$i"
	;;
    "##"*)
	C '/*'"$i"	'*/'
	;;
    "#"[a-z]*)
	C "$i"
	;;
    "#"*)
	;;
    "")
	;;
    *)
	# a line with data...
	# $1 is the name for the tcl proc
	#
	tclname=$1

	#
	# $2 is the name of the C routine to use for the tcl proc
	# if it is "-" then call it the same name as the tcl proc
	# with Cmd tacked on the end
	#
	case "$2" in
	"-")
	    cname="tcl_"$1"Cmd"
	    ;;
	*)
	    cname="$2"
	    ;;
	esac

	# client data handle name (if any)
	if [ X$3 = X ]; then
	    data=NULL
	else
	    data="$3"
	fi

	if [ X$4 = X ]; then
	    destroyfuncp=NULL
	else
	    case "$4" in
	    "-")
		destroyfuncp="tcl_"$1"DestroyCmd"
		;;
	    *)
		destroyfuncp="$4"
		;;
	    esac
	fi
	C "	Tcl_CreateCommand(interp, \"$tclname\", $cname,"
	C "		(ClientData) $data, (void (*)()) $destroyfuncp);"

	H "extern int" $cname"(/* */);"
	if [ $destroyfuncp != NULL ]; then
	    H "extern void $destroyfuncp"'(/* ClientData cdata */);'
	fi
	;;
    esac
  fi
done

C ''
C '	return 0;'
C '}'

# now sort the header file to get rid of duplicate entries
echo "/* $gen_h : generated by build_cmd, do not edit */" >$gen_h
echo "" >>$gen_h
sort -u <$tmp_h >>$gen_h
rm -f $tmp_h
