#!/bin/csh -x
##########################################################################
#
# routine: f2gxxx.csh 
#
# purpose: Script to convert input FITS files to GEIS for OTFR
#          (OnTheFlyReprocessing) pipeline.
#
#       The IRAF/STSDAS/STLOCAL task 'FITS2GEIS' is used to perform the conversion.
#
#          This is currently only needed for WFPC-2.
#
# modification history:
#
#   date    opr     who       reason
# -------- -----    --------  --------------------------------------
# 04/03/02 45563    MSwam     first version
# 12/06/02 45563_01 MSwam     add cal extensions (DUH!)
# 02/03/03 47461    MSwam     add IRAFARCH to find bin
# 08/21/03 48370    Sherbert  Add missing /bin/ qualifier to date
# 11/13/03 49769    jschultz  modifications to utilize a new opus_fitsverify 
#                             tool. This new tools is a modification of the 
#                             original fitsverify tool provided by HEASARC at 
#                             GSFC.  The opus_fitsverify tool supports an 
#                             additional -s command line option which is not
#                             directly supportd by the original fitsverify tool.
#                             The additional option makes the error checking 
#                             performed by tool more flexible.
#                             The command line arguments passed to the tool are
#                             determined from environment variables which get 
#                             set to values specified in in the process resource 
#                             file
# 12/09/04 49854   MSwam      add wf2_asn call (moved from otfr_science)
# 05/27/08 59798   MSwam      tweak to cleanup to avoid removing drz.fits
# 07/25/08 60382   FHamilton  added wf2 repro code
# 12/14/10 66639   RBelt      removed special case WEF file to GEIS for c3t
# 
##########################################################################
set banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $banner
\date
#
set go_absent         = 102 # this exit status is in the FATAL range for XPOLL
set not_needed        = 2
set quit_this_dataset = 1   # this exit status is mapped and will allow
                            #    the process to try another dataset
set all_is_well       = 0
#
# resolve stretches for UNIX
set caldir = `osfile_stretch_file $OUTPATH`
#
# parse dataset,userid from OSF field
set p_dset = `echo $OSF_DATASET | awk '{n=split($1,a,"_");print a[2]}'`
set p_dir = $OSF_DATASET
#
# if NOT WF2, skip out
if ( $p_dset !~ [u]* ) then 
   echo "Nevermind, $p_dset not a WFPC-2."
   exit $not_needed
endif
#
# move to working directory
if (! -e $caldir/$p_dir) then
   echo "ERROR: $caldir/$p_dir directory does not exist"
   exit $go_absent
endif
cd $caldir/$p_dir
if ($status != 0) then
   echo "ERROR: Failed to set directory to $caldir/$p_dir"
   exit $go_absent
endif
#
# verify IRAF environment defined
if (! -e $STLOCAL) then
    echo "ERROR: STLOCAL undefined. Unable to run FITS2GEIS."
    exit $go_absent
endif
#
echo " "
echo "F2GBEG ---" `\date +"%d-%b-%Y %T"` "------------------------------------"

#
# Copy the multiple extension fits set in the otfr science path's cal 
# directory to the science repro pipeline being used for reprocessing
#

set p_otfcid=`echo $OSF_DATASET | awk '{n=split($1,a,"_");print a[1]}'`

set atest=`echo $p_otfcid | grep -i ${REPRO_ACCOUNT}`
set savestat = $status

if ( $savestat == 0 ) then
   set ipppssoo=`echo $p_dset | awk '{a=substr($1,1,8); print a}'`

#
# list files for log (copy all FITS files to reprocessing pipeline for ingest)
   \ls -l ${ipppssoo}*.fits
#
# copy the data to the repro science pipeline WF2_CAL_DIR
#
   \cp ${ipppssoo}*.fits $WF2_REPING_DIR
   \cp ${ipppssoo}*.trl $WF2_REPING_DIR
   chmod go+rw $WF2_REPING_DIR/${ipppssoo}*
endif

# attempt to create the WF2 ASN table in the local dir
# note1: none may be produced since ASNs aren't defined for every exposure
# note2: running an OPUS task on the command line like this relies on the 
#          existence and correctness of OPUS null.path)
#
wf2_asn ${p_dset}
set savestat = $status
if ( $savestat != 0 ) then
  # failures only occur if something major goes wrong, not if there is no
  # applicable asn or if the exposure name is garbled
  echo "ERROR: Failed to run wf2_asn task for: ${p_dset}"
  echo $banner
  exit $quit_this_dataset
endif

#
# Run FITS2GEIS for WF2
#
set fits = (_c0f.fits _c1f.fits _d0f.fits _x0f.fits _q1f.fits _q0f.fits _shf.fits end)
# duplicate of list to use for file removal at the end
set fullset = (_c0f.fits _c1f.fits _d0f.fits _x0f.fits _q1f.fits _q0f.fits _shf.fits end)
set geis = (.c0h .c1h .d0h .x0h .q1h .q0h .shh end)
#
while (${fits[1]} !=  ${geis[1]}) # For each file type
  set cnt = `\ls -1 ${p_dset}${fits[1]} | wc -l`  # Is there a FITS file that
  if ($cnt > 0) then                             # requires conversion
    echo "verify and convert ${p_dset}${fits[1]}"
#
    # prior to geis conversion, perform fits check, unless suppressed
    if (!($?FITS_VERIFY)) then
       echo "ERROR: FITS_VERIFY mnemonic not present in resource file"
       exit $go_absent
    endif
    if ($FITS_VERIFY != "FALSE") then
       # set command line options based on resource file mnemonics
       set verify_level=""
       set verify_report=""      
       if ($?FITS_VERIFY_LEVEL) then
         switch ($FITS_VERIFY_LEVEL)
           case [eE]:
             set verify_level=-e
             breaksw
           case [sS]:
             set verify_level=-s
             breaksw
         endsw
       endif
       if ($?FITS_VERIFY_REPORT) then       
         switch ($FITS_VERIFY_REPORT)
            case [qQ]:
             set verify_report=-q
             breaksw
         endsw
       endif 
       # run opus_fitsverify for FITS file prior to geis conversion 
       opus_fitsverify $verify_level $verify_report ${p_dset}${fits[1]}
       if ($status != 0) then
         echo "opus_fitsverify failed on" ${p_dset}${fits[1]}
         echo $banner
         exit $quit_this_dataset
       endif
    endif
#
    # perform fits to geis conversion
    ${STLOCAL}/bin.${IRAFARCH}/fits2geis.e  ${p_dset}${fits[1]} ${p_dset}${geis[1]}
    if ($status != 0 ) then
      echo "ERROR: FITS2GEIS conversion failed"
      echo $banner
      exit $quit_this_dataset
    endif
  endif
  shift fits
  shift geis
end

#
# remove source FITS files so only GEIS remain
# (using the dataset name allows us to avoid wiping out any WF2 ASN file)
while (${fullset[1]} != "end") # For each file type
  echo "removing ${p_dset}${fullset[1]}"
  \rm -f ${p_dset}${fullset[1]}
  shift fullset
end

#
echo "F2GEND ---" `\date +"%d-%b-%Y %T"` "------------------------------------"
exit $all_is_well
