#!/bin/csh -f
#+
#OSIRISGOI - OSIRIS library of scripts
#
#NAME
#     osirisGoi - takes OSIRIS data frames
#
#SYNOPSIS
#     osirisGoi mode [-t #] [-n #] [-nw] [-lgs] [-m]
#
#DESCRIPTION
#     takes OSIRIS frames using pre-existing exposure settings
#     ...ADD MORE LATER...
#
#OPTIONS
#     mode
#          specfies detector, "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 ";".
#
#     -n [#]
#          take n frames, defaults to 1.
#
#     -nw  
#          nowait - don't execute wfgo after starting exposure.  All status
#          checking before starting exposure will still occur.
#
#     -lgs
#          command lgs lbwfs - if this flag is set, osirisGoi will set the
#          aolb keyword aolbloop=2 before starting the exposure
#
#     -m
#          simulate the exposure - do not actually set go=1.  status checks of
#          motors and detector readiness will still occur.  during simulated
#          mode the go=1 command will be echoed to the screen.
#
#EXAMPLES
#     osirisGoi -m IMAG -n 3 -m
#          Takes 3 simulated IMAG exposures
#
#FILES
#     none
#
#SEE ALSO
#     ???
#-
#
# Modifcation History:
# 20041005 - MB: Copied from NIRC2 and adapted for OSIRIS
# 20041018 - MB: Added -t and -nw flags, expanded -s to be like take_dataset
# 20050911 - MB: Added support for LBWFS modes "Loop N" and "Infinite Loop"
# 20060413 - MB: Commented out lbwfs_time_check.txt stuff (was for testing)
# 20200522 - jlyke: Changed aolb service to ao
#

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

### need to figure out how make syncheck work with flags like "-s"...
#set noglob
#set CheckStatus = `syncheck -command $0 $* -pattern [SPEC,spec,IMAG,imag] {text int:1,9999999} {text} {text}` 
#unset noglob

#if ("$CheckStatus" != "OK") then
#    help $0
#    exit 1
#endif

# End of help/syncheck boiler plate.

# Set up to trap control-C
onintr ctrlc
### should also trap other interrupts (like kill, etc)

# Set default variable values
set nframes = 1
set idnum = 0
set fcmd = $0
set cmd = ${fcmd:t}
set cmdpre = ""
set cmdsuf = ""
set time_here = 0
set lbtimelimit = 300

# Decide if we should use SPEC or IMAG
set mode = $1
switch ($mode)
    case "SPEC":
    case "spec":
	set M = "s"
	set mode = "spec"
	breaksw
    case "IMAG":
    case "imag":
	set M = "i"
	set mode = "imag"
	breaksw
    default:
	osirisScriptMsg -T "${cmd} ${mode}: Specified mode must be SPEC or IMAG - aborting."
	exit 1
	breaksw
endsw
shift
##echo mode=${mode}
##echo M=${M}

# 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
		osirisScriptMsg -T "${cmd} ${mode}: Invalid script ID number"\
		    "specified <${2}> - using default."
	    endif
	    unset Checkstatus
	    breaksw

	case -n:
	    ###error checking for invalid number or non-numeric parameter
	    ###following the -n
	    ###should default to 1 in those cases (or if no # specified)
	    set nframes = $2
	    shift
	    breaksw

	case -nw:
	    osirisScriptMsg -T "${cmd} ${mode}: Entering nowait mode."
	    set nowait
	    breaksw

	case -lgs:
	    osirisScriptMsg -T "${cmd} ${mode}: In LGS mode, will start LBWFS."
	    set lgs
	    breaksw

	case -m:
	    set sim
	    set cmdpre = "echo ${cmd} ${mode}: sim:"
	    set cmdsuf = "-m"
	    breaksw

	default:
	    osirisScriptMsg -T "${cmd} ${mode}: Invalid command line flag $1 specified."
	    osirisScriptMsg -T "${cmd} ${mode}: Usage: $0 mode [-n #] [-nw] [-m]"
	    # set the error code for an error with command line input
	    exit 2
	    breaksw
    endsw
    shift
end
unset noglob

## echo nframes=${nframes}
## echo cmdpref=${cmdpref} 

