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

#
# 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
$GCC30 -o t.exe t1.o -Wl,--data-init,-Map=t1.map
err=$?
if [ $vflag = "on" ]; then
    echo
    echo "$GCC30 -o t.exe t1.o Wl,--data-init,-Map=t1.map"
    echo $err
    echo
fi

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

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

if [ $vflag = "on" ]; then
    echo
    echo "size of .init with --data-init is $size1"
    echo
    echo "size of .init 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
