#!/bin/tcsh -fx
################################################################################
#
# routine: calwf3.csh 
#
# purpose: Runs the SDAS calibration executable for WF3.
#
# modification history:
#
#   date    opr  who       reason
# -------- ----- --------- -----------------------------------------------------
# 10/23/03 49468 MSwam     initial version
# 02/01/07 57556 Sherbert  get ASNs to calibrate
# 04/15/10 64437 RBelt     Set up temporary directory to hold uparm process info
# 08/25/10 64342 Sherbert  fix time stamp 
# 11/20/12 72689 Sherbert  IRAF-free cal
#
#########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 $SSGROOT) then
     echo "`${opustime}`-E-ERROR-SSGROOT undefined. Unable to run CALWF3."
     echo $banner
     exit $go_absent
 endif

 #
 # remove old temp files for the ASN members, if any
 # (when CALWF3 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 calwf3
    ## 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}*crj.fits
           \rm ${r}*flt.fits
           \rm ${r}*ima.fits
           ## There is another file created by calwf3, 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}*ima.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/calwf3$$_$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

 # run CALWF3
 #set calwf3 = ${STSDASDISK}/bin.${IRAFARCH}/calwf3.e   ## Original
 set calwf3 = ${SSGROOT}/bin/calwf3.e         ## IRAF-free 11/20/2012
 if ( $lastchar =~ [0-9a-i] ) then
     # verify that input file exists BEFORE running calibration s/w
     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
     ${calwf3} -tv ${p_dset}_asn
     set savestat = $status
 else
     # verify that input file exists BEFORE running calibration s/w
     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
     ${calwf3} -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
