#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisTakeDarks - takes a user-defined list of darks
#
#SYNOPSIS
#     osirisTakeDarks mode [-n #] [-m] itime1 [itime2 itime3 ...]
#
#-
#DESCRIPTION
#     takes a user-defined set of darks in IMAG or SPEC
#
#OPTIONS
#     mode    specfies detector, "SPEC" or "IMAG".
#
#     -n [#]  take n frames of each exposure time, defaults to 1.
#
#     -m
#          simulate modify's to servers.  status checks of
#          motors and detector readiness will still occur.  during simulated
#          mode the modify commands will be echoed to the screen.
#
#     itime1 itime2 itime3 ...
#          list of any number of integration times to use for darks
#
#EXAMPLES
#     osirisTakeDarks spec -n 5 2 4 6 8 10
#          Takes 5 dark frames for 2, 4, 6, 8, and 10 second integration times
#
#     To abort: issue CTRL-C from window in which script is running,
#               do not abort the current exposure, wait for completion.
#FILES
#     none
#
#SEE ALSO
#     ???
#-
#
# Modifcation History:
# 20050330 - MB: Initial version created (adapted from osirisGoi)
# 20160420 - jlyke: Added osirisupAutoRamp to set numreads
# 20200702 - jlyke: Changed osirisup to osiris
# 20220302 - jlyke: Allow user to continue if scriptrun=1
#

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

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

