#!/bin/tcsh -f

# DESCRIPTION : sets the NOTCam calibration items (telescope mirror covers and
#           baffle lamps) up for a calibration image, takes the calibration 
#           image(s), switches off lamps, and per default opens mirror covers 
#           again at exit if and only if the upper hatch is already open (i.e. 
#           night-time observing), and then switches on the TV, regains the
#           previously used TV-filter (using store-tel and restore-tel) and
#           restarts autoguiding using auto-positioning-retry.
#
#           Does not touch the NOTCam setup!
#
#           Switches autosave_on, and leaves it on.
#           Switches off autoguiding if not already off.
#           Switches off the guide TV if not already off.
#           Closes mirror-covers if not already closed.
#
#           If an Object name is given, then the string will be added
#           to the already present lamp specifier in the OBJECT FITS keyword.
#
#           Sets IMTYPE to FLAT/WAVE .
#
#           If CNTR-C is pressed the ongoing exposure will be aborted, and the
#           calibration mirror will be moved out of the beam.
#           What to do with CTRL-C for NOTCam scripts? It does not abort the
#           exposure, only the script itself.
#
#
#
# USAGE :   notcam.calibexp [-e] [-n Nexp] [-o "Object Name"] [-LeaveMirrorClosed] [-lmc] [-llo] lampID exptime  
#            -e                    echoing mode, do not execute  
#            -n Nexp               optional number of exposures (default=1)
#            -o ObjectName         optional ObjectName
#            -LeaveMirrorClosed    if set the mirror covers will stay closed at exit
#            -lmc                  if set the mirror covers will stay closed at exit
#            -llo                  if set the lamp is left on at exit
#            lampID                lampID=Halogen/Argon/Xenon 
#            exptime               exposure time
#
# EXIT STATUS:  
#           0  all OK
#           1  error in command-line arguments
#           2  error returned by Sequencer command
#           3  script ended by CNTR-C
#
#
# DEPENDS : notcam.expose, notcam.autosave_on, notcam.object, notcam.imtype 
#           tcs.open-mirror-covers, tcs.close-mirror-covers, tcs.tv-on, tcs.tv-off,
#           tcs.baffle-lamp-1-on, tcs.baffle-lamp-1-off, tcs.baffle-lamp-2-on,
#           tcs.baffle-lamp-2-off, tcs.baffle-lamp-3-on, tcs.baffle-lamp-3-off,
#           tcs.ag-on, tcs.ag-off,
#           tcs.store-tel, tcs.restore-tel, tcs.tv-filter, tcs.auto-positioning-retry,
#           tcs.restore-tv-fil
#
# PROVIDES: notcam.calibexp
#
# TFUNCT  : 
#
# AUTHOR  : JHT/AAD
#
# HISTORY : 12/2008 created by JHT for ALFOSC
#
#           13/09/2010 modified by AAD for NOTCam, using baffle lamps
#           28/10/2010 updated to use store-tel/restore-tel to find the correct TV-filter (AAD)
#           13/04/2011 added script parameters to talker log, AAD
#           09/05/2012 updated to include option "leave lamp on" [-llo] at exit (AAD)
#           11/06/2012 modified to use "tcs.restore-tv-fil" to cut down overheads (AAD)


# Initialise command line parameters
set e          = "" 
set lmc        = False
set llo        = False
set objectName = ""
set lampID     = ""
set expotime   = ""
set Nexpo      = 1

# Initialise internal parameters
set showUsage  = False

# Process command-line arguments; they can be given in any order.
while ( "$1" != "" )

   ## Leave mirror in?
   if ( "$1" == "-lmc" || "`echo $1 | tr "A-Z" "a-z"`" == "-leavemirrorclosed" ) then   
      set lmc = True
      shift

   ## Leave lamp on?
   else if ( "$1" == "-llo") then
      set llo = True
      shift

   ## Object name
   else if ( "$1" == "-o" ) then 
      shift
      set objectName = "$1"
      shift

   ## Number of exposures
   else if ( "$1" == "-n" ) then 
      shift
      set Nexpo  = `echo "$1" | sed -n -e '/^[0-9.]*$/p'`              ## Do some filtering to allow only numbers
      if ($Nexpo == '' ) then 
          echo "\n [00;31m-n $1[00m"
          set showUsage = True
          break
      endif
      shift

   ## Echo/test mode
   else if ( "$1" == "-e" ) then 
      set e = "echo" 
      shift

   ## Lamp to be used
