#!/bin/csh -f

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

set rev = 0
set devs = (0 1 2 3)
set tmpdir = ${rootpath}/tmp

echo "Start check for ${#devs} device(s) (revision: ${rev}, device IDs: ${devs})..."

#
# tests on each device.
#
set i = 1
while (${i} <= ${#devs})
    set okfile = ${tmpdir}/device$devs[$i].ok
    set ngfile = ${tmpdir}/device$devs[$i].ng
    (setenv GDEVICE "$devs[$i]" ; \
     setenv GREVISION "${rev}" ; \
     setenv GNDEVICE ${#devs} ;\
     rm ${okfile} ${ngfile} >& /dev/null ; \
     ${rootpath}/gdr/test/checksub ${argv}) &
    sleep 1
    @ i++
end
onintr LABEL_HUP

# wait until all sub programs are done.
set nruns = 1
while (${nruns} > 0)
    set nruns = `ps x | pgrep checksub | wc -l`
    sleep 1
end

set allok = 1
set i = 1
while (${i} <= ${#devs})
    set okfile = ${tmpdir}/device$devs[$i].ok
    set ngfile = ${tmpdir}/device$devs[$i].ng
    if ( -f ${ngfile}) then
        set allok = 0
    else if (! -f ${okfile}) then
        set allok = 0
    endif
    @ i++
end

if (${allok} == 0) then
    echo ""
    echo "Check failed."
    echo ""
    exit 1
endif

#
# Tests using all devices.
#
if (${#devs} == 1) then
    # do not perform this test for a single device system.
    cd ${rootpath}
    exit 0
endif

echo ""
echo "Start tests using all devices."
echo ""

setenv GDEVICE "$devs"
setenv GREVISION "${rev}"
set tmpdir = ${rootpath}/tmp
set tmpout = ${tmpdir}/tmpouts9.all
cd ${rootpath}/sample/s9
set ntry = 0
foreach n (256k)
  while (${ntry} < 3)
    echo "Start s9 ${n} try${ntry} devices: ${devs}..."
    switch (${n})
     case "1k"
      echo 128.0 256.0 10.0 1.0 pl1k 2 8.0 7 > ${tmpdir}/inputpara9.all
      breaksw
     case "64k"
      echo 128.0 256.0 0.5 0.0625 pl64k 2 8.0 7 > ${tmpdir}/inputpara9.all
      breaksw
     case "256k"
      echo 128.0 256.0 0.2 0.0625 pl256k 2 8.0 7 > ${tmpdir}/inputpara9.all
      breaksw
    endsw

    ./s9_gdr ${tmpdir}/inputpara9.all |& tee ${tmpout}.try${ntry} | grep 'time'
    grep -v "cputime\|nplus\|closed\|opened\|devid" ${tmpout}.try${ntry} > ${tmpout}.try${ntry}striped
    if (${ntry} != 0) then
      diff -w ${tmpout}.try0striped ${tmpout}.try${ntry}striped
      set s = ${status}
      if (${s} == 0) then
        echo Devices:${devs}    s9 ${n} try${ntry} OK
      else
        echo Devices:${devs}    s9 ${n} try${ntry} NG
        echo ""
        echo "Check failed."
        echo ""
        cd ${rootpath}
        exit 1
      endif
    endif

    @ ntry++
  end
end

echo ""
echo "All devices passed all tests."
echo ""
cd ${rootpath}
exit 0

LABEL_HUP:
killall checksub s9_gdr s8_gdr >& /dev/null
