#! /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
AR30=$PIC30_CD/bin/pic30-ar
OBJDUMP=$PIC30_CD/bin/pic30-objdump


#
# 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 2> /dev/null
err=$?
if [ $vflag = "on" ]; then
    clear
    echo
    echo "$GAS30 -o t1.o t1.s"
    echo $err
fi

rm -f t2.o
$GAS30 -o t2.o t2.s 2> /dev/null
err=$?
if [ $vflag = "on" ]; then
    echo "$GAS30 -o t2.o t2.s"
    echo $err
fi


rm -f t3.o
$GAS30 -o t3.o t3.s 2> /dev/null
err=$?
if [ $vflag = "on" ]; then
    echo "$GAS30 -o t3.o t3.s"
    echo $err
fi

# iteration 1: all object files
if [ $vflag = "on" ]; then
    echo
    echo "Linking three object files..."
    echo
fi

{
cat <<EOF

Linking three object files...

EOF
} > test.out

rm -f t.exe
$GLD30 -o t.exe t1.o t2.o t3.o || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo "$GLD30 -o t.exe t1.o t2.o t3.o"
    echo $err
fi


if [ $vflag = "on" ]; then
    $OBJDUMP -d -j.text t.exe || exit 99
    echo
fi

rm -f test1.out
$OBJDUMP -d -j.text t.exe >> test.out

# iteration 2: t2.o as archive
if [ $vflag = "on" ]; then
    echo
    echo "Linking two object files and an archive..."
    echo
fi

{
cat <<EOF

Linking two object files and an archive...

EOF
} >> test.out

rm -f t2.a
$AR30 r t2.a t2.o
err=$?
if [ $vflag = "on" ]; then
    echo "$AR30 r t2.a t2.o"
    echo $err
fi

rm -f t.exe
$GLD30 -o t.exe t1.o t2.a t3.o || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo "$GLD30 -o t.exe t1.o t2.a t3.o"
    echo $err
fi


if [ $vflag = "on" ]; then
    $OBJDUMP -d -j.text t.exe || exit 99
    echo
fi

rm -f t2.a
$OBJDUMP -d -j.text t.exe >> test.out

# iteration 3: t2.o,t3.o as archive
if [ $vflag = "on" ]; then
    echo
    echo "Linking one object file and an archive..."
    echo
fi

{
cat <<EOF

Linking one object files and an archive...

EOF
} >> test.out

rm -f t23.a
$AR30 r t23.a t2.o t3.o
err=$?
if [ $vflag = "on" ]; then
    echo "$AR30 r t23.a t2.o t3.o"
    echo $err
fi

rm -f t.exe
$GLD30 -o t.exe t1.o t23.a || exit 99
err=$?
if [ $vflag = "on" ]; then
    echo "$GLD30 -o t.exe t1.o t23.a"
    echo $err
fi


if [ $vflag = "on" ]; then
    $OBJDUMP -d -j.text t.exe || exit 99
    echo
fi

rm -f t23.a
$OBJDUMP -d -j.text t.exe >> test.out


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
