#!/bin/csh -f

#
# GRAPE-9 functionality test program subroutine for G5PIPE
# In order to run this script, environment vars
# GDEVICE and GREVISION must be set.
#
# GDEVICE   : device IDs in use.
# GNDEVICE  : total number of devices under test.
# GREVISION : iFPGA revision.
#

set cmdname  = $0:t;
set rootpath = $0:h/../..
pushd $rootpath > /dev/null
set rootpath = `pwd`
popd > /dev/null

setenv HIB_WARNLEVEL "1"

if (! $?GDEVICE) then
    echo "An environment variable GDEVICE must be set."
    exit
endif
set gndevice = $GNDEVICE
set gdevice = $GDEVICE
set tmpdir = ${rootpath}/tmp
set okfile = ${tmpdir}/device${gdevice}.ok
set ngfile = ${tmpdir}/device${gdevice}.ng

if (! $?GREVISION) then
    echo "An environment variable GREVISION must be set."
    exit
endif
set revision = "rev${GREVISION}";

set runtype = $1   # 's' for short run.

echo "----------------------------------------------------------"
echo " GRAPE-9 functionality test program subroutine for G5PIPE"
echo "  usage: checksub_g5"
echo "----------------------------------------------------------"
echo "Start the tests. It may take a few minutes." 
echo

set tmpout = ${tmpdir}/tmpouts9
set logdir = ${rootpath}/sample/s9/logg9
set initdir = ${rootpath}/init
cd ${rootpath}/sample/s9

foreach n (1k 8k 16k)
  if (! (${n} == "64k" && ${runtype} == "s")) then
    echo
    echo "Start s9 ${n} using device${gdevice}..."
    switch (${n})
      case "1k":
        echo 128.0 256.0 10.0 1.0 ${initdir}/pl1k 2 8.0 7 > ${tmpdir}/inputpara9.${gdevice}
        breaksw
      case "8k":
        echo 128.0 256.0 1.0 0.125 ${initdir}/pl8k 2 8.0 7 > ${tmpdir}/inputpara9.${gdevice}
        breaksw
      case "16k":
        echo 128.0 256.0 1.0 0.125 ${initdir}/pl16k 2 8.0 7 > ${tmpdir}/inputpara9.${gdevice}
        breaksw
    endsw
    if (${gndevice} == 1) then
      # all outputs go to the console.
      ./s9_g9 ${tmpdir}/inputpara9.${gdevice} |& tee ${tmpout}.${gdevice}
    else
      # some outputs are filtered for readability.
      if (${n} == "64k") then
        ./s9_g9 ${tmpdir}/inputpara9.${gdevice} |& tee ${tmpout}.${gdevice} | grep -E 'time | DCM'
      else
        ./s9_g9 ${tmpdir}/inputpara9.${gdevice} |& tee ${tmpout}.${gdevice} | tail -5 | grep -E 'time | DCM'
      endif
    endif
    grep -E 'pot|total|DCM|DE' ${tmpout}.${gdevice} | grep -v 'g5_nchip' > ${tmpout}2.${gdevice}
    grep -E 'pot|total|DCM|DE' ${logdir}/sample.${n}.${revision} | grep -v 'g5_nchip' > ${tmpout}3.${gdevice}
    diff -w ${tmpout}2.${gdevice} ${tmpout}3.${gdevice} > /dev/null
    set s = ${status}
    if (${s} == 0) then
      echo Device${gdevice} s9 ${n} OK
    else
      echo Device${gdevice} s9 ${n} NG
      touch ${ngfile}
      exit 1
    endif
  endif
end

echo
cd ../..
echo "Device${gdevice} passed all tests." 
echo

touch ${okfile}
exit 0
