#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     wfao - waits for AO loops to close
#
#SYNOPSIS
#     wfao [-noask] [-t #]
#
#DESCRIPTION
#     waits for the AO tip/tilt and deformable mirror loops to close.
#     Note that the behavior is controllable through the keywords:
#
#	WFTT	wait for tip-tilt
#	WFDM	wait for deformable mirror
#	WFDAR	offload DAR (differential atmospheric refraction) moves
#
#OPTIONS
#     -noask
#          if this flag is given, wfao will not ask the user whether to
#          continue if a waitfor timeout is reached - it will simply exit
#          with an error code
#
#     -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 ";".  ID number is needed for
#          use with the ODEC, not needed if used from the command line.
#
#EXAMPLES
#     wfao -t 123456
#
#ENVIRONMENT VARIABLES
#     none
#
#FILES
#     none
#
#SERVERS & KEYWORDS
#     service = osiris
#          keywords: wftt, wfdm, wfdar, AOTTOFLD, aodelay,
#                    script...
#
#     service = ao
#          keywords: dtclxoff, dtclyoff, aowfslav, obfmgoim, aodtstat,
#                    aodmstat, obwfstst, 
#
#SCRIPTS CALLED
#     help, syncheck
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error accessing servers
#     4 - error with a wf flag
#     5 - timed out waiting for 
#
#SEE ALSO
#     ???
#-
#
# Modification History:
# 20050220 - MB: Adapted from NIRC2 scripts
# 20051122 - MB: Major restructuring! includes:
#                Better checking of wait4xx keywords
#                Lots more error handling
#                Fewer messages written to scriptwarn
#                More streamlined exitting when a timeout occurs
#                Added "-noask" flag and associated functionality
# 20210426 - jlyke: added pop-up to ease setting osiris.SCRIPTREPLY
# 

# 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.

# More advanced argument checking required, see below

# End of help/syncheck boiler plate.

# Set up to trap interrupts
onintr break

# Set default values
set idnum = 0
set timeOut = 30
set fcmd = $0
set cmd = ${fcmd:t}
set ogscmdpre = "" # functionality not implemented, but variable is used
set ogscmdsuf = "" # functionality not implemented, but variable is used
set aocmdpre = "" # functionality not implemented, but variable is used
set aocmdsuf = "" # functionality not implemented, but variable is used

