#!/bin/tcsh -ef

# DESCRIPTION : 
#           Script to do NOTCam-spectroscopy target acquisition.
#          
#           The user may request a check of the positioning by making
#           an additional test image with the slit in the beam.  In
#           this case the slit will be left in the beam at exit of the
#           script.
#
#           The user may request an interactive query,
#           which allows to do another slitoffset iteration,
#           and/or another slit image.
#
#           This script makes sure that the aperture, filter and grism
#           wheels are correctly positioned.
#
#           Moves to the default internal focus for slit and filter.
#
#
# USAGE :   notcam.acquisition  [-e] -c  -q  cam slit filter expotime
#            -c              make a slitview exposure of target on slit
#            -q              query the user
#            -noslitim       option to NOT take an image of the slit first
#            cam             camera (WF or HR) 
#            slit            slit ID (128 or 44)
#            filter          filter ID (Z=237, Y=236, J=201, H=203 or K=208)
#            expotime        expo time for acquisition image
#
# EXAMPLE:  notcam.acquisition [-e] -c -q -noslitim wf 128 208 3
#
# EXIT STATUS:  
#           0  all OK
#           1  error in command-line arguments
#           2  error returned by Sequencer command
#           3  script ended by CNTR-C
#           4  wrong setup requested
#
# DEPENDS : notcam.setup-spec, notcam.expose,
#
# PROVIDES: notcam.acquisition
#
# TFUNCT  : typically 1-3 minutes
#
# AUTHOR  : AAD (based on JHT alfosc script)
#
# HISTORY : 2013-09-09 adjusted with slit-imaging and sky-subtraction for NOTCam. AAD.
#           2014-03-12 updated to work with upgraded (by PS) slitoff task. AAD.
#           2014-03-17 updated to use imexamin with logfile "slitpos". AAD.
#           2014-04-04 updated to include option to not take a slitimage. AAD.
#

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

if ("$1" == "-e") then
  set e = "echo"
  shift
else
  set e = ""
endif

# Initialise command line parameters
set cam        = ""
set slit       = ""
set fid        = ""
set expotime   = ""
set cflag      = ""
set qflag      = ""
set noslitim   = "no"

# Flag for test image
if ("$1" == "-c") then
  set cflag = "yes"
  shift
endif

# Flag for query
if ("$1" == "-q") then
  set qflag = "yes"
  shift
endif

# Flag for the option to not take a slit image
if ("$1" == "-noslitim") then
  set noslitim = "yes"
  shift
endif

# Get required command line arguments
set cam      = `echo "$1"`
set slit     = `echo "$2" | sed -n -e '/^[0-9.]*$/p'`
set fid      = `echo "$3" | sed -n -e '/^[0-9.]*$/p'`
set expotime = `echo "$4" | sed -n -e '/^[0-9.]*$/p'`

# Check for missing or erroneous arguments
if ($cam == '' || $slit == '' || $fid == '' || $expotime == '') then 
   echo "\e[00;31m Error in arguments\e[00m"
#logger -p local0.debug -t notcam.acquisition "[ERROR]: Script ended on error"
   echo "Usage : notcam.acquisition [-e] -c -q cam slit fid expotime \n"
   echo "        [-e]        = test mode, listing commands only"
   echo "        -c          = "
   echo "        -q          = "
   echo "        -noslitim   = do not take a slit image (not recommended)"
   echo "        cam         = camera (WF or HR)"
   echo "        slit        = slit   (128 or 44)"
   echo "        fid         = filter ID (Z=237, Y=236, J=201, H=203 or K=208)"
   echo "        expotime    = exposure time in seconds"
   exit 1
endif


echo " camera $cam   slit $slit   filter $fid   expotime $expotime   qflag $qflag   cflag $cflag "


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


# Trap CNTR-C
onintr trap

# Define error exit procedure as alias
alias bombNow 'echo "\e[00;31m Error detected, exiting notcam.acquisition\e[00m"; logger -p local0.debug -t notcam.acquisition "[ERROR]: Script ended on error" ; playphone ; sleep 2; notcam.clearobject ; notcam.wcs-align $wcs-align ; exit 2'


