#!/bin/sh

. sh/tools.sh
. sh/verbose.sh
. sh/ac.sh

if [ -z "$1" ]
then
    echo 1>&2 "$0:  *** error"
    exit 1
fi

get_dep ()
# $1:  file to read
# $get_dep_list:  result
{
    get_dep_list="`grep '^# *include *\"' $1 \
       | $sed 's/^# *include *\"\([a-z0-9_]*\)\...\".*$/\1/g' \
       | $sed 's/^#.*$//g' `"
}

modules=

pending="`cat bin/$1.group-programs` hello"

echo 1>&4 $ac_n "Generating module list$ac_c"

while [ "$pending" ]
do
    new_pending=
    for module in $pending
    do
	echo 1>&4 $ac_n .$ac_c
	modules="$modules $module"
	if [ -r src/$module.cc ]
	then
	    get_dep src/$module.cc
	    new_pending="$new_pending $get_dep_list"
	    new_pending="$new_pending `grep '^ *\/\* *Needs: *[a-z_]* *\*\/ *$' src/$module.cc | \
	        $sed 's/^ *\/\* *Needs: *\([a-z_]*\) *\*\/ *$/\1/g'`"
	fi
	if [ -r src/$module.hh ]
	then
	    get_dep src/$module.hh
	    new_pending="$new_pending $get_dep_list"
	fi
	if [ -r src/test_$module.cc ]
	then
	    new_pending="$new_pending test_$module"
	fi
    done
    pending=
    for module in $new_pending
    do
	echo 1>&4 $ac_n .$ac_c
	if echo "$modules" | grep -vw $module >/dev/null
	then
	    if echo "$pending" | grep -vw $module >/dev/null
	    then
		pending="$pending $module"
	    fi
	fi
    done
done

echo $modules

echo 1>&4 

exit 0