### PROBLEM: setting nowait and nframes>1 will cause a problem
### goi will not wait before trying to start second exposure
### and will not return to parent script as desired.

# Wait until for mechanisms to be OK
$cmdpre wfmech $mode
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $cmdsuf "${cmd}: Error waiting for"\
	"mechanisms (wfmech error #${error}) - aborting."
    exit $error
endif

# Wait until the AO loops are closed (if wait4ao is on)
wfao -t $idnum
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $cmdsuf "${cmd}: Error waiting for ao (wfao error"\
	    "#${error}) - aborting."
    exit $error
endif

# Time estimate checking for LBWFS
#if ($mode == "spec") then
#    echo -n "wfao done at " >> ~/lbwfs_time_check.txt
#    date >> ~/lbwfs_time_check.txt
#endif

# Start the LBWFS exposures if in LGS mode
if ($?lgs) then
    # Check how long will be at this dither position
    set time_here = `show -s ao -terse scittdpos | cut -f1 -d"."`


    # Decide what lbwfs mode to use
    if ($time_here > $lbtimelimit) then
	# Use infinite loop mode
	set loopnum = 1
    else
	# Use loop N mode
	set loopnum = 2
    endif

    $cmdpre modify -s ao aolbloop=${loopnum}
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -t $idnum -T -W "${cmd}: Error starting LBWFS - aborting."
	exit $error
    else
	osirisScriptMsg -t $idnum -T "${cmd}: LBWFS exposures started."
    endif
endif

# Wait until the detector server is ready to take a frame
$cmdpre wfready $mode -t $idnum
set error = $status
if ($error != 0) then
    osirisScriptMsg -t $idnum -T -W $cmdsuf "${cmd}: Error waiting for $mode detector"\
	"ready (wfready error #${error}) - aborting."
    exit $error
endif

# Start taking frames
osirisScriptMsg -T "${cmd} ${mode}: Starting $mode frames."
set count = 0
while ( $count < $nframes)
    @ count++

    # Check for aborts before starting the exposure
    set abort = `show -s osiris -terse abort${mode}only`
    if ($abort == 0) then
	# Output some status info
	set curfile = "`show -terse -s osiris "$M"datafile`"
	osirisScriptMsg -T "${cmd} ${mode}: Taking frame ${curfile}"
	if (`math $nframes - $count` > 1) then
	    osirisScriptMsg -T "${cmd} ${mode}: This is frame $count of ${nframes}."
	endif
    
	# Start the exposure
	$cmdpre modify -s osiris silent ${M}go=1
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $cmdsuf "${cmd}: Error starting $mode exposure"\
		"(modify go=1 error #${error}) - aborting."
	    exit $error
	else
	    osirisScriptMsg -S $cmdsuf "Exposing."
	endif

	if ($?nowait) then
	    osirisScriptMsg -T "${cmd} ${mode}: Not waiting for ${mode} exposure to finish."
	else
	    # Wait for the exposure to finish
	    wfgo $mode -t $idnum
	    set error = $status
	    if ($error != 0) then
		osirisScriptMsg -t $idnum -T -W $cmdsuf "${cmd}: Error waiting for $mode exposure"\
		    "to finish (wfgo error #${error}) - aborting."
		exit $error
	    endif
	    osirisScriptMsg -T "${cmd} ${mode}: Frame completed."
	endif
    endif #endif for: if ($abort == 0)
    unset abort

    # Check if the last exposure was aborted
    set abort = `show -s osiris -terse abort${mode}only`
    if ($abort) then
	# Send message to observer
	osirisScriptMsg -T "${cmd} ${mode}: Caught abort for ${curfile}."

	# Get out of the exposure repeat while loop
	set count = $nframes
    endif
    unset abort
end

goto done

ctrlc:

# Block of code to handle interrupts.

###modify this stuff for OSIRIS
#set default = y
#echo -n "Do you want to abort current exposure ? [$default] "
#set answer = $<
#if ("$answer" == "") set answer = "$default"

#if ("$answer" == "y") then
    ###abort
#else
#    echo "Please wait for exposure to finish."
#    echo "(Note that the exposure estimate given below will be incorrect.)"
    ###wfg
#endif
exit 1

done:
# is there anything that needs to go here?
osirisScriptMsg -S $cmdsuf "Successfully completed."
exit
