#! /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=elf"
GAS30="$PIC30_CD/bin/xc16-as -omf=elf -W"
OBJDUMP="$PIC30_CD/bin/xc16-objdump -omf=elf"

BIN2HEX="$PIC30_CD/bin/xc16-bin2hex -omf=elf"
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 t1.out t2.out
$GCC30 t1.c t2.c -o t1.exe -msmart-io=1 -mcpu=30F6014 -Wl,--heap=256,-Map=t1.map
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GCC30 t1.c -o t1.exe -msmart-io=1 -mcpu=30F6014 -Wl,--heap=256,-Map=t1.map"
    echo $err
fi

if [ $err -ne 0 ]; then
    exit
fi


rm -f t1.hex
$BIN2HEX t1.exe -v > t1.out 2>&1
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$BIN2HEX t1.exe -v >t1.out 2>&1"
    echo $err
fi


$GCC30 t1.c t2.c -o t2.exe -msmart-io=0 -mcpu=30F6014 -Wl,--heap=256,-Map=t2.map
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GCC30 t1.c -o t2.exe -msmart-io=0 -mcpu=30F6014 -Wl,--heap=256,-Map=t2.map"
    echo $err
fi

rm -f t2.hex
$BIN2HEX t2.exe -v > t2.out 2>&1
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$BIN2HEX t2.exe -v >t2.out 2>&1"
    echo $err
fi

SIZE1=`perl -n -e 'if (/\.text.*\((\d+)\)/) {print +$1}' t1.out`
SIZE2=`perl -n -e 'if (/\.text.*\((\d+)\)/) {print +$1}' t2.out`

{
echo "size of section .text with --smart-io:    $SIZE1"
echo "size of section .text with --no-smart-io: $SIZE2"
} > test.out

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

echo
echo `head -1 info.txt`

if [ $SIZE1 -ge $SIZE2 ]; then
    echo "ERRORs Detected!!"
    echo
    exit 199
fi

echo "All Tests Pass"
echo
exit 0
