#! /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
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

# first link with the normal startup module
rm -f t.exe t1.map
$GLD30 -o t.exe t1.o -L $LIB_PATH -lpic30 --data-init -Map=t1.map
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GLD30 -o t.exe t1.o -L $LIB_PATH -lpic30 --data-init -Map=t1.map"
    echo $err
    echo
fi

# now link with the smaller startup module
rm -f t.exe t2.map
$GLD30 -o t.exe t1.o -L $LIB_PATH -lpic30 --no-data-init -Map=t2.map
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GLD30 -o t.exe t1.o -L $LIB_PATH -lpic30 --no-data-init -Map=t2.map"
    echo $err
    echo
fi

# use perl to extract the size of section .libc
size1=`perl -n -e 'if (/.*libc\s+\w+\s+(\w+).*/) {print hex $1,"\n"}' t1.map`
size2=`perl -n -e 'if (/.*libc\s+\w+\s+(\w+).*/) {print hex $1,"\n"}' t2.map`

if [ $vflag = "on" ]; then
    echo
    echo "size of .libc with --data-init is $size1"
    echo
    echo "size of .libc with --no-data-init is $size2"
    echo
fi

echo
echo `head -1 info.txt`

# evaluate $size1 > $size2
[ "${size1:-0}" -gt "${size2:-1}" ]

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

echo "All Tests Pass"
echo
exit 0
