#!/bin/csh -f
#+
#
# dither filename [scaleX [scaleY]] [n=Nexp] [laser=/-1/0/1]
#
# takes a series of exposures at different telescope positions.
# Objects in the field will appear shifted by the amounts specified
# in the dither pattern file "filename", with the moves scaled by
# the optional arguments "scaleX" and "scaleY".
#
# The optional "n=Nexp" argument allows Nexp exposures to be taken
# at each dither position.  (Nexp = 1 by default.)  Note that this 
# argument can be positioned anywhere in the argument list.
#
# The dither file must be set up as follows:
#
# first line contains one of: "absolute" or "relative", specifying
# whether the moves are absolute, (0,0) being the starting position 
# of the telescope, or relative to the previous position.
# NOTE THAT THE FIRST (x,y) PAIR GIVEN WILL BE THE POSITION OF THE
# FIRST IMAGE.  The first image is hence only taken at the starting
# position if 0 0 is specified as the first position.
# NOTE ALSO THAT THE TELESCOPE WILL ALWAYS BE MOVED BACK TO ITS
# ORIGINAL POSITION.  It does this using the mark and gomark commands.
#
# second line contains one of: "pixel" or "arcsec", specifying
# whether the offsets are in pixels or arcsec.
#
# subsequent lines should have pairs of numbers, corresponding to the
# desired positions of the objects on the image.
#
# Example:
#
# absolute
# arcsec
# 0 0
# 0 5.5
# 5.5 0
# 5.5 5.5
#
# This six-line file will move in a 5.5 arcsec square with the starting
# position at one corner.  Four images will be taken.
#
# NOTE: some dither patterns are in arbitrary units, and really are meant
# to be scaled by some user-specified "step size".  Generally the step
# size you will see if you forget to scale is 1 arcsec.
#
# History:
# 20??       Original version
# 2010-may-03  MK Mods: 1) added motchill and wfao right before dithers start
#                       2) call xy with -s option to skip wfao check
#                       3) call goi with -s option to skip motchill
# 2011-May-4  MK Added -w flag to goi commands. See goi script for details.
# 2018-Sep-29 CAAI Remove control of the LBWFS
# 2018-Sep-30 CAAI Undo remove control of the LBWFS
# 2019-May-08 jlyke Adapt for OSIRIS imager
# 2020-Jul-05 jlyke Add setting of dither offset keywords
##------------------------------------------------------------------------- 

# Boiler plate for "-h" support for command autohelp.

if ("$1" == "-h") then
    help $0
    exit $status
endif

set scriptrun = `show -s osiris -terse scriptrun`
if ($scriptrun != 0 ) then
  echo "OSIRIS keyword 'scriptrun' must be 0, but is $scriptrun"
  echo "exiting..."
  exit 1
endif
modify -s osiris scriptrun=1

set File   = ""
set scaleX = "none"
set scaleY = "none"
set Nexp   = 1
set laser  = -1
set aoopsmode = 0