#  else if ( "$1" == "-l" ) then 
#     shift
   else 
      set lampID  = "`echo $1 | tr "A-Z" "a-z"`"                       ## Use 'tr' to allow upper/lower case
      ## Now set to proper upper/lower case strings
      if ( $lampID == "halogen" ) then 
          set lampID = "Halogen"
      else if ( $lampID == "argon" ) then 
          set lampID = "Argon"
      else if ( $lampID == "xenon" ) then 
          set lampID = "Xenon"
      else
          #echo "\n [00;31m-l $1[00m"
          echo "\n [00;31mWrong argument $1[00m"
          set showUsage = True
          break
      endif
      shift

   ## Exposure time
#  else if ( "$1" == "-t" ) then 
#     shift
      set expotime  = `echo "$1" | sed -n -e '/^[0-9.]*$/p'`           ## Do some filtering to allow only numbers
      if ($expotime == '' ) then 
          #echo "\n [00;31m-t $1[00m"
          echo "\n [00;31mWrong argument $1[00m"
          set showUsage = True
          break
      endif
      shift
   
#  ## Wrong command-line argument
#  else 
#     echo "[00;31m\n $1[00m"
#     set showUsage = True
#     break
   endif
end

if ($lampID == "" || $expotime == "") then 
  set showUsage = True
  echo " [00;31mRequired command-line parameter missing: lampID or exptime[00m"
endif

# Bomb if any arguments are not OK
if ( $showUsage == True ) then
   echo " Inadequate command-line argument detected ! "
   echo ' Usage :  notcam.calibexp  [-n Nexp]                     number of expos if not 1'
   echo '                           [-o "Object Name"]            quoted name'
   echo '                           [-LeaveMirrorClosed] [-lmc]   leave mirror covers closed'
   echo '                           [-llo]                        leave selected lamp on'
   echo '                           [-e]                          test mode'
   echo '                           lampID                        Halogen/Argon/Xenon'
   echo '                           exptime                       in seconds'
   exit 1
endif

#echo lmc $lmc echomode $e  expotime $expotime
#echo lampID $lampID  Nexpo $Nexpo  objectName $objectName


###### Start the real stuff ######

#echo "\n [00;32m notcam.calibexp started [00m ...\n"

# Trap CNTR-C
onintr trap


# Define exit procedure as alias
alias bombNow 'echo "Error detected: exiting notcam.calibexp";    logger -p local0.debug -t notcam.calibexp "[WARNING]: Script ended on error" ;      playphone;   exit 2'


# Write to Talker
logger -p local0.debug -t "$0" "[NOTE]: Script started as $0 $*"
#logger -p local0.debug -t "notcam.calibexp" "[NOTE]: Script started"
#echo " [00;32mSetting up for NOTCam calibrations [00m..."

# Get the telescope status
set auto_guiding            = `tcs.getstatus AutoguiderModeNumber`
set power_on               = `tcs.getstatus PowerIsOn`
set upper_hatch_opened     = `tcs.getstatus UpperHatchOpened`
set mirror_covers_closed   = `tcs.getstatus MirrorCoversClosed`
set mirror_covers_opened   = `tcs.getstatus MirrorCoversOpened`
set tv_on                  = `tcs.getstatus TVisOn`

# Stop auto-guiding
if ($auto_guiding != '0') then
   echo " [00;32mSwitching auto-guiding off [00m..."
   $e tcs.ag-off
endif
if ($? != 0) then
  bombNow
endif

# Switch off the guide TV if not already off
if ($tv_on == '1') then
   $e tcs.store-tel my-tel-config
   echo " [00;32mSwitching guide TV off [00m..."
   $e tcs.tv-off
endif
if ($? != 0) then
  bombNow
endif

# Switch on the Argon lamp to ensure it will be on by the time the
# mirror covers are closed
$e tcs.baffle-lamp-2-on

# Close mirror covers if they are not already closed
if ($mirror_covers_opened == '1') then
   echo " [00;32mClosing mirror covers, takes 40 seconds [00m..."
   $e tcs.close-mirror-covers
endif
if ($? != 0) then
  bombNow
endif

# Switch the requested lamp on, all others off
if ( $lampID == Halogen) then 
  set imtype = 'FLAT'
  echo " [00;32mSwitching on the Halogen lamp [00m..."
  $e tcs.baffle-lamp-1-on
else
  $e tcs.baffle-lamp-1-off
endif
if ($? != 0) then
  bombNow
endif
sleep 0.2

if ( $lampID == Argon) then 
  set imtype = 'WAVE'
  echo " [00;32mSwitching on the Argon lamp [00m..."
  $e tcs.baffle-lamp-2-on
#  sleep 30
else
  $e tcs.baffle-lamp-2-off
endif
if ($? != 0) then
  bombNow
