#!/bin/csh -x
##########################################################################
#
# routine: bc_calnca.csh
#
# purpose: Tasks that preceed CALNICA
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 10/08/01 44598  MSwam     first version
# 11/01/01 44524  J.Baum    add exposure_times.pl 
#
##########################################################################
set banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $banner
\date
#
set go_absent = 102          #this exit status is in the FATAL range for XPOLL
set no_calibration = 7       #no calibration is required
set calib_error    = 3
set all_is_well    = 1
#
# parse dataset,userid from OSF field
set expname = $OSF_DATASET
#
# Skip NDM data
if ( $OSF_DATA_ID == 'ndm') then
    echo "PRECAL: calibration not required for NDM file $expname"
    exit $no_calibration
endif
#
# verify that calibration should be attempted
check_cal_state.pl $expname
if ($status == 1) then
   echo "WARNING: Calibration will NOT be attempted for $expname."
   exit $no_calibration
endif
#
#-------------------------------------------------------
# resolve stretch for UNIX
#-------------------------------------------------------
set caldir = `osfile_stretch_file $OUTPATH`
set sisdir = `osfile_stretch_file $INPATH`
#
#-------------------------------------------------------
# move to working directory
#-------------------------------------------------------
if (! -e $caldir) then
   echo "ERROR: $caldir directory does not exist"
   echo $banner
   exit $go_absent
endif
cd $caldir
if ($status != 0) then
   echo "ERROR: Failed to set directory to $caldir"
   echo $banner
   exit $go_absent
endif
#-------------------------------------------------------
# copy the trailer file to .tra
#-------------------------------------------------------
\cp  $sisdir/$expname.trx $caldir/$expname.tra
if ($status != 0) then
   echo "ERROR: Failed to copy $sisdir/$expname.trx to cal path $caldir"
   echo $banner
   exit $calib_error
endif
#
#-------------------------------------------------------
# update qolink_sms times using raw science data
#-------------------------------------------------------
#
exposure_times.pl ${expname}_raw.fits | tee -a $expname.tra
if ( $status != 0 ) then
  exit $calib_error
endif
#
#-------------------------------------------------------
# check if calibration is required for this exposure
#-------------------------------------------------------
set calib = `kval {$expname}_spt.fits CALIBRAT`
if ( $calib == 'N' || $calib == 'F' ) then
    echo "PRECAL: calibration not required for $expname" | tee -a $expname.tra
    exit $no_calibration
endif

exit $all_is_well
