#! @SHELL@
echo 1..8 # Number of tests to be executed.
#
test -n "$CDO"      || CDO=cdo
test -n "$DATAPATH" || DATAPATH=./data
#
CDOOUT=cout$$
CDOERR=cerr$$
OFORMAT="-f srv -b 32"
FORMATS="srv ext ieg grb grb2 nc nc2 nc4"
#FORMATS="nc4"
#
IFILE=$DATAPATH/pl_data
NTEST=1
#
function fileformat()
{
  FILEFORMAT=undefined
  ENABLE_TEST=yes

  if [ "${FORMAT}" = srv  ] ; then  FILEFORMAT=SERVICE;  fi
  if [ "${FORMAT}" = ext  ] ; then  FILEFORMAT=EXTRA;    fi
  if [ "${FORMAT}" = ieg  ] ; then  FILEFORMAT=IEG;      fi
  if [ "${FORMAT}" = grb  ] ; then  FILEFORMAT=GRIB;     fi
  if [ "${FORMAT}" = grb2 ] ; then  FILEFORMAT=GRIB_API; fi
  if [ "${FORMAT}" = nc   ] ; then  FILEFORMAT=netCDF;   fi
  if [ "${FORMAT}" = nc2  ] ; then  FILEFORMAT=netCDF2;  fi
  if [ "${FORMAT}" = nc4  ] ; then  FILEFORMAT=netCDF4;  fi

  if [ "@ENABLE_SERVICE@" = no -a "${FORMAT}" = srv  ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_EXTRA@" = no   -a "${FORMAT}" = ext  ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_IEG@" = no     -a "${FORMAT}" = ieg  ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_GRIB@" = no    -a "${FORMAT}" = grb  ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_GRIBAPI@" = no -a "${FORMAT}" = grb2 ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_NETCDF@" = no  -a "${FORMAT}" = nc   ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_NETCDF@" = no  -a "${FORMAT}" = nc2  ] ; then  ENABLE_TEST=no; fi
  if [ "@ENABLE_NC4@" = no     -a "${FORMAT}" = nc4  ] ; then  ENABLE_TEST=no; fi
}
#
function testfunc()
{
  RSTAT=0

  CDOTEST="chaining set $INSET with $FILEFORMAT"
  echo "Running test: $NTEST - $CDOTEST"

  RFILE=$DATAPATH/tsformat${INSET}_ref
  OFILE=thread${NTEST}_res

  CDOCOMMAND="$CDO $INSTR ${IFILE}(${FORMAT}) $OFILE"
      
  echo "$CDOCOMMAND"

  if [ "${ENABLE_TEST}" = yes ] ; then
    if [ "@ENABLE_THREADS@" = yes ] ; then
      $CDO -f $FORMAT setgrid,r12x6 ${IFILE} ifile$$
      CDOCOMMAND="$CDO $INSTR ifile$$ $OFILE"

      for i in {1..5} ; do
        $CDOCOMMAND
        test $? -eq 0 || let RSTAT+=1
      done

      $CDO diff -selcode,130 $RFILE $OFILE > $CDOOUT 2> $CDOERR
      test $? -eq 0 || let RSTAT+=1
      test -s $CDOOUT && let RSTAT+=1
      cat $CDOOUT $CDOERR

      rm -f $OFILE ifile$$

      test $RSTAT -eq 0 && echo "ok $NTEST - $CDOTEST"
      test $RSTAT -eq 0 || echo "not ok $NTEST - $CDOTEST"
    else
      test $RSTAT -eq 0 && echo "ok $NTEST - $CDOTEST # SKIP threads not enabled"
    fi
  else
    test $RSTAT -eq 0 && echo "ok $NTEST - $CDOTEST # SKIP $FILEFORMAT not enabled"
  fi
  
  let NTEST+=1
  rm -f $OFILE
}
#
for FORMAT in $FORMATS; do
  fileformat
#  INSTR="-fldmin -timmean -select,code=129,130,152"
  INSTR="-fldmin -timmean -select,code=130"
  INSET=1
  testfunc
done
#
rm -f $CDOOUT $CDOERR
#
exit 0
