#!/bin/tcsh -fx
##########################################################################
#
# routine: calcos_randseed.csh
#
# purpose: A CUSTOM version of the CALCOS wrapper script that is needed
#          to apply a special keyword update to RANDSEED (setting it to
#          a fixed value, to assist header differencing during parallel
#          Ops comparisons).  This is only intended to be used pre-archive,
#          as it could, in theory, affect the quality of COS calibration
#          results if used in OTFR.
#
##########################################################################
 set banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
 echo $banner
 \date
 set opustime = ( eval "date '+%Y%j%H%M%S'" )
 echo "`${opustime}`-I-INFO-*** executable is $0 *** "

 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 no_cal      = 5          # this exit status is mapped to set CA=n
 set all_is_well = 0

 # set dataset from triggering OSF
 set p_dset = $OSF_DATASET 
 # Decide if --csum should be used for calcos or not 
 # USE_CSUM should be an ENV var set by the science path
 set csum_switch = "--csum"
 if ( $USE_CSUM =~ [nNfF][oOaA]* ) then
    ## Turn off csum if path file has No or false
    set csum_switch = ()
 endif
 set msg = "USE_CSUM is ${USE_CSUM} " 
 echo "`${opustime}`-D-DIAG-$msg"
 set msg = "therefore csum_switch is ${csum_switch} ; size of var is ${#csum_switch} "
 echo "`${opustime}`-D-DIAG-$msg"

 #-------------------------------------------------------
 # resolve stretch for UNIX
 #-------------------------------------------------------
 set caldir = `osfile_stretch_file $OUTPATH`
 set sisdir = `osfile_stretch_file $INPATH`
 ## OTFR will not need to create CSUM files
 if ( ${#csum_switch} ) then
    set sumdir = `osfile_stretch_file $CSUM_DIR`
    if (! -e $sumdir) then
        set msg = "ERROR-$sumdir directory does not exist"
        echo "`${opustime}`-E-$msg"
        echo $banner
        exit $go_absent
    endif
 endif
 #
 #-------------------------------------------------------
 # move to working directory
 #-------------------------------------------------------
 if (! -e $caldir) then
   set msg = "ERROR-$caldir directory does not exist"
   echo "`${opustime}`-E-$msg"
   echo $banner
   exit $go_absent
 endif
 cd $caldir
 if ($status != 0) then
   set msg = "ERROR-Failed to set directory to $caldir"
   echo "`${opustime}`-E-$msg"
   echo $banner
   exit $go_absent
 endif

 #-------------------------------------------------------
 # PR 61512 Do NOT Exit if encounter an ACQ
 #-------------------------------------------------------

 # remove old temp or calibrated files for the ASN products and members, if any
 # (when CAL fails, these get left around and prevent retriggering)
 # Alas, it also removes shared wavecal files and can cause errors there...
 # 06/09/08 - use COS extension names, wildcards help limit the list, 
 #            i.e. flt, flt_a, flt_b, fltsum, fltsum_a, etc. -> flt*
 #
 # Set up a list of calibration file "types"
 set exposure_typs = ( counts corrtag flt x1d lampflash csum )
 if ( -e ${p_dset}_asn.fits ) then
    set asn_present = 1
    ## For each ROOTNAME in the asn file (member AND product), 
    ## remove files created by calibration 
    ## Set up the list of members so it can be used multiple times
    set memASNList = ()
    set MEMBERS = (`listasn ${p_dset}_asn.fits -s | \awk '{print $1}' `) 
    foreach ROOTNAME ( ${MEMBERS} )
        ## We need 9th character to identify missing members
        set lastchar = `echo "$ROOTNAME" | cut -c 9 `
        ## We need lowercased rootnames for file removal
        set r = `echo "$ROOTNAME" | \tr '[A-Z]' '[a-z]' `
        ## We need to avoid expansion of asterisks in broken ASN rootnames 
        if ( "$lastchar" !~ [*] ) then
            set memASNList = ( ${memASNList} ${r} )
        endif
    end
    set msg = "INFO-Association cleanup in case of re-trigger:"
    echo "`${opustime}`-I-$msg"
    ## Do one loop for ASN and singleton cleanup
 else
    ##
    ## remove old temp or cal files for the singletons, if any
    ##
    set asn_present = 0
    set memASNList = ${p_dset}
    set msg = "INFO-Singleton cleanup in case of re-trigger:"
    echo "`${opustime}`-I-$msg"
    ## Do one loop for ASN and singleton cleanup
 endif
 ## One loop for ASN and singleton cleanup
 foreach rootname ( ${memASNList} )
    ## remove possible calibration files for non-missing members 
    foreach TYPE ( ${exposure_typs} )
       #echo -n "## rm ${rootname}_${TYPE}*.fits:  "
        \rm ${rootname}_${TYPE}*.fits
    end
    #===================================================================
    # 03/30/2011
    # CUSTOM OVERRIDE of RANDSEED keyword value in the RAW FITS header(s)
    #   (there will NOT be a RAW file for ASN names and there can be 
    #    MORE THAN 1 if A and B sides are present for a singleton/member)
    kwmod ${rootname}_raw\*.fits RANDSEED 1 -i 
    #===================================================================
 end

 #
 # run CAL
 if ( ${asn_present} ) then
     ## this is an association
     echo "CALBEG ------------ `date` ------------------ $p_dset ------------------ " |& tee -a $p_dset.tra
     ## verify that input file exists BEFORE running CAL
     if (! -e ${p_dset}_asn.fits ) then
        echo "`${opustime}`-E-ERROR-${p_dset}_asn.fits file does not exist" |& tee -a $p_dset.tra
        set savestat = $quit_this_dataset
        goto END
     endif
     calcos ${csum_switch} ${p_dset}_asn |& tee -a $p_dset.tra
     set savestat = $status
 else
     ## As it turns out, you need to feed calcos a rootname with 
     ## rawaccum or rawtag but only one per rootname, otherwise it repeats 
     ## itself and we are very inefficient.
     ## PR 61512 I can now use raw* as the wildcard since rawacq is ok now.
     set inFile = `\ls -1 ${p_dset}_raw*.fits | \head -1`
     echo "CALBEG ------------ `date` ------------------ $p_dset ------------------ " |& tee -a $p_dset.tra

     ## "anything between xyz_raw and xyz_rawtag_a.fits is OK", Phil Hodge says.
     ## PR 63026 don't write singleton output to trailer as calcos already does
     calcos ${csum_switch} ${inFile} 
     set savestat = $status
     if ( $savestat == $no_cal ) then
        echo "`${opustime}`-I-INFO-SKIP Calibration for ACQ ${p_dset}" |& tee -a $p_dset.tra
        goto END
     endif
     if ( $savestat != 0 ) then
        echo "`${opustime}`-E-ERROR-Calibration failed for ${p_dset}" |& tee -a $p_dset.tra
     endif
 endif
 #
 #-------------------------------------------------------
 # put termination banners in the trailer and log
 #-------------------------------------------------------
 END:
 if ( $savestat == 0 ) then
    ## Move the csum files out of the processing dir 
    ## so they are NOT copied to the cache later
    if ( ${#csum_switch} ) then
        ## csum files are named for singletons or members, not ASNs
        foreach MEM ( ${memASNList} ) 
            echo "`${opustime}`-INFO-mv  ${MEM}_*csum*.fits ${sumdir} "
            \mv  ${MEM}_*csum*.fits ${sumdir}
        end 
    endif
    echo "CALEND ------------ `date` ------------------ $p_dset ------------------ " |& tee -a $p_dset.tra
    echo $banner
    exit $all_is_well
 else if ( $savestat == $no_cal ) then
    echo "CALEND ------------ `date` ------------------ $p_dset ------------------ " |& tee -a $p_dset.tra
    echo $banner
    exit $no_cal
 else
    echo "CALFAIL ----------- `date`------------------ $p_dset ------------------ " |& tee -a $p_dset.tra
    echo $banner
    exit $quit_this_dataset
 endif
