#!/bin/tcsh -fx
################################################################################
#
# routine: calacs.csh 
#
# purpose: Runs the SDAS calibration executable for ACS.
#
# modification history:
#
#   date    opr  who       reason
# -------- ----- --------- -----------------------------------------------------
# 01/13/99 38161 Rose	   initial version
# 03/03/99 38161 Rose      Correct the substring awk
# 04/21/99 38897 Rose	   remove tee, and correct savestat
# 03/22/00 40964 Rose	   don't copy the association trx file
# 08/25/00 43165 MSwam     add check to bypass calibration (for OTFR)
# 02/14/01 43165 MSwam     adjust ASN ending character test
# 10/08/01 44598 MSwam     move tasks to pre-cal stage
# 01/31/03 47461 MSwam     use IRAFARCH to find cal executable
# 08/21/03 48370 Sherbert  Add missing /bin/ qualifier to tr
# 08/17/04 51701 Sherbert  Remove more files to make retriggerable
# 09/10/04 51801 Sherbert  Add timestamping to some messages and a file check
# 02/04/05 52183 Sherbert  Reinstate 47213 change awk to cut so broken ASNs work 
# 02/14/05 52183 Sherbert  Refactor above so retriggering still works
# 04/15/10 64437 RBelt     Set up temporary directory to hold uparm process info
# 08/25/10 64342 Sherbert  fix time stamp and first line
# 07/22/11 68298 MSwam     Let $PATH find the IRAF-free CALACS version and set
#                             imclobber
# 03/28/12 70895 MSwam     Allow switching between CTE,NONCTE calacs versions
#
#########1#########2#########3#########4#########5#########6#########7#########8

 set banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
 echo $banner
 set opustime = ( eval "date '+%Y%j%H%M%S'" )
 echo "`${opustime}`-I-INFO-*** executable is $0 *** "
 echo $banner
 \date

 #
 set go_absent = 102          #this exit status is in the FATAL range for XPOLL
 set quit_this_dataset = 1    #this exit status is mapped and will allow
                              #  the process to try another dataset
 set all_is_well = 0
 #
 # set dataset from triggering OSF
 set p_dset = $OSF_DATASET 
 #
 # resolve stretch for UNIX
 set caldir = `osfile_stretch_file $OUTPATH`

 #
 # move to working directory
 if (! -e $caldir) then
    echo "`${opustime}`-E-ERROR-$caldir directory does not exist"
    echo $banner
    exit $go_absent
 endif
 cd $caldir
 if ($status != 0) then
    echo "`${opustime}`-E-ERROR-Failed to set directory to $caldir"
    echo $banner
    exit $go_absent
 endif

 #
 # verify IRAF environment defined
 if (! -e $STSDASDISK) then
     echo "`${opustime}`-E-ERROR-STSDASDISK undefined. Unable to run CALACS."
     echo $banner
     exit $go_absent
 endif

 #
 # determine CALACS version to run 
 # (default is whatever is in the std name, which is currently the CTE version,
 #  all are found within the Unix $PATH via the opus_login.csh/SSB set-up)
 #
 set calacsExe = calacs.e
 if ( $?CALACS_TYPE) then
   if ( $CALACS_TYPE == "CTE_VERSION" ) then
     set calacsExe = calacs.e
   else if ( $CALACS_TYPE == "NONCTE_VERSION" ) then
     set calacsExe = calacs.e_preCTE
   endif
 endif

 #
 # remove old temp files for the ASN members, if any
 # (when CALACS fails, these get left around and prevent retriggering)
 ## Also remove already created flt, crj, or sfl files 
 #
 if ( -e ${p_dset}_asn.fits ) then
    set msg =  "INFO-Association cleanup:"
    echo "`${opustime}`-I-$msg"
    ## For each ROOTNAME in the asn file (member AND product), 
    ## remove files created by calacs
    ## We need to avoid expansion of asterisks in broken ASN rootnames 
    ## We need 9th character in order to identify Associations
    ## We need lowercased rootnames for file removal

    foreach ROOTNAME ( `listasn ${p_dset}_asn.fits -s | \awk '{print $1}'`)
       set lastchar = `echo "$ROOTNAME" | cut -c 9 `
       if ( "$lastchar" !~ [*] ) then
           ## remove possible calibration files for non-missing members 
           set r = `echo "$ROOTNAME" | tr '[A-Z]' '[a-z]' `
           \rm ${r}*tmp.fits
           \rm ${r}*flt.fits
           \rm ${r}*crj.fits
           \rm ${r}*sfl.fits
           ## There is another file created by calacs, but specific to ASN products...
           ## DO NOT REMOVE spt file FOR MEMBERS! Only for products.
           if ( $lastchar =~ [0-9a-i] ) then
               \rm ${r}_spt.fits
           endif
           ## Assumption: the SPT file will never exist for 0th root that isn't listed 
           ## as a product in ASN table.  If it ever does, it will not be deleted by 
           ## this logic.
       endif
    end
 else
 ##
 ## remove old temp files for the singletons, if any
 ## Also remove already created flt, crj, or sfl files 
 ##
    set msg = "INFO-Singleton cleanup:"
    echo "`${opustime}`-I-$msg"
       \rm ${p_dset}*tmp.fits
       \rm ${p_dset}*flt.fits
       \rm ${p_dset}*crj.fits
       \rm ${p_dset}*sfl.fits
 endif

 #
 # get the last character of the ipppssoot
 set lastchar = `echo $p_dset | \awk '{a=substr($1,length,1); print a}'`

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

 # set imclobber so any leftover files that made it past the cleanup filters
 #   above will still get overwritten by CALACS
 setenv imclobber yes

 # run CALACS
 echo "using CALACS from: ${calacsExe}"
 if ( $lastchar =~ [0-9a-i] ) then
     # verify that input file exists BEFORE running CALACS
     if (! -e ${p_dset}_asn.fits ) then
        echo "`${opustime}`-E-ERROR-${p_dset}_asn.fits file does not exist"
        echo $banner
        rm -rf $temp_uparm
        exit $quit_this_dataset
     endif
     ${calacsExe} -tv ${p_dset}_asn
     set savestat = $status
 else
     # verify that input file exists BEFORE running CALACS
     if (! -e ${p_dset}_raw.fits ) then
        echo "`${opustime}`-E-ERROR-${p_dset}_raw.fits file does not exist"
        echo $banner
        rm -rf $temp_uparm
        exit $quit_this_dataset
     endif
     ${calacsExe} -tv ${p_dset}_raw
     set savestat = $status
 endif
 #
 # Remove temporary uparm directory
 rm -rf $temp_uparm
 #
 echo $banner
 if ( $savestat == 0 ) then
   exit $all_is_well
 else
   exit $quit_this_dataset
 endif