# Write to Talker
logger -p local0.debug -t "notcam.acquisition" "[DEBUG]: Script started as $0 $*"


# Test if slit is aligned, TBD later
echo "\n [00;32m This script is interactive. Follow instructions [00m..."

# The grism is not an input parameter to acquisition, but needed for setup-spec
set grism = 1

# Set up NOTCam for spectroscopy, put the requested slit in, check that grism is out
$e notcam.setup-spec $cam $fid $slit $grism
   if ( $? != 0 ) then 
      bombNow
   endif
$e notcam.grism 2
   if ( $? != 0 ) then 
      bombNow
   endif
   if ($slit == 128) then
       set apid = 10
   else if ($slit == 44) then
       set apid = 1
   endif

if ("$noslitim" == "no") then
   echo "\n [00;32m Putting in the selected slit [00m..."
   $e notcam.aperture $apid
   if ( $? != 0 ) then 
      bombNow
   endif
endif

$e playphone
echo "\n [00;32m For VERY bright stars (< 5th mag), add a narrowband filter [00m"   
echo "   [00;32m Select one in Filter 1 within the wavelength range you use [00m..."
echo "\n [00;32m When ready, press any key to continue [00m..."
  set answer = $<

# Make sure we are Autoguiding 
set agmode = `tcs.getstatus AutoguiderModeNumber`
if ( ("$agmode" != "3") && ("$agmode" != "4") ) then
  echo ' \n[00;33mWarning: You are not autoguiding... [00m'
  logger -p local0.debug -t "notcam.acquisition" "[WARNING]: You are not autoguiding..."
  echo ' \n[00;32m Start autoguiding or ignore this warning. Then press any key to continue...[00m'
  set answer = $<
endif


if ("$noslitim" == "no") then
   # Take a slit image at the pointing of your target 
   echo "\n [00;32mMaking the slit image [00m..."
   $e notcam.object "slit image"
   $e notcam.autosave_on
     set tt = `echo "10*$expotime" | bc -l | awk '{printf ("%5i"),$1}'`
     if ($tt < 30) then 
       set slitexpotime = 3
     else 
       set slitexpotime = $expotime
     endif
   $e notcam.setskysub no
   $e notcam.expose $slitexpotime
     if ( $? != 0 ) then 
        bombNow
     endif


   # Get and store current ds9 display orientation setting
   set wcsalign =  `rsh -l postprocess elena "xpaget NOTCAM wcs align"`
   # Set DS9 alignment to none, in order to have the slit horizontal
   $e notcam.wcs-align no
   sleep 0.25

   # Measure centre of slit (in y) at default x for position A. The x,y values are 
   # stored in the slitpos logfile, and the last value will be used as slit-position 
   # by the "slitoff" task.

   echo "\n [00;32m Use imexam to measure y at default x for position A [00m..."
   echo " [00;31m NB! Set scale to minmax on DS9 to see the slit!  [00m..."  
   echo " [00;32m Locate cursor, press 'k', then 'q' to quit [00m..."
   $e notcam.imexam slitpos
     if ( $? != 0 ) then 
        bombNow
     endif
endif

# Set aperture wheel to open position
echo "\n [00;32m Taking out the slit [00m..."
if ($cam == "WF" || $cam == "wf") then 
      $e notcam.aperture 4
      if ( $? != 0 ) then 
         bombNow
      endif
else if ($cam == "HR" || $cam == "hr") then
      $e notcam.aperture 8
      if ( $? != 0 ) then 
         bombNow
      endif
endif


# Make the first acquisition image
echo "\n [00;32mMaking the first acquisition image [00m..."
$e notcam.setskysub no
$e notcam.object "acquisition"
$e notcam.expose $expotime
   if ( $? != 0 ) then 
      bombNow
   endif