# Parse command line flags and arguments
### osirisScriptMsg -T "${cmd}: Parsing command line arguments."
set noglob
while ($#argv != 0)
    #echo Checking ${1} ...
    switch ($1)
	case -noask:
	    osirisScriptMsg -T "${cmd}: Entering no-ask mode."
	    set noask
	    breaksw

	case -t:
	    set CheckStatus = `syncheck -command $1 $2 -pattern float`
	    if ("$CheckStatus" == "OK") then
		set idnum = $2
		shift
	    else
		osirisScriptMsg -T "${cmd}: Invalid script ID number"\
		    "specified <${2}> - using <${idnum}>."

		# Check if we should shift the arguments (we want to if
		# there was a parameter for the current flag)
		set firstchar = `echo $2 | cut -c1`
		if ("${firstchar}" != "-") then
		    shift
		endif
		unset firstchar
	    endif
	    unset Checkstatus
	    breaksw

	default:
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Unknown flag"\
		"specified <$1> - wfao aborted."
	    set exitcode = 2
	    goto done
	    breaksw
    endsw
    shift
end
unset noglob


# Check the OSIRIS global server
set osiris_server_up = `osirisCheckServer osiris`
if ($osiris_server_up) then
    # Continue with script
else
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Global server does"\
	"appear to be running.  Please check the health of the global server"\
	"- wfao aborted."
    set exitcode = 3
    goto done
endif


# Get the current setstatus keyword value so it can be restored later
set old_setstatus = `show -s osiris -terse setstatus`
set error = $status
if ($error != 0) then
    osirisScriptMsg -T "${cmd}: Error getting osiris setstatus keyword"\
	"- wfao will continue."
    set old_setstatus = " "
endif


# Offload DAR move accumulation.
# Note that in this script the FCS is unslaved from the FSMs.
# This makes the assumption that the FSM moves are small.  We can
# make that assumption here because larger DAR moves due to telescope
# moves are taken up automatically by the AO system.

# Check WFDAR behavior keyword values.
set wfdar = `show -s osiris -terse wfdar`
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting osiris"\
	"wfdar keyword (show error #${error}) - wfao aborted."
    set exitcode 3
    goto done
endif

switch ($wfdar)
    case off:
	# Don't warn the observer... this is unnecessary - MB 20050824
	# osirisScriptMsg -t $idnum -T -W "${cmd}: Advisory: wfao is not"\
	#    "offloading DAR moves."
    breaksw

    case on:
	# Check magnitude of DTCLOF (the amount of DAR taken up by the down
	# tip-tilt control loops).  If it is more than "maxDAR", offload it.
	# Otherwise leave the FSMs alone.

	set dtxDAR  = ( `show -s ao -terse dtclxoff` )
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting"\
		"AO dtclxoff keyword (show error #${error}) - wfao aborted."
	    set exitcode 3
	    goto done
	endif

	set dtyDAR  = ( `show -s ao -terse dtclyoff` )
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting"\
		"AO dtclyoff keyword (show error #${error}) - wfao aborted."
	    set exitcode 3
	    goto done
	endif

	# The DTCLOF numbers need to be scaled to milliarcseconds.
	# The magnitude of the offset is calculated and compared to some
	# maximum allowable value.  If larger than this value, the FSM is
	# asked to offload the DAR.

	set maxDAR  = `show -s osiris -terse AOTTOFLD`
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting"\
		"osiris AOTTOFLD keyword (show error #${error}) - wfao aborted."
	    set exitcode 3
	    goto done
	endif

	set dtScale = 0.00002
	set magDAR  = `math "$dtScale x sqrt($dtxDAR x $dtxDAR + $dtyDAR x $dtyDAR)"`
	set test    = `math $maxDAR - $magDAR | grep '-'`

	if ("$test" != "") then
	    set count = 0
	    osirisScriptMsg -T "${cmd}: Unslaving FCS."
	    $aocmdpre modify -s ao aowfslav = false
	    set error = $status
	    if ($error != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
		    "setting AO keyword aowfslav (modify error #${error})"\
		    "- wfao aborted."
		set exitcode 3
		goto done
	    endif

	    osirisScriptMsg -T "${cmd}: Offloading accumulated DAR"\
		"(diff. atm. refraction) moves to FSMs."
	    if ($?noask) then
		# Don't update the setstatus keyword
	    else
		osirisScriptMsg -t $idnum -S "Offloading DAR moves."
	    endif

	    $aocmdpre modify -s ao obfmgoim = true
	    set error = $status
	    if ($error != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
		    "setting AO keyword obfmgoim (modify error #${error})"\
		    "- wfao aborted."
		set exitcode 3
		goto done
	    endif

	    wait4fsm

	    osirisScriptMsg -T "${cmd}: Reslaving FCS."
	    $aocmdpre modify -s ao aowfslav = true
	    set error = $status
	    if ($error != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
		    "setting AO keyword aowfslav (modify error #${error})"\
		    "- wfao aborted."
		set exitcode 3
		goto done
	    endif
	else
	    osirisScriptMsg -T "Amount of DAR in tip-tilt only $magDAR;"\
		"skipping offloading to FSMs."
	endif
    breaksw

    default:
	osirisScriptMsg -t $idnum -T -W "${cmd}: Unknown value for wfdar"\
	    "keyword <${wfdar}> - wfao aborted."
	set exitcode = 4
	goto done
    breaksw
endsw
 

# Check WFTT and WFDM behavior keyword values.
set wftt  = `show -s osiris -terse wftt`
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting osiris"\
	"wftt keyword (show error #${error}) - wfao aborted."
    set exitcode 3
    goto done
endif

set wfdm  = `show -s osiris -terse wfdm`
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting osiris"\
	"wfdm keyword (show error #${error}) - wfao aborted."
    set exitcode 3
    goto done
endif


# Alert the user if both WFTT and WFDM are false, and exit script
if ("$wftt" == "off" && "$wfdm" == "off") then
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Advisory: wfao is"\
	"not waiting for AO locks."
    set user_alerted
    goto done
endif


# Wait for tip-tilt.
switch ($wftt)
    case off:
	if ($?user_alerted) then
	    # Don't warn the user again
	else
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Advisory:"\
		"wfao is not waiting for TT lock."
	endif
    breaksw

    case on:
	set count = 0
	osirisScriptMsg -T "${cmd}: Waiting for AO tip/tilt loop to close..."
	if ($?noask) then
	    # Don't update the setstatus keyword
	else
	    osirisScriptMsg -t $idnum -S "Waiting for AO TT loop..."
	endif

	while( $count < $timeOut )
	    set test = `show -s ao -terse aodtstat`
	    set error = $status
	    if ($status != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: ERROR"
		    "trying to read the tip-tilt status - wfao aborted."
		set exitcode = 3
		goto done
	    endif

	    if ( $test == 'closed' ) then 
		osirisScriptMsg -t $idnum -T "${cmd}: Tip/Tilt loop closed"
		break
	    endif
	    sleep 1
	    @ count++
	end # while ($count < $timeOut)

	# Was the timeout period reached for TT?
	if ($count >= $timeOut) then
	    if ($?noask) then
		# Don't ask the user if they want to continue, just exit
		osirisScriptMsg -T "${cmd}: Timed out waiting for TT"\
		    "loop - wfao aborted."
		set exitcode = 5
		goto done
	    else
	        # Ask the user if they want to continue
		$ogscmdpre modify -s osiris scriptreply="r"
		osirisScriptMsg -t $idnum -T -A $ogscmdsuf "${cmd}:"\
		    "Timed out waiting for TT loop.  If TT lock is not"\
		    "required, please turn wait4tt OFF for future"\
		    "exposures.  Do you want to continue now?"
		osirisScriptMsg -T "${cmd}: Set scriptreply keyword to"\
		    "Y or N to respond."
		osirisScriptMsg -T "${cmd}: Waiting for response."

                # pop-up a window to ease setting scriptreply                 
                osirisScriptReplyWrapper

		# Don't change any other OGS keywords (that ODEC pays
		# attention to) here while the modal dialog is up on
		# ODEC, otherwise bad things happen... MB 1/6/05

		set reply = `show -s osiris -terse scriptreply`
		while ("$reply" == "r")
		    echo -n "."
		    sleep 1
		    set reply = `show -s osiris -terse scriptreply`
		end

		# should there be a timeout here?

		switch ($reply)
		    case Y:
		    case y:
		        echo ""
			osirisScriptMsg -T "${cmd}: ${reply} detected"\
			    "- resuming wfao."
		    breaksw

		    case N:
		    case n:
		        echo ""
			osirisScriptMsg -T "${cmd}: ${reply} detected"\
			    "- wfao aborted."
			set exitcode = 3
			goto done
		    breaksw

		    default:
			echo ""
			osirisScriptMsg -T "${cmd}: invalid response"\
			    "<${reply}> - wfao aborted."
			set exitcode = 3
			goto done
		    breaksw
		endsw # switch ($reply)
	    endif # if ($?noask)
	endif # if ($count >= $timeOut)
    breaksw

    default:
	osirisScriptMsg -t $idnum -T -W "${cmd}: Unknown value for wftt"\
	    "keyword <${wftt}> - wfao aborted."
	set exitcode = 4
	goto done
    breaksw
endsw


# Check WFDM again, in case user has switched it after getting WFTT warnings
set wfdm  = `show -s osiris -terse wfdm`
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error getting osiris"\
	"wfdm keyword (show error #${error}) - wfao aborted."
    set exitcode 3
    goto done
endif


# Wait for deformable mirror if asked.
switch ($wfdm)
    case off:
	if ($?user_alerted) then
	    # Don't warn the user again
	else
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Advisory:"\
		"wfao is not waiting for DM lock."
	breaksw

    case on:
	set count = 0
	osirisScriptMsg -T "${cmd}: Waiting for AO DM loop to close..."
	if ($?noask) then
	    # Don't update the setstatus keyword
	else
	    osirisScriptMsg -t $idnum -S "Waiting for AO DM loop..."
	endif

	while( $count < $timeOut )
	    set test = `show -s ao -terse aodmstat`
	    set error = $status
	    if ($status != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: ERROR"
		    "trying to read the DM status - wfao aborted."
		set exitcode = 3
		goto done
	    endif

	    if ( $test == 'closed' ) then 
		osirisScriptMsg -t $idnum -T "${cmd}: DM loop closed"

		# Now we have to wait for the FCS to settle.
		set count2 = 0
		osirisScriptMsg -T "${cmd}: Waiting for FCS to settle..."
		if ($?noask) then
		    # Don't update the setstatus keyword
		else
		    osirisScriptMsg -t $idnum -S "Waiting for FCS to settle..."
		endif

		while( $count2 < $timeOut )
		    set test2 = `show -s ao -terse obwfstst`
		    set error = $status
		    if ($error != 0) then
			osirisScriptMsg -t $idnum -T -W $ogscmdsuf \
			    "${cmd}: ERROR trying to read FCS status -"\
			    "wfao aborted."
			set exitcode = 3
			goto done
		    endif

		    if ( $test2 == 'INPOS') then
			osirisScriptMsg -T "${cmd}: FCS settled"
			break
		    else if ( $test2 == 'TRACK' ) then
			osirisScriptMsg -T "${cmd}: FCS tracking"
			break
		    endif
		    sleep 1
		    @ count2++
		end # while ($count2 < $timeOut)

		# Was the timeout period reached for FCS?
		if ($count2 >= $timeOut) then
		    if ($?noask) then
			# Don't ask user if they want to continue, just exit
			osirisScriptMsg -T "${cmd}: Timed out waiting for FCS"\
			    "to settle - wfao aborted."
			set exitcode = 5
			goto done
		    else
			# Ask the user if they want to continue
			$ogscmdpre modify -s osiris scriptreply="r"
			osirisScriptMsg -t $idnum -T -A $ogscmdsuf "${cmd}:"\
			    "Timed out waiting for FCS to settle.  If FCS"\
			    "settling is not required, please turn wait4dm"\
			    "OFF for future exposures.  Do you want to"\
			    "continue now?"
			osirisScriptMsg -T "${cmd}: Set scriptreply keyword"\
			    "to Y or N to respond."
			osirisScriptMsg -T "${cmd}: Waiting for response."

                        # pop-up a window to ease setting scriptreply 
                        osirisScriptReplyWrapper

			# Don't change any other OGS keywords (that ODEC pays
			# attention to) here while the modal dialog is up on
			# ODEC, otherwise bad things happen... MB 1/6/05

			set reply = `show -s osiris -terse scriptreply`
			while ("$reply" == "r")
			    echo -n "."
			    sleep 1
			    set reply = `show -s osiris -terse scriptreply`
			end

			# should there be a timeout here?

			switch ($reply)
			    case Y:
			    case y:
				echo ""
				osirisScriptMsg -T "${cmd}: ${reply} detected"
				    "- resuming wfao."
			    breaksw

			    case N:
			    case n:
				echo ""
				osirisScriptMsg -T "${cmd}: ${reply} detected"
				    "- wfao aborted."
				set exitcode = 3
				goto done
			    breaksw

			    default:
				echo ""
				osirisScriptMsg -T "${cmd}: invalid response"\
				    "<${reply}> - wfao aborted."
				set exitcode = 3
				goto done
			    breaksw
			endsw # switch ($reply)
		    endif # if ($?noask)
		endif # if ($count2 >= timeOut)

		# Now get out of DM while loop (since it's closed)
		break
	    endif # if ($test == 'closed')

	    # Wait a second and repeat while loop
	    sleep 1
	    @ count++
	end # while ($count < timeOut)

	# Was the timeout period reached for DM?
	if ($count >= $timeOut) then
	    if ($?noask) then
		# Don't ask the user if they want to continue, just exit
		osirisScriptMsg -T "${cmd}: Timed out waiting for DM"\
		    "loop - wfao aborted."
		set exitcode = 5
		goto done
	    else
		# Ask the user if they want to continue
		$ogscmdpre modify -s osiris scriptreply="r"
		osirisScriptMsg -t $idnum -T -A $ogscmdsuf "${cmd}:"\
		    "Timed out waiting for DM loop.  If DM lock is not"\
		    "required, please turn wait4dm OFF for future"\
		    "exposures.  Do you want to continue now?"
		osirisScriptMsg -T "${cmd}: Set scriptreply keyword to"\
		    "Y or N to respond."
		osirisScriptMsg -T "${cmd}: Waiting for response."

                # pop-up a window to ease setting scriptreply                 
                osirisScriptReplyWrapper

		# Don't change any other OGS keywords (that ODEC pays
		# attention to) here while the modal dialog is up on
		# ODEC, otherwise bad things happen... MB 1/6/05

		set reply = `show -s osiris -terse scriptreply`
		while ("$reply" == "r")
		    echo -n "."
		    sleep 1
		    set reply = `show -s osiris -terse scriptreply`
		end

		# should there be a timeout here?

		switch ($reply)
		    case Y:
		    case y:
			echo ""
			osirisScriptMsg -T "${cmd}: ${reply} detected"\
			    "- resuming wfao."
		    breaksw

		    case N:
		    case n:
			echo ""
			osirisScriptMsg -T "${cmd}: ${reply} detected"\
			    "- wfao aborted."
			set exitcode = 3
			goto done
		    breaksw

		    default:
			echo ""
			osirisScriptMsg -T "${cmd}: invalid response"\
			    "<${reply}> - wfao aborted."
			set exitcode = 3
			goto done
		    breaksw
		endsw # switch ($reply)
	    endif # if ($?noask)
	endif # if ($count >= $timeOut)
    breaksw

    default:
	osirisScriptMsg -t $idnum -T -W "${cmd}: Unknown value for wfdm"\
	    "keyword <${wfdm}> - wfao aborted."
	set exitcode = 4
	goto done
    breaksw
endsw


# Wait an additional "fudge" time, if needed
set delay = `show -s osiris -terse aodelay`
set error = $status
if ($error != 0) then
    osirisScriptMsg -T "${cmd}: Error getting osiris keyword AODELAY"\
	"(show error #${error}) - skipping additional delay."
else
    sleep $delay
endif


# Restore the original value of the setstatus keyword
if ($?noask) then
    # Don't do anything, since we didn't change it in the no-ask mode
else
    $ogscmdpre modify -s osiris silent setstatus="${old_setstatus}"
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -T "${cmd}: Error restoring osiris setstatus keyword"\
	    "to original value."
    endif
endif


# We made it!
goto done


break:
echo "Control C abort detected ... Ending wfao."
set exitcode = -1
goto done


done:
# Block of code to execute regardless of what happened

# Exit with the proper exit code
if ($?exitcode) then
    exit $exitcode
else
    exit
endif
