#! /bin/sh

port=1
nchannels=2
loops=1
    unit=0
rcv=""
mem=""
rate=ge
load=0
totalerrors=0


while [ $# -ge 1 ] ; do

if [ "$1" == "rate" ] ; then
	rate=$2
	shift
	shift
elif [ "$1" == "loops" ] ; then
	loops=$2
	shift
	shift
elif [ "$1" = "-u" ] ; then
	unit=$2
	shift
	shift
elif [ "$1" == "load" ] ; then
	load=1
	shift
elif [ "$1" == "mem" ] ; then
	mem="mem"
	shift
elif [ "$1" == "rcv" ] ; then
	rcv=rcv
	shift
elif [ "$1" == "port" ] ; then
	port=$2
	nchannels=1
	shift
	shift
else
echo "unknown arg $1"
shift
fi

done

extbdid | grep threep_sdh_sdh_sync.bit > /dev/null

if [ $? -ne 0 ] ; then
load=1
fi

#make sure mezz loaded
nbufs=`expr $nchannels \* 500`
echo "Options rate=$rate mem=$mem $rcv port=$port unit=$unit load=$load loops=$loops nbufs=$nbufs nchannels=$nchannels"

echo "calling setup"

if [ $load -eq 1 ] ; then
mezzload -u $unit -b threep_sdh_sdh_sync.bit
fi

if [ "$rate" == "ge" ] ; then

echo "threep_setup -d -m1 1gbe_slk -m2 1gbe_slk -1"
threep_setup -u $unit -d -m1 1gbe_slk -m2 1gbe_slk -1

else
echo "threep_setup -d -m1 sdh -m2 sdh -1"
threep_setup -u $unit -d -m1 sdh -m2 sdh -1
fi

sleep 0.5


for (( loop=1 ; $loop <= $loops ; loop ++ )) ; do

echo -n "Rate $rate Loop $loop: "
pdb -u $unit -f threep_${rate}_test.pdb > /dev/null

if [ "$mem" != "" ] ; then
pdb -u $unit -f mem.pdb > /dev/null
else
pdb -u $unit -f nomem.pdb > /dev/null
fi

if [ "$rcv" != "" ] ; then
pdb -u $unit -f rcv.pdb > /dev/null
else
pdb -u $unit -f norcv.pdb > /dev/null
fi

sleep 0.1

# set up STM16 channels for loopack
# check
results=`chkprbs7 -u $unit -c $port -n $nchannels -i -l 500 `
rc=$?

nerrors=`echo "$results" | grep bufs=$nbufs | head -1 | awk '{print substr($2,6)}'`

#echo "$results" | grep bufs=nbufs | head -1 
#echo "$results"

#echo "totalerrors=expr $totalerrors + $nerrors"
totalerrors=`expr $totalerrors + $nerrors`

if [ $totalerrors -ne 0 ] ; then
echo "ERRORS=$totalerrors $results"
exit $totalerrors
else
echo "ERRORS=$totalerrors"
fi

done

exit $totalerrors