$e notcam.wcs-align yes
sleep 0.25
# Potentially use this image as the sky-subtraction image
set skyimage = `cd /data/notcam; ls -rt NC*fits | tail -1`


# Ask if sky subtraction is needed, and if so, do another iteration
echo "\n\e[00;35m Do you need sky subtraction to see your target? Then enter '[00my[00;35m'. [00m"
echo "  [00;35m Enter any other key to continue [00m... " 
set skyanswer = $<
if ($skyanswer == 'y' || $skyanswer == 'Y') then
   echo "\n [00;32m Doing teloffset and another acquisition image [00m..."
   $e notcam.teloffset -10 0
   $e notcam.setskysub $skyimage
   $e notcam.expose $expotime
   if ( $? != 0 ) then 
      bombNow
   endif
else 
   $e notcam.setskysub no
endif


# Use the interactive slitoff task to move target to slit position A.
# By using the option "uselog", the last measured slit position is used.

echo "\n [00;32m Put cursor on target, press a or x, and then q [00m..."
$e notcam.slitoff uselog
   if ( $? != 0 ) then 
      bombNow
   endif


# Make iteration image, potentially with skysubtraction

NextIteration:

if ($skyanswer == 'y' || $skyanswer == 'Y') then
   $e notcam.setskysub $skyimage
else
   $e notcam.setskysub no
endif

echo "\n [00;32m Making another acquisition image [00m..."
$e notcam.expose $expotime
if ( $? != 0 ) then 
   bombNow
endif

$e notcam.slitoff uselog
if ( $? != 0 ) then 
   bombNow
endif


TestImage:

# Make a test image of slit+star if requested 
if ("$cflag" == "yes") then
    if ($slit == 128) then
      set apid = 10
      $e notcam.object "128slit+target"
    else if ($slit == 44) then
      set apid = 1
      $e notcam.object "44slit+target"
    endif
echo "\n [00;32m Putting in the selected NOTCam slit [00m..."
   $e notcam.aperture $apid
   if ( $? != 0 ) then 
      bombNow
   endif
  echo "\n [00;32m Imaging target on slit [00m..."
  $e notcam.setskysub no
  $e notcam.expose $expotime
  if ( $? != 0 ) then 
     bombNow
  endif
  # Set ds9 display orientation back to detector 'coordinates'
  notcam.wcs-align no
  sleep 0.25
endif


# Let user decide whether to loop back or not
if ("$qflag" == "yes") then
  echo "\n  [00;35m Let this script do another interactive iteration?  Then enter '[00my[00;35m'. [00m"
  echo "  [00;35m Enter any other key to continue [00m... "
  set answer=$<

  if (("$answer" == "y")  || ("$answer" == "Y")) then

    # Set aperture wheel to Open
    echo "\n [00;32m Setting NOTCam aperture wheel to OPEN position [00m..."
    $e notcam.aperture 4
    if ( $? != 0 ) then 
       bombNow
    endif
    
    $e notcam.object "acquisition"
    $e notcam.wcs-align yes
    sleep 0.25
 
    goto NextIteration

  endif


  if ("$cflag" == "yes") then

    echo "\n  [00;35m Take another slit image?  Will be done right after you enter '[00my[00;35m'. [00m"
    echo "  [00;35m Enter any other key to exit [00m... "
    set answer=$<

    if (("$answer" == "y")  || ("$answer" == "Y")) then

      goto TestImage

    endif
  endif
endif


$e notcam.clearobject
if ( $? != 0 ) then 
   bombNow
endif


# Set back original display orientation setting
$e notcam.wcs-align $wcsalign

echo "\n [00;32m Remember to put in grism before starting ABBA script\!  [00m\n"

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




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

trap:
echo "\n [00;31m CNTR-C detected\! [00m"
echo "\n [00;31m Wait for exposure to finish. NOTcam exposures can not be aborted\! "

$e notcam.clearobject
if ( $? != 0 ) then 
   bombNow
endif

# Set back original display orientation setting
$e notcam.wcs-align $wcsalign

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