#!/bin/csh -fx
##########################################################################
#
# routine: bc_cos.csh 
#
# purpose: Script for ACS pre-calibration activities
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 07/11/08 60265  Sherbert  COS breaks all the rules
# 07/04/08 60265  Sherbert  members should not include products 
# 02/23 09 61512  Sherbert  Send ACQs to calibration now
# 08/25/10 64342  Sherbert  fix time stamp and first line
# 10/07/10 64432  MSwam     remove /usr/bin/ from head call
#
##########################################################################
 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          #causes XPOLL to error exit
 set no_calibration = 2   #causes calibration to be skipped
 set all_is_well = 0
 set quit_this_dataset = 1 #status mapped to OSF_ERROR
 #
 # set dataset from triggering OSF
 set expname = $OSF_DATASET 
 set traBeg = "-------------- Before Calibration Started: ${expname} -------------- "
 set traEnd = "-------------- Before Calibration Completed: ${expname} -------------- "
 #
 #-------------------------------------------------------
 # resolve stretch for UNIX
 #-------------------------------------------------------
 set caldir = `osfile_stretch_file $OUTPATH`
 set sisdir = `osfile_stretch_file $INPATH` 
 #
 #-------------------------------------------------------
 # 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

 #-------------------------------------------------------
 # copy the trailer file to .tra
 #-------------------------------------------------------
 set lastchar = `echo $expname | \awk '{a=substr($1,length,1); print a}'`
 if ( $lastchar =~ [0-9a-i] ) then
    set msg = "Creating list of existing member trailers to copy for ASN $expname"
    echo "`${opustime}`-I-$msg"
    ## Exclude missing members and products
    set members = `listasn ${expname}_asn.fits -s | \egrep -v 'F$|PROD' | \awk '{print $1}' | /bin/dd conv=lcase`
   ## splitting long line above with continuation chars causing an error
    if ($#members == 0) then
        set msg = "ERROR-Failed to generate list of members for ${expname}: no trailers copied"
        echo "`${opustime}`-F-$msg" 
        exit $quit_this_dataset
    else
        echo "`${opustime}`-I-Copying member trailers from SIS trx to CAL tra"
        foreach MEMBER_ROOT ( $members ) 
            \cp  $sisdir/$MEMBER_ROOT.trx $caldir/$MEMBER_ROOT.tra
        end
    endif
 else
    set msg = "Copying singleton trailer from SIS trx to CAL tra"
    echo "`${opustime}`-I-$msg"
    \cp  $sisdir/$expname.trx $caldir/$expname.tra
 endif
 ## Ready to write to trailer AND process log
 echo "`${opustime}`-I-${traBeg}" >> $expname.tra
 ## TRACE uncomment if needed
#if ( $?members ) then
#    set msg = "DEBUG: members is $members"
#    echo "`${opustime}`-D-$msg"
#else
#    set msg = "DEBUG: members is NOT defined "
#    echo "`${opustime}`-D-$msg"
#endif

 #-------------------------------------------------------
 # update qolink_sms times using raw data
 #-------------------------------------------------------
 set msg = "Update qolink_sms times "
 echo "`${opustime}`-I-$msg" 
 if ( $lastchar =~ [0-9a-i] ) then
    # use asn table 
    exposure_times.pl ${expname}_asn.fits | tee -a $expname.tra
    set savestat = $status
 else
    # use raw science 
    # only one per rootname
    # Yes, do update TACQs
    set inFile = `\ls -1 ${expname}_raw*.fits | head -1`
    exposure_times.pl ${inFile} | tee -a $expname.tra
    set savestat = $status
 endif
 if ( $savestat != 0 ) then
    set msg = "ERROR updating qolink_sms with exposure_times.pl"
    echo "`${opustime}`-F-$msg" | tee -a $expname.tra
    exit $quit_this_dataset 
 endif

 #-------------------------------------------------------
 # verify that calibration should be attempted
 #-------------------------------------------------------
 set msg = "Check otfr_special_processing table."
 echo "`${opustime}`-I-$msg"
 # This process checks the otfr_special_processing table
 # I'll put no specific message in trailer if it exits happy, since only really matters for OTFR
 check_cal_state.pl $expname
 if ($status == 1) then
    set msg = "WARNING: Calibration will NOT be attempted for $expname." 
    echo "`${opustime}`-W-$msg" | tee -a $expname.tra
    echo "`${opustime}`-I-${traEnd}" >> $expname.tra
    exit $no_calibration
 endif

 # 1) PR 61512: CALIBRAT in ACQ files set to Y  is no longer a problem
 # 2) there is NO SPT file for the product files so how get CALIBRAT value?
 #
 # To handle 2, check all the member spt files and if any a N or F, exit $no_calibration
 #
 # Actually, the above must have been written before creation of the product jnk 
 # file, but what we are doing still seems like a good solution, espcially as the 
 # jnk file is just a copy of the first member's spt file with a few keyword modifications.
 if ( $lastchar =~ [0-9a-i] ) then
    set exposure_list = ( $members )
 else
    set exposure_list = $expname
 endif
 foreach EXPOSURE ( $exposure_list ) 
    # We expect an SPT file for each observation
    if (-e ${EXPOSURE}_spt.fits) then
        ## 61512 calcos wants to create csums for ACQ/IMAGE but not other ACQs.
        ## However, calcos wants to have right of refusal, so send ACQs through.

        # So now check to see if SPSS thinks this should be calibrated
        set msg = "Checking CALIBRAT value" 
        echo "`${opustime}`-I-$msg" 
        set calib = `kval ${EXPOSURE}_spt.fits CALIBRAT`
        if ( $calib == 'N' || $calib == 'F' ) then
            set msg = "PRECAL: calibration not required for $expname" 
            echo "`${opustime}`-W-$msg" | tee -a $expname.tra
            echo "`${opustime}`-I-${traEnd}" >> $expname.tra
            exit $no_calibration
        endif

    else
        # Complain about missing SPT
        set msg = "ERROR-No SPT file found for ${EXPOSURE}. "
        set msg = "$msg Cannot check CALIBRAT. "
        echo "`${opustime}`-E-$msg" | tee -a $expname.tra
        exit $quit_this_dataset 
    endif
 end
 
 echo "`${opustime}`-I-${traEnd}" >> $expname.tra
 exit $all_is_well
