#! /bin/sh

# This is the official template for pipetool regression test scripts.
# In addition to supporting the "SHORTTEST" option, this script also
# allows the user to run individual subtests from the command line.
# The script will accept a series of test identifiers, generally of
# the form "test1" "test2" ... which are to be run.


# arfcorr.t
# test script for arfcorr


# syntax:
# arfcorr.t [<testid> ... ]
 



######################################################################
# subroutine
# error_exit <message>
# Fatal error exit

error_exit()
{
  echo "$1" | tee -a $LOGFILE
  echo "${toolname} : FAIL" | tee -a $LOGFILE
  exit 1
}

######################################################################
# subroutine
# keyfilter infile outfile
# filters out CHECKSUM, Dataset, CREATOR, HISTORY, DATASUM, 
#             ASCDSVER, HISTNUM, and DATE
# To filter additional keywords, add s/KEYWORD/Dataset/g; for each.

keyfilter()
{
  cat $1 | sed -e 's/CHECKSUM/Dataset/g;s/COMMENT/Dataset/g;
  s/DATE/Dataset/g;s/CREATOR/Dataset/g;s/HISTORY/Dataset/g;
  s/DATASUM/Dataset/g;s/ASCDSVER/Dataset/g;s/HISTNUM/Dataset/g' | \
  grep -v Dataset > $2
  zerotest $2
}

######################################################################
# subroutine
# find_tool <toolname>
# checks that tool exists and is runnable

find_tool()
{
  s1=`type $1`
  s2=`echo $s1 | awk -F" " '{ print $3}'`
  if test -x $s2 ; then
    :
  else
    error_exit "tool $1 not found"
  fi
}

######################################################################
# subroutine
# zerotest <file> 
# Makes sure that file is not 0 length.
# Use this to protect yourself against empty files  (which will 
# 'diff' without error).  This can happen when the input file to
# cat $infile | do_something >> $outfile
# is missing.  This is used by keyfilter(), above.

zerotest()
{
 if test -s $1 ;
 then
   :
 else
   echo "ERROR: file $1 is of zero length" >> $LOGFILE
   #  Indicate failure, but do not exit.
   mismatch=0
 fi
}


######################################################################
# Initialization

toolname="arfcorr"

# set up list of tests
alltests="test1 test2 test3 test4 test5 test6"

# "short" test to run
shortlist="test1"

# compute date string for log file
DT=`date +'%d%b%Y_%T'`


# check for directory environment variables
if test "x${TESTIN}" = "x" -o "x${TESTOUT}" = "x" -o "x${TESTSAV}" = "x" \
   -o "x${TESTLOG}" = "x" ; then
  error_exit "one or more of TESTIN/TESTOUT/TESTSAV/TESTLOG not defined" 
fi

# convenience definitions
OUTDIR=$TESTOUT/$toolname
SAVDIR=$TESTSAV/$toolname
INDIR=$TESTIN/$toolname
LOGDIR=$TESTLOG/$toolname

# set up log file name
LOGFILE=$LOGDIR/${toolname}_log.$DT

#get rid of old logs
rm -f $LOGDIR/${toolname}_log.*



# Any tests specified on command line?
if test $# -gt 0; then
  # yes, do those tests
  testlist=$*
else
  # No, see if we are to do "short" test
  if test "x$SHORTTEST" = "x" ; then
    # No, do everything
    testlist=$alltests
  else
    # yes, do short test
    testlist=$shortlist
  fi
fi


# Make sure we have a log directory
if test -d $LOGDIR ; then
 :
else
  mkdir -p $LOGDIR 
  if test $? -ne 0 ; then
    error_exit ""
  fi
fi


# Make sure we have an output directory
if test -d $OUTDIR ; then
 :
else
  mkdir -p $OUTDIR >> $LOGFILE 2>&1
  if test $? -ne 0 ; then
    error_exit "can't create output directory $OUTDIR"
  fi
fi


