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

#
# 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 t.exe t.map
$GLD30 -o t.exe t1.o -Map=t.map --script=t.gld
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GLD30 -o t.exe t1.o -Map=t.map --script=t.gld"
    echo $err
    echo
fi

rm -f temp
$OBJDUMP -h t.exe > temp
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$OBJDUMP -h t.exe > temp"
    echo $err
    echo
fi

# extract info about sections
LINE1=`perl -n -e 'if (/(Name.*Size.*VMA.*LMA).*$/) {print "$1\n"}' temp`
LINE2=`perl -n -e 'if (/.*(low_data\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`
LINE3=`perl -n -e 'if (/.*(high_data\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`
LINE4=`perl -n -e 'if (/.*(low_code\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`
LINE5=`perl -n -e 'if (/.*(high_code\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`
LINE6=`perl -n -e 'if (/.*(low_eedata\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`
LINE7=`perl -n -e 'if (/.*(high_eedata\s+\w+\s+\w+\s+\w+).*$/) {print "$1\n"}' temp`

# build an output file
rm -f test.out
{
    echo
    echo "Excerpt from pic30-elf-objdump output:"
    echo
    echo "$LINE1"
    echo "$LINE2"
    echo "$LINE3"
    echo "$LINE4"
    echo "$LINE5"
    echo "$LINE6"
    echo "$LINE7"
    echo
} > test.out

if [ $vflag = "on" ]; then
    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
