#! /bin/sh
# hp'3/2001 - phpr@snafu.de
# lib4th: find %include-d files, substitute slow nasm -M execution
# $1:filename.asm	$2:/topdir
#	$1: startfile[rel.path+]name
#	$2: abs.path[list] (no trailing "/" & 1st should be base dir for $1)

unset a d f i n o p t x incf dirf

d=
i=

# top file
a=${1}
# dirs in single stg
shift;d=${*}

# strip all filename-'extensions'
o=$(echo $(basename ${a})|cut -d. -f1)
p=$(echo ${d}|cut -d\  -f1)/dep/
[ -d ${p} -a -n "${o}" ]||mkdir ${p}
o=${p}${o}.dep
t=${o}tt

unset p
echo ${a}>${o}

# $1:[localpath+]file $2:path; echo path+file
dirf() {
    local b d p
    [ -z "${1}" ]&&echo ${2}&&return 0
    d=$(dirname ${1})
    b=$(basename ${1})
    p=${2}/${b}
    [ -z "${d}" ]||
    [ "${d}" == "." ]||
    [ "${d}" == "./" ]||
    {
        [ "$(echo ${d}|cut -c1)" = "/" ]&&p=${1}||
	    { $(echo "${d}"|grep "^\./")&&p=${2}$(echo "${d}"|cut -d\. -f2)/${b}||p="${2}/${1}"; }
    }
    echo ${p}
}
# $1:file $2:path
incf() {
    local b d f n p
    [ -n "${1}" ]||return 0
    [ -n "${2}" ]||return 0
    d=$(dirf ${1} ${2});[ -r ${d} ]||return 0
    cat ${d}|cut -d\; -f1|grep 'include "'|cut -d\% -f2|cut -d\" -f2|while read f
    do
	[ -n "${f}" ]||continue;[ -z "$(cat ${o}|grep ${f})" ]||continue
	b=$(basename ${f});d="$(dirname $(dirf ${f} ${2}))"
	n=$(find ${d} -depth -follow ! -type d -name ${b} -print 2>/dev/null)
	[ -n "${n}" ]||n=${f}
	for p in ${n};do echo "${p}">>${t};incf "${p}" "${d}";done
    done
    return 0
}
date > $(dirname ${o})/mupdt.dep
rm -f ${t}
for p in ${d}
do incf "${a}" "${p}";done
[ -z "${t}" ]||cat ${t}|sort|uniq|while read f;do echo "${f} \\">>${o};done
rm -f ${t}
exit 0
# fdinc <eof>