if ($#argv < 2) then
    set CheckStatus = -1
    echo "Error: too few arguments provided."
else
    set CheckStatus = "OK"
endif

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

# End of help/syncheck boiler plate.

# Set up to trap control-C
onintr abort

# Set default variable values
set fcmd = $0
set cmd = ${fcmd:t}
set idnum = 0
set nframes = 1
set cmdpre = ""
set cmdsuf = ""
set itimelist = ""
set chgd_getkw = 0
set error = 0

# Set the abort message instructing observers how to exit
set abortmsg = "###"
set abortmsg = "$abortmsg"

# 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:
	echo "${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 -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 -m:
	    set sim
	    set cmdpre = "echo ${cmd} ${mode}: sim:"
	    set cmdsuf = "-m"
	    breaksw

	default:
#	    set CheckStatus = `syncheck -command $0 $1 -pattern int`
            set CheckStatus = "OK"
	    if ("$CheckStatus" != "OK") then
		echo "${cmd} ${mode}: Invalid command line flag <${1}>, aborting."
		echo "${cmd} ${mode}: Usage: $0 mode [-n #] [-m] itime_list"
		# set the error code for an error with command line input
		exit 2
	    else
		set itimelist = (${itimelist} ${1})
	    endif	    
	    breaksw
    endsw
    shift
end
unset noglob

## echo nframes=${nframes}
## echo cmdpre=${cmdpre} 

# Check that no other scripts are running
set scriptrun = `show -s osiris -terse scriptrun`
if ($scriptrun) then
  set sexposing = `show -s osiris -terse sexposing`
  set iexposing = `show -s osiris -terse iexposing`
  modify -s osiris scriptreply="r"
  osirisScriptMsg -t $idnum -T -A "${cmd}: Another script appears to be running (scriptrun = 1). "  \
    "SPEC Exposing = $sexposing. " \
    "IMAG Exposing = $iexposing. " \
    "Do you want to continue?"
  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, 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
  switch ($reply)
    case Y:
    case y:  
      echo ""
      osirisScriptMsg -t $idnum -T "${cmd}: Reply: ${reply} -  resuming script."
      breaksw
    case N:
    case n:
      echo ""
      osirisScriptMsg -t $idnum -T "${cmd}: Reply: ${reply} -  exiting script."      
      exit 3
      breaksw
    default:
      echo ""
      osirisScriptMsg -t $idnum -T"${cmd}: Reply: ${reply} -  exiting script."
      exit 3
      breaksw
  endsw
endif    

# Notify OGS that this script is running
$cmdpre modify -s osiris silent scriptrun=1

# Clear out old messages from script message keywords
$cmdpre modify -s osiris silent scripterror=" "
$cmdpre modify -s osiris silent scriptwarn=" "
$cmdpre modify -s osiris silent scriptask=" "

# Set script status keyword
osirisScriptMsg -T -S $cmdsuf "Darks starting (${mode})."

# Set filter to Drk
osirisScriptMsg -T $cmdsuf "${cmd} mode: Setting $mode filter to Drk."
osirisSetupMech ${mode} -f Drk $cmdsuf
set error = $status
if ($error != 0) then
    osirisScriptMsg -S $cmdsuf "Error - darks not started."
    $cmdpre osirisScriptCleanUp
    osirisScriptMsg -T $cmdsuf "${cmd}: Error setting ${mode} filter (osirisSetupMech error #${error}) - aborting."
    set error = 2
    goto done
endif

# Get the current setnum and increment it if no setnum has been passed in
set cursetnum = `show -s osiris -terse setnum`
if ($cursetnum < 999) then
    set setnum = `math ${cursetnum} + 1`
else
    set setnum = 0
    osirisScriptMsg -t $idnum -T $cmdpre "${cmd}: The previous dataset number was 999, which is the maximum allowed value." \
	    "The current dataset will be assigned the number ${setnum}.  If there are already datasets with that number, the next" \
	    "available frame number will automatically be used when the FITS file is written.  Existing data WILL NOT be overwritten."
	### could get into a bad situation here if all available setnums and framenums are already used...
endif

$cmdpre modify -s osiris silent setnum="${setnum}"
$cmdpre modify -s osiris silent ${M}framenum=1

# Set dataset informational keywords
$cmdpre modify -s osiris silent dataset="Darks - ${mode}"
$cmdpre modify -s osiris silent ${M}object="Darks"

# Do not bother with ao or dcs keywords
# save current state to restore at end of script
set state_getkw = `show -s o${M}ds -terse getkw`
set state_getdcskw = `show -s o${M}ds -terse getdcskw`
set state_getaokw = `show -s o${M}ds -terse getaokw`
set chgd_getkw = 1
$cmdpre modify -s o${M}ds silent getkw=1
$cmdpre modify -s o${M}ds silent getdcskw=1
$cmdpre modify -s o${M}ds silent getaokw=1

# check and wait for mechanisms to be OK
$cmdpre wfmech $mode
set error = $status
if ($error != 0) then
    osirisScriptMsg -T $cmdsuf "${cmd}: Error waiting for mechanisms (wfmech error #${error}) - aborting."
    set error = 3
    goto done
endif

# Start taking frames
set count = 0
set fcount = 0
set total = `math ${#itimelist} x ${nframes}`
while (${#itimelist} != 0)
    @ count++
    set ncount = 0
    while (${ncount} < ${nframes})
	@ ncount++
	@ fcount++
	osirisScriptMsg -T -S $cmdsuf "Taking dark ${fcount} of ${total} - ${itimelist[1]} sec"

	
	$cmdpre wfready $mode
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T $cmdsuf "${cmd}: Error waiting for $mode detector ready (wfready error #${error}) - aborting."
	    set error = 3
	    goto done
	endif

    
echo "-------------------------------------------------------"
echo "To stop ${cmd}:"
echo "-------------------------------------------------------"
echo "1. Issue CTRL-C from window in which script is running"
echo "2. Answer n to question: Do you want to abort current exposure ?"
echo "3. Wait for current exposure to finish"       
echo ""
       

#	$cmdpre modify -s osiris silent ${M}itime=${itimelist[1]}
        sleep 1
        $cmdpre osirisAutoRamp $mode ${itimelist[1]}
        sleep 1
	$cmdpre modify -s osiris silent ${M}go=1
	set curfile = `show -terse -s osiris ${M}datafile`
	osirisScriptMsg -T $cmdsuf "${cmd} ${mode}: Taking frame ${curfile}"

	sleep 1
    
	$cmdpre wfgo $mode -t $idnum
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T $cmdsuf "${cmd}: Error waiting for $mode exposure to finish (wfgo error #${error}) - aborting."
	    set error = 3
	    goto done
	endif

	# wait a few seconds for frame to finish being written to disk
	# need it currently to prevent ods server crash if try to start
	# new exp while previous is still being written to disk

        # 2012 Mar 16 jlyke new ods does not seem to have this issue
        # reduce sleep from 6 seconds to 1 second.
	sleep 1
    end
    shift itimelist
end

goto done

abort:
# Block of code to handle interrupts.

set default = n
echo -n "Do you want to abort current exposure ? [$default] "
set answer = $<
if ("$answer" == "") then
    set answer = "$default"
endif

if ("$answer" == "y") then
    $cmdpre modify -s osiris ${M}abort=1
else
    echo "Please wait for exposure to finish."
endif

$cmdpre wfgo $mode

set error = 1


done:
if ("${chgd_getkw}" == "1") then
    $cmdpre modify -s o${M}ds silent getkw=${state_getkw}
    $cmdpre modify -s o${M}ds silent getdcskw=${state_getdcskw}
    $cmdpre modify -s o${M}ds silent getaokw=${state_getaokw}
endif

if (${error} != 0) then
    osirisScriptMsg -S $cmdsuf "Darks aborted."
else
    osirisScriptMsg -S $cmdsuf "Darks finished."
endif

$cmdpre osirisScriptCleanUp

exit $error
