#! /bin/sh

#
# CONFIGURATION SECTION
#
if [ -z "$PIC30_CD" ]; then
    echo "Environmental variable PIC30_CD must be set up.";
    exit 1;
fi

GAS30=$PIC30_CD/bin/pic30-as
GLD30=$PIC30_CD/bin/pic30-ld
OBJDUMP=$PIC30_CD/bin/pic30-objdump

BIN2HEX=$PIC30_CD/bin/pic30-bin2hex
SIM30=$PIC30_CD/bin/simpic30

#
# END CONFIGURATION
#

# process args
vflag=off
while [ $# -gt 0 ]
do
    case "$1" in
        -v)  vflag=on;;
    esac
    shift
done

rm -f t1.o
$GAS30 -o t1.o t1.s
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GAS30 -o t1.o t1.s"
    echo $err
fi

rm -f t2.o
$GAS30 -o t2.o t2.s
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GAS30 -o t2.o t2.s"
    echo $err
fi

rm -f t3.o
$GAS30 -o t3.o t3.s
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GAS30 -o t3.o t3.s"
    echo $err
fi

rm -f t4.o
$GAS30 -o t4.o t4.s
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GAS30 -o t4.o t4.s"
    echo $err
fi

rm -f t.exe
$GLD30 -o t.exe t1.o t2.o t3.o t4.o -L $PIC30_CD/lib -lpic30 -Map=t.map --no-pack-data || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GLD30 -o t.exe t1.o t2.o t3.o t4.o -L $PIC30_CD/lib -lpic30 -Map=t.map --no-pack-data"
    echo $err
fi

rm -f t1.hex
$BIN2HEX t.exe > /dev/null
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$BIN2HEX t.exe"
    echo $err
fi

rm -f test.out
$SIM30 run.cmd > /dev/null
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$SIM30 run.cmd"
    echo $err
fi

{
echo
echo  ">>Simulator Output:"
echo
} > test.out
cat UartOut.txt >> test.out
rm -f UartOut.txt

{
echo
echo ">>Linker Map File:"
echo
} >> test.out
grep .LC t.map >> test.out
echo >> test.out
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "grep .LC t.map"
    echo $err
fi

if [ $vflag = "on" ]; then
    echo
    cat test.out
fi

echo
echo `head -1 info.txt`

if [ $vflag = "on" ]; then
    diff -b -B test.out expect.out
else
    diff -b -B test.out expect.out > /dev/null
fi


if [ $? -ne 0 ]; then
    echo "ERRORs Detected!!"
    echo
    exit 199
fi

echo "All Tests Pass"
echo
exit 0
