#!/bin/sh
#$1 => $2 ; $3,$4 ... contain the include path

if [ $# -lt 2 ]
then
	echo fpp file1 file2 [ include_path ... ]
	exit 1
fi

export number_of_recurse 
number_of_recurse=`expr ${number_of_recurse:-0} + 1`
if [ $number_of_recurse -gt 50 ]
then
	exit 1
fi

inputfile=$1 ; outputfile=$2

test ! -f $inputfile && echo "fpp:can't open $inputfile" && exit 2

str=`@AWK@  ' $1 ~ "[Ii][Nn][Cc][Ll][Uu][Dd][Ee]" {
	if ( $2 !~ /\".*\"/  && $2 !~ /'"'"'.*'"'"'/ )
	{
		printf "%s:%d: %s\n","'$inputfile'",NR,"unterminated string or character constant !!" 
		exit 2
	}
	printf "%d %s ",NR,substr($2,2,length($2)-2) 
} '  $inputfile `
test $? != 0 && echo $str && exit 2
test "x$str" = x && exit 1

cp $inputfile $outputfile
shift ; shift

count=0  

for i in $str
do 
count=`expr $count + 1`
test `expr $count % 2` -ne 0 && lineno=$i && continue
filenm=$i
if [ ! -f $filenm ]
then
	for incdir
	do test -f $incdir/$filenm && filenm=$incdir/$filenm && break ; done
	test "$filenm" = "$i" && echo $inputfile:$lineno: $filenm: No such file or directory && exit 2
fi 
#no=1 ; tmp1=`@MKTMP@`
tmp1=`echo ${outputfile}~1`
#   recursively expand the include file
/bin/sh $0 $filenm $tmp1 $*
status=$?
test $status = 1 && tmp1=$filenm
test $status -gt 1 && exit $status
lno=`sed -n -e "/^[ 	]*[Ii][Nn][Cc][Ll][Uu][Dd][Ee]/ {=; q;}" $outputfile`
#no=2 ; tmp2=`@MKTMP@`
tmp2=`echo ${outputfile}~2`
sed -e "$lno {s&^.*$&#  $lineno \"$filenm\"&;a\\
#  $lineno \"$inputfile\"\\

}" $outputfile   |
sed -e "$lno r $tmp1"    > $tmp2
mv -f $tmp2 $outputfile
test $status = 0 && rm -f $tmp1
done

exit 0