# check for tools
# if a utility is used in the form "utility <args> > outfile", and 'utility'
# cannot be run, 'outfile' will still be created.  If utility is used on 
# both the output and reference files of a tool the resultant utility output 
# files will both exist and be empty, and will pass a diff.

find_tool dmlist
find_tool dmimgcalc



# announce ourselves
echo ""
echo "${toolname} regression" | tee $LOGFILE
echo ""

# All parameters except verbose should be set anyway, but clear them
# to be safe.
bose=`pget $toolname verbose`
punlearn $toolname
pset $toolname verbose=$bose

script_succeeded=0

######################################################################
# Begin per-test loop

for testid in $testlist
do

  # delete old outputs
  rm -f $OUTDIR/${testid}*

  # Set up file names
  outfile=$OUTDIR/${testid}.fits
  savfile=$SAVDIR/${testid}.fits

  echo "" | tee -a $LOGFILE
  echo "running $testid" | tee -a $LOGFILE
  echo "" | tee -a $LOGFILE
  ####################################################################
  # run the tool
  case ${testid} in

    test1 ) # create output psf cf image for obsid 735, 
            # src 59 broadband, energy=2.3
	    #...Define input files, params 
	    infile="${INDIR}/test1_pstamp3.fits"
            outfile=$outfile
	    region="region\(${INDIR}/test1_srcreg3.fits\)"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test1_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=2.3 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842105263 y=4330.2368421053 \
             arf="" radlim=2.0 ecffile=$ecffile verbose=0"
	    echo $test1_string | tee -a  $LOGFILE 
	    eval $test1_string  | tee -a  $LOGFILE  2>&1
            ;;

   test2 )  # create output table of psf fractions from obsid 735, 
            # src 69 broadband arf file
	    #...Define input files, params 
	    infile="${INDIR}/test2_pstamp3.fits"
            outfile=$outfile
	    region="region\(${INDIR}/test2_srcreg3.fits\)"
	    arffile="${INDIR}/test2_arf3.fits"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test2_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=0.0 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842105263 y=4330.2368421053 \
             arf=$arffile e_step=500 radlim=2.0 \
	     ecffile=$ecffile verbose=0"
	    echo $test2_string | tee -a  $LOGFILE 
	    eval $test2_string  | tee -a  $LOGFILE  2>&1
            ;;

   test3 )  # run test using region specified in wcs coords 
	    infile="${INDIR}/test2_pstamp3.fits"
            outfile=$outfile
	    region="ellipse\(9:53:51.934,+69:02:49.86,17.1034\'\',11.4805\'\',5.99068\)"
	    arffile="${INDIR}/test2_arf3.fits"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test3_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=0.0 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842 y=4330.2369 \
             arf=$arffile e_step=500 radlim=2.0 \
	     ecffile=$ecffile verbose=0"
	    echo $test3_string | tee -a  $LOGFILE 
	    eval $test3_string  | tee -a  $LOGFILE  2>&1
            ;;

   test4 )  # repeat test3 but using a region string with physical coords
	    infile="${INDIR}/test2_pstamp3.fits"
            outfile=$outfile
	    region="ellipse\(5087.5857,4330.2366,34.763008,23.33435,5.99068\)"
	    arffile="${INDIR}/test2_arf3.fits"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test4_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=0.0 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842 y=4330.2369 \
             arf=$arffile e_step=500 radlim=2.0 \
	     ecffile=$ecffile verbose=0"
	    echo $test4_string | tee -a  $LOGFILE 
	    eval $test4_string  | tee -a  $LOGFILE  2>&1
            ;;

   test5 )  # repeat test3 but using a region file containing physical coords
	    infile="${INDIR}/test2_pstamp3.fits"
            outfile=$outfile
	    region="region\(${INDIR}/test5_srcreg.fits\)"
	    arffile="${INDIR}/test2_arf3.fits"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test5_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=0.0 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842 y=4330.2369 \
             arf=$arffile e_step=500 radlim=2.0 \
	     ecffile=$ecffile verbose=0"
	    echo $test5_string | tee -a  $LOGFILE 
	    eval $test5_string  | tee -a  $LOGFILE  2>&1
            ;;

   test6 )  # repeat test3 but test for error condition with invalid tmpdir
	    infile="${INDIR}/test2_pstamp3.fits"
            outfile=$outfile
	    region="region\(${INDIR}/test5_srcreg.fits\)"
	    arffile="${INDIR}/test2_arf3.fits"
            ecffile="${CALDB}/data/chandra/default/reef/hrmaD1996-12-20reefN0001.fits"
	    test6_string="arfcorr infile=$infile \
	     outfile=$outfile region=$region energy=0.0 \
             nsubpix=5 nfracpix=1 \
	     x=5087.5842 y=4330.2369 \
             arf=$arffile e_step=500 radlim=2.0 \
             tmpdir='/fakE/908717/unL1kelyDirNAmE' \
	     ecffile=$ecffile verbose=0"
            echo $test6_string | tee -a  $LOGFILE
            rm -f $OUTDIR/scrub_${testid}.0.tmp
            eval $test6_string 2>&1 | tee -a $OUTDIR/scrub_${testid}.0.tmp
            cat $OUTDIR/scrub_${testid}.0.tmp >> ${LOGFILE}
            ;;

  esac

  ####################################################################
  # check the outputs

  # Init per-test error flag
  mismatch=1

  ####################################################################
  # FITS table

  # new output
  #dmlist $outfile opt=header,data,clean rows=700:1400 > \
  # $OUTDIR/${testid}.dmp1 2>>$LOGFILE
  #keyfilter $OUTDIR/${testid}.dmp1 $OUTDIR/${testid}.dmp2 \
  # 2>>$LOGFILE
  
  # reference output
  #dmlist $savfile opt=header,data,clean rows=700:1400 > \
  # $OUTDIR/${testid}.dmp1_std 2>>$LOGFILE
  #keyfilter $OUTDIR/${testid}.dmp1_std $OUTDIR/${testid}.dmp2_std \
  # 2>>$LOGFILE
  
  # compare
  #diff $OUTDIR/${testid}.dmp2 $OUTDIR/${testid}.dmp2_std > \
  # /dev/null 2>>$LOGFILE
  #dmdiff $outfile $savfile tol=$SAVDIR/toleranceB error_on_comment- > /dev/null 2>>$LOGFILE


  if test ${testid} = "test6" ; then
    sed -e "s;${INDIR};;g" $OUTDIR/scrub_${testid}.0.tmp | sed -e "s;${OUTDIR};;g" > $OUTDIR/${testid}_output.txt
    diff $OUTDIR/${testid}_output.txt $SAVDIR/${testid}_output.txt > /dev/null 2>> ${LOGFILE}
    if  test $? -ne 0 ; then
      echo "ERROR: TEXT MISMATCH in $OUTDIR/${testid}_output.txt" >> $LOGFILE
      mismatch=0
    fi
  else
     dmdiff $outfile $savfile tol=$SAVDIR/tolerance error_on_comment- > /dev/null 2>>$LOGFILE
     if  test $? -ne 0 ; then
       echo "ERROR: MISMATCH in $outfile" >> $LOGFILE
       mismatch=0
    fi
  fi
  
  ####################################################################
  # Did we get an error?
  if test $mismatch -eq 0 ; then
    # Yes
    echo "${testid} NOT-OK"
    script_succeeded=1
  else
    # No
    echo "${testid} OK"
  fi

done
# end per-test loop
######################################################################


######################################################################
# report results

# blank line
echo ""

if test $script_succeeded -eq 0; then
    echo "${toolname} : PASS" | tee -a $LOGFILE
else
    echo "${toolname} : FAIL" | tee -a $LOGFILE
fi

echo "log file in ${LOGFILE}"


exit $script_succeeded
