#!/bin/csh -f
#+
#WFGO - OSIRIS library of scripts
#
#NAME
#     wfgo - waits for an exposure to finish
#
#SYNOPSIS
#     wfgo mode [-t #] 
#
#DESCRIPTION
#     waits for current SPEC or IMAG exposure to finish (by monitoring
#     imagedone keyword) and then exits.
#     if waiting period exceeds a threshold, then wfgo times out and exits
#     with an error code.
#
#OPTIONS
#     mode
#          specifies detector, can be "SPEC" or "IMAG"
#
#     -t NUM
#          ID number to attach to all script generated errors, warnings, and
#          questions that are passed to the OGS.  The ID number is separated
#          from the rest of the message with a ";".
#
#EXAMPLES
#     wfgo imag
#          Waits for current IMAG exposure to complete
#
#ENIVIRONMENT VARIABLES
#     none
#
#FILES
#     none
#
#SERVERS & KEYWORDS
#     service = osds/oids
#          keywords: itime, coadds, numreads, imagedone
#
#SCRIPTS CALLED
#     help, syncheck
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error parsing command line input
#     4 - time out error
# 
#SEE ALSO
#     ???
#-
#
# Modification History:
# 20041017 - MB: Copied from NIRC2 and adapted for OSIRIS
# 20050910 - MB: Updated calculation of time to wait
# 20070508 - jlyke: changed to monitor imagedone instead of exposing
#                   and reversed logic test (=0 instead of =1)
# 20120315 - jlyke: Added initial check of status/imagedone to shorten
#                   execution time if no exposure in progress
#
# 20160308 - JLW: convert itime from ms to s for spec (OSIRIS upgrade)
# 20180625 - jlyke: import upwfgo functionality (IMAG itime from ms to s 
#		for imager upgrade)
# 
# Boiler plate for "-h" support for command autohelp.

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

# Boilerplate for syncheck.
# Note that the boiler plate should be transparent for all usages,
# but to make correct use of syncheck you will need to specify the
# correct pattern.

set noglob
set CheckStatus = `syncheck -command $0 $* -pattern [SPEC,spec,IMAG,imag] {text int}` 
unset noglob

if ("$CheckStatus" != "OK") then
    echo 'Type "'${0}' -h" for more help.'
    #help $0 | more
    # set appropriate exit status for syncheck error
    exit 2
endif

# End of help/syncheck boiler plate.

#  set up to trap control-C
onintr reset

# Set default variable values
set idnum = ""
set fcmd = $0
set cmd = ${fcmd:t}

# Decide if we should check SPEC or IMAG
set mode = $1
switch ($mode)
    case "SPEC":
    case "spec":
	set M = "s"
	set mode = "spec"
	set fileOH = 5
	set coaddOH = 20
	breaksw
    case "IMAG":
    case "imag":
	set M = "i"
	set mode = "imag"
	set fileOH = 5
	set coaddOH = 20
	breaksw
    default:
	echo "${cmd} ${mode}: Specified mode must be SPEC or IMAG"
	# set appropriate exit status for command line error
	exit 3
	breaksw
endsw
shift
 
# Check for more flags
set noglob
while ($#argv != 0)
##echo "${cmd} ${mode}: Checking ${1}..."
    switch ($1)
	case -t:
	    set CheckStatus = `syncheck -command $1 $2 -pattern int`
	    if ("$CheckStatus" == "OK") then
		set idnum = $2
		shift
	    else
		echo "${cmd} ${mode}: Invalid script ID number specified"\
		    "<${2}> - using default."
	    endif
	    unset Checkstatus
	    breaksw
	default:
	    echo "${cmd} ${mode}: Invalid command line flag $1 specified."
	    echo "${cmd} ${mode}: Usage: $0 mode [-t #]"
	    # set the error code for an error with command line input
	    exit 2
	    breaksw
    endsw
    shift
end
unset noglob

# First check if an exposure is in progress
set expstatus = `show -s o${M}ds -terse status`
set expstatus = `echo $expstatus[1]`
set done = `show -s o${M}ds -terse imagedone`
if ( $expstatus == "Idling" || $done == 1 ) then
  exit
endif

# Get the current itime and coadds
set itime = `show -s o${M}ds -terse itime`
set coadd = `show -s o${M}ds -terse coadds`
set reads = `show -s o${M}ds -terse numreads`
set readtime = `show -s o${M}ds -terse readtime`

# JLW up: itime now in ms, convert to s
set itime = `math ${itime} / 1000`
set readstime = `math ${reads} x ${readtime}`

# Add some extra to "wait" to allow for miscalculation.
set extra = 60

# Calculate expected integration time.
set wait = `math ${itime} + ${readstime}`
set wait = `math ${wait} x ${coadd} + ${coadd} x ${coaddOH} + ${fileOH}`
set wait = `round ${wait}`
echo "${cmd} ${mode}: Time estimate = ${wait} sec."

set timeout = `math ${wait} + ${extra}`
set timeout = `round ${timeout}`

# Start waiting...
echo "${cmd} ${mode}: Waiting for ${mode} exposure to end."
set count = 0
set test = `show -s o${M}ds -terse imagedone`

while( ($test == 0) && ($count <= $timeout) )
    @ count++
    echo -n .
    sleep 1
    set test = `show -s o${M}ds -terse imagedone`
end

###is this the right way - could miss when imagedone=1 during a sleep

if ( $test == 1 ) then
    echo "OK"
else
    echo ""
    echo "${cmd} ${mode}: ${mode} exposure timed out."
    # set appropriate exit status for time out
    exit 3
endif

exit
 
reset:
###put stuff here
echo "Control C abort detected ... Ending wfgo ${mode}."
# set appropriate exit status for abort
exit 1