#! /bin/sh

# igawk --- like gawk but do @include processing
# Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
# July 1993

igs=${TMP:-/tmp}/igs$$
ige=${TMP:-/tmp}/ige$$

if [ "$1" = debug ]
then
    set -x
    shift
else
    # cleanup on exit, hangup, interrupt, quit, termination
    #trap 'rm -f $igs $ige' 0 1 2 3 15
    trap 'rm -f $igs $ige' 0 2 15
fi

while [ $# -ne 0 ] # loop over arguments
do
    case $1 in
    --)     shift; break;;

    -W)     shift
            set -- -W"$@"
            continue;;

    -[vF])  opts="$opts $1 '$2'"
            shift;;

    -[vF]*) opts="$opts '$1'" ;;

    -f)     echo @include "$2" >> $igs
            shift;;

    -f*)    f=`echo "$1" | sed 's/-f//'`
            echo @include "$f" >> $igs ;;

    -?file=*)    # -Wfile or --file
            f=`echo "$1" | sed 's/-.file=//'`
            echo @include "$f" >> $igs ;;

    -?file)    # get arg, $2
            echo @include "$2" >> $igs
            shift;;

    -?source=*)    # -Wsource or --source
            t=`echo "$1" | sed 's/-.source=//'`
            echo "$t" >> $igs ;;

    -?source)  # get arg, $2
            echo "$2" >> $igs
            shift;;

    -?version)
            echo igawk: version 1.0 1>&2
            gawk --version
            exit 0 ;;

    -[W-]*)    opts="$opts '$1'" ;;

    *)      break;;
    esac

    shift
done

if [ ! -s $igs ]
then
    if [ -z "$1" ]
    then
         echo igawk: no program! 1>&2
         exit 1
    else
        echo "$1" > $igs
        shift
    fi
fi

# at this point, $igs has the program
gawk -f igawk.awk $igs > $ige
eval gawk -f '$ige' $opts -- "$@"

exit $?
