#!/bin/tcsh -fx
##########################################################################
#
# routine: saa_clean.csh
#
# purpose: Runs the NICMOS SAA clean task
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 11/16/07 55049  MSwam     initial version
# 05/08/08 59478  MSwam     put SAA CLEAN trailer output into real trailer
# 08/05/08 60429  MSwam     add SAADARK_CACHE import, change SAACORR test
# 04/15/10 64437  RBelt     Set up temporary directory to hold uparm process info
# 09/10/12 70213  MSwam     use tcsh
#
##########################################################################
set banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $banner
\date
#
set go_absent      = 102
set error_found    = 3
set all_is_well    = 1
#
# parse dataset,userid from OSF field
set expname = $OSF_DATASET
#
#-------------------------------------------------------
# resolve stretch for UNIX
#-------------------------------------------------------
set caldir = `osfile_stretch_file $OUTPATH`
#
#-------------------------------------------------------
# move to working directory
#-------------------------------------------------------
if (! -e $caldir) then
   echo "ERROR: $caldir directory does not exist"
   echo $banner
   exit $go_absent
endif
cd $caldir
if ($status != 0) then
   echo "ERROR: Failed to set directory to $caldir"
   echo $banner
   exit $go_absent
endif
echo "SAADARK_CACHE=${SAADARK_CACHE}"
if (! -e ${SAADARK_CACHE}) then
   echo "ERROR: SAADARK_CACHE directory does not exist"
   echo $banner
   exit $go_absent
endif
echo "SAACLEAN------------ `date`------------------" | tee -a $expname.tra
#
#-------------------------------------------------------
# verify IRAF environment defined
#-------------------------------------------------------
if (! -e $STSDASDISK) then
  echo "SAACLEAN ERROR: STSDASDISK undefined. "| tee -a $expname.tra
  echo $banner
  exit $go_absent
endif

#-------------------------------------------------------
# remove any old intermediate files (will likely fail if they exist)
#-------------------------------------------------------
\rm ${expname}_psb.fits

#------------------------------------------------------
# Set up temporary directory to hold uparm process info
#------------------------------------------------------
set temp_uparm = /var/tmp/saa_clean$$_$OSF_DATASET/
mkdir $temp_uparm
if ( $status != 0 ) then
    echo "Could not create temporary uparm directory"
    exit $go_absent
endif
setenv uparm $temp_uparm

# TURNED OFF FOR NOW (not running SAA CLEAN on TACQ datasets)
#-------------------------------------------------------
# see if this is a NICMOS TACQ dataset
#-------------------------------------------------------
#if ( -e {$expname}_rwb.fits ) then
#    ${STSDASDISK}/pkg/hst_calib/nicmos/runcalsaa.py ${expname}_rwb >> $expname.tra
#    if ( $status != 0 and $status != 1) then
#	echo "SAA CLEAN for ${expname}_rwb failed"
#    endif
#
#    ${STSDASDISK}/pkg/hst_calib/nicmos/runcalsaa.py ${expname}_rwf >> $expname.tra
#    if ( $status != 0 and $status != 1) then
#	echo "SAA CLEAN for ${expname}_rwf failed"
#    endif
#endif

#-------------------------------------------------------
# set SAACORR switch depending on SAA_DARK value
#-------------------------------------------------------
if (! -e {$expname}_cal.fits ) then
  echo "ERROR: {$expname}_cal.fits NOT FOUND."
  rm -rf $temp_uparm
  exit $error_found
endif
set saa_dark_kwd = `kval ${expname}_cal.fits SAA_DARK`
if ($saa_dark_kwd != "N/A") then
  echo "SAA_DARK= $saa_dark_kwd, so SAACORR will be set to PERFORM." | tee -a $expname.tra
  kwmod ${expname}_cal.fits SAACORR PERFORM
else
  kwmod ${expname}_cal.fits SAACORR OMIT
endif

#------------------------------------------------------
# import any specified SAADARK from the cache area
#------------------------------------------------------
set saadark_root = `kval ${expname}_cal.fits SAA_DARK | tr '[A-Z]' '[a-z]'`
if ($saadark_root != "n/a") then
  set cache_import_error = 0
  # import the ASN file from the cache
  set saadark_asn = ${SAADARK_CACHE}/${saadark_root}_asn.fits
  if (-e ${saadark_asn}) then
    # IMPORT ASN from cache
    \cp ${saadark_asn} .
    if ($status != 0) then
      echo "ERROR: Failed to copy SAADARK ${saadark_asn} from disk cache"
      set cache_import_error = 1
    else
      # then also import the ASN member RAW files
      foreach rootname ( `listasn ${saadark_root}_asn.fits -s | grep EXP | awk '{print $1}' | tr '[A-Z]' '[a-z]'`)
        set member_name = ${SAADARK_CACHE}/${rootname}_raw.fits
        if (! -e ${member_name} ) then
           echo "WARNING: SAA DARK member file ${member_name} NOT FOUND in cache"
           set cache_import_error = 1
        else
           \cp ${member_name} .
           if ($status != 0) then
              echo "ERROR: Failed to copy SAA DARK member ${member_name} from cache"
              set cache_import_error = 1
           endif
        endif
      end
    endif
  else
    echo "WARNING: No such SAADARK in the disk cache: ${saadark_asn}" | tee -a $expname.tra
    set cache_import_error = 1
  endif

  # if anything went wrong with importing from the cache,
  # see if the SAA DARK files happen to be here, by luck of OTFR processing 
  # order (just check the ASN, assume the RAW files would have the same state)
  if ($cache_import_error == 1) then
    if (! -e ${saadark_root}_asn.fits) then
       echo "WARNING: AND the SAADARK is NOT available from OTFR for the SAA CLEAN run." | tee -a $expname.tra
    endif
  endif
endif

#-------------------------------------------------------
# run SAA CLEAN on the raw file
# (there are 4 acceptable exit codes, none of which should
#  halt the processing of the exposure)
#
#-------------------------------------------------------
${STSDASDISK}/pkg/hst_calib/nicmos/runcalsaa.py ${expname}_raw.fits >> $expname.tra
set savestatus = $status
if ( $savestatus == 0) then
    echo "SAA CLEAN complete, correction applied."
else if ( $savestatus == 1) then
    echo "SAA CLEAN complete, no correction applied."
else if ( $savestatus == 2) then
    echo "SAA CLEAN failed with exception, but continue processing."
else if ( $savestatus == 3) then
    echo "SAA CLEAN failed self-diagnostic, but continue processing."
else
    echo "SAA CLEAN unexpected exit code: $savestatus"
    # save the trailer output from the task
    cat ${expname}_trl.txt | tee -a ${expname}.tra
    echo "SAACLEAN------------ `date`------------------" | tee -a $expname.tra
    rm -rf $temp_uparm
    exit $error_found
endif

#-------------------------------------------------------
# Remove temporary uparm directory
#-------------------------------------------------------
rm -rf $temp_uparm

# append the trailer written by the tool into the pipeline trailer and
# to stdout (the process log file)
#
cat ${expname}_trl.txt | tee -a ${expname}.tra

#-------------------------------------------------------
# put termination banners in the trailer and log
#-------------------------------------------------------
echo "SAACLEAN------------ `date`------------------" | tee -a $expname.tra
exit $all_is_well
