#!/usr/bin/sh
#+
# wftel -- wait for telescope to complete a move
#
# Purpose:
#	Pause execution of script until we confirm that the
#	guider has resumed guiding at a new location.  Generally
#	this is used in scripts that perform telescope moves.
#
# Usage:
#	wftel [-D] [-p] [-v] [autresum]
# 
# Options:
#	-p = prime; return the current value of DCS AUTRESUM keyword 
#	so that we can later pass this value back to the script as a
#	reference.
#
#	-v = verbose; print additional output about execution phase and 
#	time
#
#	-D = debug mode (print diagnostics)
#
# Arguments:
#	autresum = value of AUTRESUM keyword prior to the telescope move.
#	If you fail to pass in a value then the loop will probably time out.
# 
# Output:
#	transcript writted to stdout
# 
# Procedure:
#	Second method is to monitor the pause and resume events. After
#	issuing the offset request, we need to monitor the keyword AUTPAUSE
#	to increment its sequence number. Then we monitor the keyword AUTGO
#	to change to RESUMEACK, which is issued by the guider. At this
#	point, the guider will throws away the first image and resume
#	guiding with the next image. The offsetting/nodding script can
#	terminate at this point also, without waiting for guiding to fully
#	resume. Because TCS internally waits for AXESTAT to go from SLEWING
#	to TRACKING before sending the RESUME notification, we assume that
#	the telescope is at the correct position by the time the guider
#	acknowledges the RESUME notification. This will save more time one
#	more guider cycle than the first method at the risk that the guide
#	star may be not at the final destination. This can happen if the
#	plate scale is not correct (i.e. at the edges of the guider
#	detector) and the guide box goes to a different place than the guide
#	star image. The first guider image after the offset will drag the
#	star to where the guide box is.
# 
# Exit values:
#	 0 = normal completion
#	 1 = wrong number of arguments
#
# Example:
#	1) Use this sort of code in a script to ensure that the telescope
#
#		set autresum = `wftel -p` # grab value
#		(perform telescope offset) 
#		wftel -v $autresum
#-
# Modification history:
#	Date Unknown	SHK/MK/GDW	Original version (MOSFIRE)
#	2013-Oct-04	GDW		Adapted for DEIMOS
#	2014-Feb-25	GDW		Make verbose mode work
#-----------------------------------------------------------------------

cmd=`basename $0`
usage="Usage: $cmd"
startTime=`timestamp -s`
wordy=0

# check for command-line flags...
while getopts pvD flag
do case "$flag" in
    D) debug=1;wordy=1;;
    v) wordy=1;;
    p) prime=1;;
    \?)  echo "Usage: $0 [-p] <autresum>" && exit 1;;
esac
done

# remove the options from the command line arg list...
shift `echo $OPTIND-1 | bc`

# check whether autoguider is active...
active=`show -s dcs -terse AUTACTIV`
if [ "$active" = "no" ]
then
    if [ $wordy != 0 ]
    then
	printf "[$cmd] WARNING: guider not currently active\n\a"
    fi
    exit 2
fi

#----------------------------------------
# return autpause
#----------------------------------------
if [ $prime ]
then
  show -s dcs -terse autresum 2>/dev/null
  exit
fi

#----------------------------------------
# wait for AUTPAUSE to increment...
#----------------------------------------

# set the value for the current autpause 
if [ $# = 1 ] 
then 
  i=$1
else  
  i=`show -s dcs -terse autresum 2>/dev/null`
fi

count=0
timeout=20 # max guider exposure time

# cycle until the cycle number increments or the timeout is reached...
if [ $wordy != 0 ]
then
    printf "[$cmd] waiting for AUTRESUM to increment above $i\n"
fi

while [ 1 ]
do
    # check new cycle number...
    j=`show -s dcs -terse autresum 2>/dev/null`

    if [ $debug ]
    then
	printf "[$cmd]   AUTRESUM is now $i (iteration $count/$timeout)\n"
    fi

    
    # if it has changed, then continue...
    if [ $i -ne $j ]
    then
	break
    fi
    
    # increment counter
    count=`expr $count + 1`
    
    # check whether we have exceeded the timeout...
    if [ $count -ge $timeout ]
    then
	printf "[$cmd] WARNING: timeout waiting for AUTRESUM to increment\n\a"
	break
    fi
    
    # pause before continue...
    sleep 1
done

#----------------------------------------
# monitor the keyword AUTGO to change to RESUMEACK, 
# which is issued by the guider 
#----------------------------------------
count=0
timeout=20 # max guider exposure time
desired1="RESUMEACK"
desired2="GUIDE"

if [ $wordy != 0 ]
then
   printf "[$cmd] waiting for AUTGO==$desired1 or $desired2\n"
fi

while [ 1 ]
do

   # check new cycle number...
    buf=`show -s dcs -terse autgo 2>/dev/null`
    autgo=`toupper $buf`

    if [ $debug ]
    then
	printf "[$cmd]   AUTGO is now $autgo (iteration $count/$timeout)\n"
    fi

    # if it has the desired value, then continue...
    if  [ "$autgo" = "$desired1" ] || [ "$autgo" = "$desired2" ] 
    then
	break
    fi
	
    # increment counter
    count=`expr $count + 1`

    # check whether we have exceeded the timeout...
    if [ $count -ge $timeout ]
    then
	printf "[$cmd] WARNING: timeout waiting for AUTGO to be $desired\n\a"
	break
    fi
    
    # pause before continue...
    sleep 1

done

# optional completion message...
if [ $wordy != 0 ]
then
    endTime=`timestamp -s`
    elapsedTime=`calc $endTime - $startTime`
    printf "[$cmd] wftel completed in $elapsedTime sec\n"
fi

exit
