#! /bin/sh

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

GCC30="$PIC30_CD/bin/xc16-gcc -omf=coff"
GLD30="$PIC30_CD/bin/xc16-ld -omf=coff"
OBJDUMP="$PIC30_CD/bin/xc16-objdump -omf=coff"

SIM30=$PIC30_CD/bin/sim30

#
# END CONFIGURATION
#

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

rm -f test.out
# map .dinit into .text
{ echo
  echo "map .dinit into .text (expect sim30 output a-z):"
  echo
} > test.out
rm -f t.exe
$GCC30 -mcpu=30F6014 -o t.exe t.c -Wl,--heap=512 -Tt1.gld || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo "$GCC30 -o t.exe t.c -Wl,--heap=512 -Tt1.gld"
    echo $err
fi

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

# map .dinit into .dinit
{ echo
  echo "map .dinit into .dinit (expect sim30 output a-z):"
  echo
} >> test.out
rm -f t.exe
$GCC30 -mcpu=30F6014 -o t.exe t.c -Wl,--heap=512  -Tt2.gld >> test.out 2>&1
err=$?
if [ $vflag = "on" ]; then
    echo "$GCC30 -o t.exe t.c -Wl,--heap=512  -Tt2.gld"
    echo $err
fi

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

# map .dinit into .foobar
{ echo
  echo "map .dinit into .foobar (expect sim30 output a-z):"
  echo
} >> test.out
rm -f t.exe
$GCC30 -mcpu=30F6014 -o t.exe t.c -Wl,--heap=512 -Tt3.gld || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo "$GCC30 -o t.exe t.c -Wl,--heap=512 -Tt3.gld"
    echo $err
fi

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

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
