#!/bin/sh

INCPATH=.
FILES=''

expandfile() {
	for i in $INCPATH
	do
		if [ -f $i/$1 ] 
		then
			echo $i/$1
			exit 0
		fi
	done
	echo "Error: Include file \`$1' does not exist" > /dev/stderr
#	echo "Fehler: Includedatei $1 existiert nicht" > /dev/stderr
	exit 1
}

findincludes() {
	for i in $*
	do
		for j in `sed -n 's/^#[Ii][Nn][Cc][Ll][Uu][Dd][Ee] *[<"]\([^>"]*\).*/\1/p' $i` \
			 `sed -n 's/^#[Rr][Ee][Aa][Dd] *[<"]\([^>"]*\).*/\1/p' $i`
		do
			echo ' \'
			foo=`expandfile $j`
			echo -n ' '$foo
			findincludes $foo
		done
	done
}

while [ "x$1" != "x" ]
do
	case "$1" in
		-I*)
			INCPATH=$INCPATH' '${1##-I}
			#INCPATH=$INCPATH' '$(1)
			;;
		*)
			FILES=$FILES' '$1
			;;
	esac
	shift
done

addmenu() {
	root_prefix=`perl -MCwd -e '$_ = cwd;s/^.*src\/?//;@f=split /\//;$n=$#f+1;print "../"x $n;'`
	menu_prefix=${root_prefix##../}

	if [ -f ${menu_prefix}menu.def ]
	then
		echo ' \'
		echo -n ' '${menu_prefix}menu.def
	fi
}

export INCPATH
export FILES

for i in $FILES
do
	echo -n `echo $i | sed 's/.wml/.html/'`: $i
	findincludes $i
	addmenu
	echo
done