while ($#argv > 0)
    set val = "$1"
    if (`echo $val | cut -c1-2` == "n=") then
        set Nexp = `echo $val | cut -c3-`
        # Nexp must be an int >= 1
        if (`isfloat $Nexp`) then
          set Nexp = `round $Nexp`
          if ($Nexp < 1) then
            set Nexp = 1
          endif
        endif

    else if (`echo $val | cut -c1-6` == "laser=") then
        set laser = `echo $val | cut -c7-`
        if (($laser != "0") && ($laser != "1") && ($laser != "-1"))  then
          echo "Unknown laser= argument: $laser"
          echo "Reset to: -1 = Do no harm"
          set laser = -1
        endif

    else
        if (`isfloat $val`) then
            if ("$scaleX" == "none") then
                set scaleX = $val
            else
                set scaleY = $val
            endif
        else
            if (-e $val) then
                set File = "$val"
            else
                echo ""
                echo The specified dither file \"$File\" does not exist.
                echo Please check your current directory and the file name specifed.
                echo Current directory is `pwd`.
                echo ""
                exit 1
            endif
        endif
    endif
    shift
end

# Now make sure we have all of the parameters.

if ("$scaleX" == "none") set scaleX = 1
if ("$scaleY" == "none") set scaleY = $scaleX
if ("$File" == "") then
    echo ""
    echo You have not specified a dither file.
    echo ""
    help $0
    exit 1
endif

onintr abort

# Set global dither keywords
modify -s osiris imagmode="Independent (Imager only)"
modify -s osiris dcoords="instr"
modify -s osiris objpttrn=`basename $File:r`
modify -s osiris skypttrn="none"
modify -s osiris issky=0
modify -s osiris setstatus="`basename $File:r` started"
# Dump the file contents into "argList".
set argList = ( `cat $File | sed '/^#/d' | sed 's/,/ /' ` )

set Mode = $argList[1]

switch ($Mode)
case absolute:
case abs:
    set UseMode = "absolute"
    breaksw

case relative:
case rel:
    set UseMode = "relative"
    breaksw

default:
                                cat <<END1

Dither file must begin with "absolute" or "relative" specifying whether
the moves are absolute, (0,0) being the current telescope position,
or relative to the last telescope position.

END1
    exit 1
    breaksw
endsw

shift argList

set Unit = $argList[1]

switch ($Unit)
case arcsec:
case arcsecs:
case asecs:
    set UseUnits = "arcsec"
    breaksw

case pixel:
case pixels:
case pix:
    set UseUnits = "pixel"
    breaksw

default:
    cat <<END2

The second line of the dither file must be either "arcsec" or "pixel" to
specify what units are used for the dither pattern.

END2
    exit 1
    breaksw
endsw

shift argList

# Done checking first two lines.

if ($UseUnits == "arcsec") then
    set Scale = 1
else
    set Scale = `show -s oids -terse pscale`
    echo camera scale = $Scale
endif

mark

set CurrPos = 1
set Npos = `expr $#argList / 2`

# check AO observing mode
set aoopsmode = `show -s ao -terse aoopsmode`
# echo "AO operation mode: " $aoopsmode
# echo "Laser mode is : " $laser

# 
if ($aoopsmode == "2") then
 echo "Record current dither parms to be restored when script ends"
 set savaolpmove = `show -s ao -terse aolpmove`
 set savaotsmove = `show -s ao -terse aotsmove`
 set savaofmmove = `show -s ao -terse aofmmove`
endif

# set dither parameters for FSM, TSS and Laser M3
# inform operator on observing time
#
#  if AO OPS mode = 0 (full NGS)
#       there is no laser
#       we do not use the TSS
#        - we force the laser not to move
#        - we force TSS not to move
#        - we calculate and print the observing efficiency
#  if AO OPS mode = 1 (NGS with TSS)
#       there is no laser
#       we use TSS
#        - we force the laser not to move
#        - we force TSS to move
#        - we calculate and print the observing efficiency
#        - we set the LBWFS looping parameters
#  if AO OPS mode = 2 (LGS with TSS)
#       there is a laser
#       we use TSS
#        - we check the laser= value
#          if laser= was in the command line, 
#                  we set laser move accordingly
#          else if leave it as it is
#        - we force TSS to move
#        - we calculate and print the observing efficiency
#        - we set the LBWFS looping parameters

if ($aoopsmode == "0") then 
    echo "Observations are performed in NGSAO mode"
    modify -s ao aolpmove = 0
    modify -s ao aotsmove = 0
    modify -s ao aofmmove = 1
else if ($aoopsmode == "1") then
    echo "Observations are performed in dual-NGSAO mode"
    modify -s ao aolpmove = 0
    modify -s ao aotsmove = 1
    modify -s ao aofmmove = 1
    setlbwfstime n=$Nexp 
else if ($aoopsmode == "2") then
    echo "Observations are performed in LGSAO mode"
    modify -s ao aotsmove = 1
#    setlbwfstime n=$Nexp 
    if ($laser == "-1") then 
        echo "No changes to laser dither preset" 
    else if ($laser == "0") then 
        echo "During dither, laser is fixed" 	
	modify -s ao aofmmove = 0
	modify -s ao aolpmove = 0
    else if ($laser == "1") then 
        echo "During dither, laser moves with object" 	
	modify -s ao aofmmove = 1
	modify -s ao aolpmove = 1
    endif
else 
      echo ""
      echo Invalid parameter for AO OPS mode 
      exit 1
endif    
echo " "

# for daytime testing of the script, uncomment
#  exit 1

# ensure we have the imager focus
osirisRefocusAO -x imag
#check that AO system is ready
wfao

# reset the old offset values
set oldxoff = 0
set oldyoff = 0
while ($#argList > 0)

    set dX = `math $scaleX x $argList[1] x $Scale`
    set dY = `math $scaleY x $argList[2] x $Scale`

    echo Moving \($dX,$dY\) arcsec, dither position $CurrPos of $Npos
    if ($UseMode == "relative") then
        # Calculate the relative offset from the previous dither position
        set relxoff = ${dX}
        set relyoff = ${dY}
        set totxoff = `math ${dX} + $oldxoff`
        set totyoff = `math ${dY} + $oldyoff`
        xy $dX $dY
    else
        # Skipped wfao move like the above rel2cur move in xy script.
        # wfao
        set totxoff = $dX
        set totyoff = $dY
        set relxoff = `math ${dX} - $oldxoff`
        set relyoff = `math ${dY} - $oldyoff`
        modify -s dcs instxoff=$dX instyoff=$dY rel2base=t
    endif

    # Remember the current offsets for the next dither position
    set oldxoff = ${totxoff}
    set oldyoff = ${totyoff}
    #
    echo "Moving to position $CurrPos of $Npos ($dX,$dY)"
    if ($aoopsmode != "0") then
       echo ""
       echo "Commanding LBWFS to start n exposures"
       modify -s ao aolbloop = 2
    endif

    
    # Set the dither offset keywords in OGS and in FITS headers
    modify -s osiris dtotoff1=${totxoff} dtotoff2=${totyoff} \
        dlstoff1=${relxoff} dlstoff2=${relyoff}
#    set error = $status
#    if ($error != 0) then
#        osirisScriptMsg -t $idnum -T -W "${cmd}: There was a problem setting"\
#            "the dither offset keywords (dtotoff and dlstoff) in the FITS"\
#            "headers.  They may be incorrect for position ${scount} of"\
#            "dataset #${setnum}."
#    endif

    # will use wffr instead of wfg in the goi script.
    igoi $Nexp

    shift argList
    shift argList
    @ CurrPos++
end
echo Returning to initial telescope position.
gomark

if ($aoopsmode == "2") then
  echo Restoring dither params
  echo "***************************"
  modify -s ao aolpmove = $savaolpmove
  modify -s ao aotsmove = $savaotsmove
  modify -s ao aofmmove = $savaofmmove
endif
osirisScriptCleanUp

exit 0

abort:
#modify -s osiris scriptrun=0
osirisScriptCleanUp
#if ($aoopsmode == "2") then    
#endif
echo Returning to initial telescope position.
echo "***************************************"
echo
echo Temporarily turning wait4ao off
wait4ao save
wait4ao off
gomark
sleep 4
echo Restoring wait4ao to previous state
echo "***************************************"
wait4ao restore

if ($aoopsmode == "2") then
  echo Restoring dither params
  echo "***************************"
  modify -s ao aolpmove = $savaolpmove
  modify -s ao aotsmove = $savaotsmove
  modify -s ao aofmmove = $savaofmmove
endif

exit 1




