#!/bin/bash

TMPFILE=/tmp/orca-macgen.$$

MACGENFLAGS="$1"
FILENAME="$2"
shift
shift

if echo $FILENAME | grep -v '\.s$' > /dev/null
then
    echo Expected second argument to be a *.s file but got $FILENAME
    exit 1
fi

BASENAME=`echo $FILENAME | sed 's/\.s$//'`
MACROSNAME="${BASENAME}.macros"
DEPSNAME="${MACROSNAME}.d"

$ORCA --trace-gsos macgen $MACGENFLAGS "$FILENAME" $* < /dev/null 2> $TMPFILE
RESULT=$?

sed '/^[A-Za-z][A-Za-z]*(.*)$/d' $TMPFILE >&2

if [ "$RESULT" -ne 0 ]
then
    rm -f $TMPFILE
    rm -f $MACROSNAME
    exit $RESULT
fi

DEPS=`awk '
    /^FastFileLoad/ {
        sub(/^FastFileLoad\(/, "");
        sub(/\)$/, "");
        print}' $TMPFILE | sort -u | while read FILE
    do
        if [ -f "$FILE" ]
        then
            echo $FILE
        fi
    done | tr '\012' ' '`

rm -f $TMPFILE

cat > $DEPSNAME << EOF
$MACROSNAME: $DEPS
EOF

exit 0
