#!/bin/sh
#-------------------------------------------------
# MathLink template compiler
#-------------------------------------------------

if [ -z "$CC" -o "$CC" = "`basename "$0"`" ] ; then
    CC=cc
fi

spath=`expr "$0"'/' : '\(/\)[^/]*//*$' \| "$0"'/' : \
            '\(.*[^/]\)//*[^/][^/]*//*$' \| .`

if [ "." = "$spath" ]; then
   MLPATH=`pwd`
else
   if [ ".`(echo $spath | grep \"^/\")`" = ".$spath" ]; then
      MLPATH="$spath"
   else
      MLPATH="`pwd`/$spath"
   fi
fi

sysid=DEC-AXP
extracc=-pthread

topdir=`\cd "$MLPATH"; pwd`

mlbinary=$topdir
mlinclude=$topdir
mllibrary=$topdir
mloutfile=""

myname="$0"
outfile="-o a.out"

cnt=$#
while [ $cnt != 0 ]
do
    case ".$1" in
        .-E|.-P)   # preprocess only, filename
            passtocc="$passtocc $1"
            outfile=""
            ;;

        .-c)       # save dot o files
            passtocc="$passtocc $1"
            savedotos=1
            outfile=""
            ;;

        .-o)       # output filename
            if [ ".$2" = "." ] ; then
                echo "$myname: -o option but no filename"
                exit 1
            else
                outfile="-o $2";
                cnt=`expr $cnt - 1`
                shift
            fi
            ;;

        .-xo)
            if [ ".$2" = "." ] ; then
                echo "$myname: -xo option but no filename"
                exit 1
            else
		[ ! -d "$2" ] && mkdir $2 > /dev/null 2>&1
		[ ! -d "$2/$sysid" ] && mkdir "$2/$sysid" > /dev/null 2>&1
                outfile="-o $2/$sysid/$2";
                if [ ! -d $2 ] ; then
                	echo "Error creating the directory \"$2\" because the file \"$2\" already exists."
                	exit 1
                fi
                cnt=`expr $cnt - 1`
                shift
            fi
            ;;

        .-g)       # want to keep generated files after mpreping
            passtocc="$passtocc $1"
            debug=1
            ;;

        .*.tm)      # make a list
            if [ ".$mloutfile" = "." ] ; then
                mloutfile=$1
            fi
            mlfiles="$mlfiles $1"
            ;;

        .*)        # pass through to cc
            passtocc="$passtocc $1"
            ;;
    esac

    cnt=`expr $cnt - 1`
    shift

done

if [ ".$mloutfile" != "." ] ; then
   "$mlbinary"/mprep $mlfiles -o $mloutfile.c
   mlteddotofiles="$mlteddotofiles $mloutfile.o"
   passtocc="$passtocc $mloutfile.c"
fi

   $CC $outfile -I"$mlinclude" $passtocc $extracc -L"$mllibrary" -lML -lm -lrt

if [ ".$mloutfile" != "." ] ; then
    if [ ".$debug" = "." ] ; then
      rm -f $mloutfile.c
    fi
    if [ ".$savedotos" != ".1" ] ; then
        rm -f $mlteddotofiles
    fi
fi
