#!/bin/sh
#set -x

VERBOSE=0
OPROG=funcalc
NPROG=../funcalc
R="cir(511,512,1)"
OFILE="${HOME}/data/snr.ev"
NFILE="${HOME}/data/snr.ev.gz"

while [ x"$1" != x ]; do
  case $1 in
  -1)
    DO1=YES
    shift
    continue;;
  -f)
    shift
    OFILE=$1
    NFILE=$1
    shift
    continue;;
  -n)
    shift
    NPROG=$1
    shift
    continue;;
  -o)
    shift
    OPROG=$1
    shift
    continue;;
  -P)
    DO1=YES
    NPROG=../funcalc.pure
    shift
    continue;;
  -r)
    shift
    R=$1
    shift
    continue;;
  -v)
    VERBOSE=1
    shift
    continue;;
  -V)
    VERBOSE=2
    shift
    continue;;
  *)
    shift
    continue;;
  esac
done

OFILE="${OFILE}[${R}]"
NFILE="${NFILE}[${R}]"
echo "OPROG="${OPROG} "FILE="${OFILE}
echo "NPROG="${NPROG} "FILE="${NFILE}

IFS="	"
while read ARG1 ARG2 ARG3; do
  if [ x"$ARG1" = x ]; then
    continue
  fi
  if [ x`echo $ARG1 | sed 's/^#.*/YES/g'` = x"YES" ]; then
    continue
  fi
  CMD=${ARG1}
  if [ x"$ARG2" = x1 ]; then
    OUT=FALSE
  else
    OUT=TRUE
  fi	
  EXPR=${ARG3}
  case $CMD in
  OPROG)
    OPROG=$ARG2
    ;;
  NPROG)
    NPROG=$ARG2
    ;;
  OFILE)
    OFILE=$ARG2
    ;;
  NFILE)
    NFILE=$ARG2
    ;;
  REGION)
    R=$ARG2
    ;;
  EXIT)
    exit
    ;;
  EXACT|SUM|REV)
    if [ x"$DO1" = xYES ]; then
      echo "DO1: $EXPR"
      if [ x"$OUT" = xFALSE ]; then
        $NPROG -e "${EXPR}" ${NFILE}  > funcalc1.out
      else
        $NPROG -e "${EXPR}" ${NFILE} stdout | fundisp stdin  > funcalc1.out
      fi
    else
      echo "EXACT: $EXPR"
      CMP=yes
      XPROG=""
      if [ x"$OUT" = xFALSE ]; then
        $OPROG -e ${EXPR} ${OFILE} > tfuncalc1.out 2>err.log
      else
        $OPROG -e ${EXPR} ${OFILE} stdout | fundisp stdin > tfuncalc1.out 2>err.log
      fi
      if test $? -ne 0; then
        CMP=no
        XPROG="$OPROG"
      fi
      if [ x"$OUT" = xFALSE ]; then
        $NPROG -e ${EXPR} ${NFILE} > tfuncalc2.out
      else
        $NPROG -e ${EXPR} ${NFILE} stdout | fundisp stdin > tfuncalc2.out
      fi
      if test $? -ne 0; then
        CMP=no
        XPROG="${XPROG:-""}${XPROG:+" "}$NPROG"
      fi
      if [ x"$CMP" = xyes ]; then
        mv tfuncalc1.out funcalc1.out
        mv tfuncalc2.out funcalc2.out
        diff funcalc1.out funcalc2.out
      fi
    fi
    echo " "
    ;;
  *)
    echo "ERROR: unknown command: $CMD"
    exit 1
    ;;
  esac
  if [ $VERBOSE = 1 ]; then
    echo "***** funcalc1.out *****"
    cat funcalc1.out
  fi
  if [ $VERBOSE = 2 ]; then
    echo "***** funcalc1.out *****"
    cat funcalc1.out
    echo "***** funcalc2.out *****"
    cat funcalc2.out
  fi
  rm -f err.log
done

rm -f funcalc1.out funcalc2.out tfuncalc1.out tfuncalc2.out