endif
# the argon lamp is known to be slow, so a "sleep 30" is added
sleep 0.2

if ( $lampID == Xenon) then 
  set imtype = 'WAVE'
   echo " [00;32mSwitching on the Xenon lamp [00m..."
  $e tcs.baffle-lamp-3-on
else
  $e tcs.baffle-lamp-3-off
endif
if ($? != 0) then
  bombNow
endif
sleep 0.2

$e notcam.autosave_on

# Do the exposures
set expcount = 0
while ($expcount < $Nexpo)
  @ expcount++
  if ( $Nexpo > 1 ) then 
    $e notcam.object "$lampID $expcount $objectName"
  else
    $e notcam.object "$lampID $objectName"
  endif
  if ($? != 0) then
    bombNow
  endif

  # Set IMTYPE to FLAT/WAVE
  $e notcam.imtype $imtype
  if ($? != 0) then
    bombNow
  endif

  # Start exposure
  echo " [00;32mStart calibration exposure $expcount [00m..."
  $e notcam.expose $expotime
  if ($? != 0) then
     bombNow
  endif

end

# Switch the lamp off (or not)
if ($llo == False) then 
   echo " [00;32mSwitching lamp off [00m..."
endif
if ($llo == True) then
   echo " [00;32mLeaving lamp on! [00m..."
endif

if ( "$lampID" == "Halogen" ) then
#  echo "Switching off the Halogen lamp." 
  if ($llo == False) then
      $e tcs.baffle-lamp-1-off
  endif
endif
if ($? != 0) then
  bombNow
endif
if ( "$lampID" == "Argon" ) then 
#  echo "Switching off the Argon lamp."
  if ($llo == False) then
      $e tcs.baffle-lamp-2-off
  endif
endif
if ($? != 0) then
  bombNow
endif
if ( "$lampID" == "Xenon" ) then 
#  echo "Switching off the Xenon lamp."
  if ($llo == False) then
      $e tcs.baffle-lamp-3-off
  endif
endif
if ($? != 0) then
  bombNow
endif


# If calibrations for this sky position finished
if ( $lmc == False ) then

  # If the upper hatch is open, then and only then open the mirror covers
  if ($upper_hatch_opened == '1') then

     # If a lamp was left on, at this point it must be switched off!
       if ($llo == True) then
       echo " [00;32m Switching all lamps off [00m..."
          $e tcs.baffle-lamp-1-off
          $e tcs.baffle-lamp-2-off
          $e tcs.baffle-lamp-3-off
       endif

     echo " [00;32m Opening mirror covers, takes 45 seconds [00m..."
     $e tcs.open-mirror-covers -f
        if ($? != 0) then
          bombNow
        endif
     sleep 1
     echo " [00;32m Because the upper hatch is open, the TV is switched on [00m..."    
     $e tcs.tv-on
        if ($? != 0) then
           bombNow
        endif   
    $e tcs.restore-tvfil -noconfirm my-tel-config         
#      $e tcs.restore-tel -noconfirm my-tel-config 
#      $e tcs.restore-tel my-tel-config
        if ($? != 0) then
           bombNow
        endif   
      echo " [00;32m TV-filter should now be set back [00m..."
      $e tcs.auto-positioning-retry
        if ($? != 0) then
           bombNow
        endif   
      echo " [00;32m Auto-guiding should be back on [00m..."
  else 
     echo " [00;31mUpper hatch is not open - therefore leaving the mirror covers closed [00m..."
  endif
else
# If you wish to continue taking calibration exposures
     echo " [00;32mLeaving the mirror covers closed as requested [00m..."
endif

# All done. Exit with error status 0 and write to Talker
logger -p local0.debug -t "notcam.calibexp" "[NOTE]: Script ended successfully"
echo "\n [00;32m notcam.calibexp ready [00m\n"
exit 0



########## CNTR-C handler ##########

trap:
echo "\n [00;31mCNTR-C detected\! [00m"

echo "\n [00;31m Wait for exposure to finish. NOTcam exposures can not be aborted! [00m"

#echo " [00;32mAborting exposure [00m..."
#alfosc.abort
#if ($? != 0) then
#  bombNow
#endif

# Leave telescope mirror covers closed upon Ctrl-C
echo " [00;32mLeaving mirror covers closed [00m..."

#$e alfosc.mirror out
#if ($? != 0) then
#  bombNow
#endif

# Exit with error status 3 and write to Talker
logger -p local0.debug -t "notcam.calibexp" "[WARNING]: Script ended by CNTR-C"
echo "\n [00;32m notcam.calibexp stopped \![00m \n"
exit 3
