#! /bin/sh

sed=`(echo "sed" | sed -e 's/sed/des/') 2> /dev/null`
if [ x"$sed" != 'xdes' ] ; then
	echo ""
	echo "I could not find the program 'sed' on your system."
	echo "This program is needed for 'compile' to work and it"
	echo "should be installed by default on every Unix system."
	echo "Please install the program 'sed' before continuing."
	echo ""
	exit
fi

if [ x"$1" = "x-64" ] ; then
    arch=64
	shift
elif [ x"$1" = "x-32" ] ; then
    arch=
	shift
else
    arch=`uname -m`
    if [ x"$arch" = "xx86_64" ] ; then
        arch=64
    else
        arch=
    fi
fi


if [ x"$1" = 'x' -o x"$1" = "x-h" -o x"$1" = "x-?" -o x"$1" = "x--help" ] ; then
	echo ""
	echo "Usage: ./compile [-32|-64] <script name>"
	echo " e.g.: ./compile plugin_base.sma"
	echo ""
	exit
fi

if [ ! -f $1 ] ; then
	echo ""
	echo "The script '$1' does not exist."
	echo "Please provide a valid script file."
	echo ""
	exit
fi

if [ x"$SC" = "x" ] ; then
    sc=sc$arch
else
    sc=$SC
fi
bindir=../binaries
incdir=../include
compdir=../compiler


if [ ! -x ${compdir}/sc ] ; then
	echo ""
	echo "I could not find the Small compiler 'sc' in the"
    echo "directory $compdir. It is either missing or not"
    echo "executable. Exiting." 
	echo ""
	exit
fi


if [ ! -d ${bindir} ] ; then
    mkdir $bindir ;
fi

amx=`echo $1 | sed "s/\.sma/.amx${arch}/"`

${compdir}/${sc}  '-C-' '-;+' -i${incdir} -o${bindir}/$amx $1
res=$?
 
if [ $res -gt 1 ] ; then
    echo "No binary created."
    \rm -f ${bindir}/$amx
fi
