#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisTakeDataset - coordinates dataset execution for OSIRIS 
#
#SYNOPSIS
#     osirisTakeDataset [-t #] [-d dataset_name] [-n #] [-o object_name] \
#          [-O observers] [-P #] [-S spec_params] [-I imag_params] \
#          [-D dither_params] [-A AO_mode] [-e est_dither_time] \
#          [-m simulated_modes] [-OP object_pattern] [-SP sky_pattern]
#
#DESCRIPTION
#     This script sets up, coordinates, and executes OSIRIS SPEC and IMAG 
#     exposures as part of an OSIRIS dataset.  It is primarily called by the
#     OSIRIS Dataset Execution Client (ODEC), but may be called directly from
#     the command line as well.  Interactions with the script while running
#     (ex. status and aborts) are accomplished with keywords in the OSIRIS
#     Global Server (service name "OSIRIS").
#
#OPTIONS
#     -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 ";".
#
#     -d 'Dataset Name'
#          Dataset name to be recorded in FITS files.
#
#     -n NUM
#          Dataset number for use with filenames and FITS headers.  If a
#          dataset number is not passed, the script will get the current
#          one from OGS and increment it.
#
#     -T 'Dataset Type'
#          Observation type, used for DRS
#          Can be one of [(target OR astro), (calstar OR star), calib] 
#
#     -o 'Object Name'
#          Object name to be recorded in FITS files.  SPEC and IMAG files
#          will both have this value.
#
#     -O 'Observer'
#          Observer name(s) to be recorded in FITS files.
#
#     -P pa
#          If set, causes osirisTakeDataset to check if the currently set 
#          telescope PA equals specified value.  If they do not agree, 
#          the script will prompt the user before starting the dataset.
#
#     -S sfilter sscale sitime scoadds
#          SPEC parameters to use for each dither position
#
#     -I 'mode' iframes [ifilter1 irepeats1 iitime1 icoadds1 etc...]
#          sets IMAG mode for current dataset. "iframes" is the total number
#          of IMAG frame setups to use (can be 0) per dither position. It is 
#          followed by the appropriate number of sets of IMAG exposure settings.
#          The possible modes are:
#          ->  "Disabled (Spec only)" 0
#
#          ->  "Independent (Imager only)" 1 ifilter irepeats iitime icoadds
#
#          ->  "Slave 1: Maximum Repeats" 1 ifilter irepeats iitime icoadds
#
#          ->  "Slave 2: Maximum Itime" 1 ifilter irepeats iitime icoadds
#
#          ->  "Slave 3: Increasing Itime" iframes ifilter1 irepeats1 iitime1 \
#                  icoadds1 ifilter2 irepeats2 iitime2 icoadds2 etc...
#
#          ->  "Slave 4: Filter Sets" iframes ifilter1 irepeats1 iitime1 \
#                  icoadds1 ifilter2 irepeats2 iitime2 icoadds2 etc...
#
#          ->  "Slave 5: Sync Readouts" 1 ifilter irepeats iitime icoadds
#
#     -D sframes coords issky1 xoff1 yoff1 issky2 xoff2 yoff2 etc...
#          dither pattern to use, consisting of sframes steps, 
#          in either "sky" or "instr" coords, and using 
#          the listed issky (0 or 1), xoff("), and yoff(") 
#          for each step of the dither pattern
#
#     -A 'AO_mode'
#          selects the intended AO mode for the observations.  
#          mostly important for
#          LGS observations.  can be one of:
#          -> "NGS"         = AO system in NGS mode
#          -> "LGS_NOLASER" = AO system in LGS mode, but laser 
#          			not being propagated
#          -> "LGS_FIXED"   = AO system in LGS mode, laser not dithered 
#          			on tel moves
#          -> "LGS_DITHER"  = AO system in LGS mode, laser dithered 
#          			on tel moves
#
#
#     -e seconds
#          estimated time for LBWFS exposures at a particular dither position.
#          for osiris, it is defined to be the time from when the first 
#          exposure starts at a dither position, to the time when both 
#          detectors have finished their exposure for a dither position.  
#          the time estimate is normally calculated
#          by the ODEC using the most up-to-date values for OSIRIS overheads.
#
#     -m [ao tel det mot ogs]
#          simulate calls to particular RPC servers from osirisTakeDataset.  
#          during simulated calls, the command is echoed 
#          (instead of being executed)
#
#     -OP object_pattern
#          Pattern for object frames.  Set by ODEC.  
#          Current values are "None", "Stare", "Box4", "Box5",
#          "Box9", "Statistical Dither", "Raster Scan", and "User Defined"
#
#     -SP sky_pattern
#         Pattern for sky frames.  Set by ODEC.  Same choices as object_pattern.
#
#EXAMPLES
#    osirisTakeDataset -t 12345 -d 'Test Dataset' -n 100 -o 'My Favorite Star' \
#          -O 'Larry, Curly, and Moe' -P 45.0 -S Kbb 0.05 10 1 \
#          -I 'Slave 4: Filter Sets" 2 Kn1 1 2 1 Kn5 1 2 1 \
#          -D 4 sky 0 0 0 1 -1 0 0 0 -1 1 -1 -1 -m ao tel
#
#    Takes a dataset with a 4-position dither, Kbb SPEC data, two IMG frames per
#    dither position (Kn1 & Kn5), and simulated calls to AO and TEL servers.
#
#ENVIRONMENT VARIABLES
#     none
#
#FILES
#     none
#
#SERVERS & KEYWORDS
#     service = osiris
#          keywords:
#
#SCRIPTS CALLED
#     help, syncheck
#
#ERROR CODES
#     2 - invalid argument enountered while parsing command line input
#     3 - aborted script due to scriptrun conflict
#
#SEE ALSO
#     to be added
#-
#
# Modification History:
# 20041005 - MB: Script started
# 20041214 - MB: Header updated, server names into variables,
# 20050105 - MB: Added handling for -T flag (Dataset Type)
# 20050910 - MB: Added setting of PA's, and dither position keywords
# 20060413 - MB: Commented out lbwfs_time_check.txt stuff (was for testing)
# 20080304 - JLW: Updated filter list with new pupil filters
#
# 20160308 - JLW: change spec to float, osirisupAutoRamp called for 
# 		SPEC upgrade; call osirisupGoi
# 20180626 - jlyke: change all osirisup cmds to osiris cmds
# 20181109 - jlyke: remove syncheck for imager filters
# 20201118 - jlyke: Add -OP and -SP arguments for obj_pattern and sky_pattern
#
# 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

# set noglob
# set CheckStatus = `syncheck -command $0 $* -pattern {text...}` 
# unset noglob

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

# End of help/syncheck boiler plate.

# Notify that the script is starting
osirisScriptMsg -T "${0}: Script starting at `date`"

# Set this to one for testing mode...
#set test
#set simall

# Set up to trap interrupts
onintr abort

# Set default values
set dataset_name = "Unnamed Dataset"
set object = "Unnamed Object"
#set observer = "Nobody"
set idnum = 0
set fcmd = $0
set cmd = ${fcmd:t}
set setnum = 1000 # this is an illegal setnum for the detector servers, but we change it below before setting it
set obstype = "astro"
set pa = 0
set aocmdpre = ""
set aocmdsuf = ""
set aosimsuf = ""
set telcmdpre = ""
set telcmdsuf = ""
set telsimsuf = ""
set detcmdpre = ""
set detcmdsuf = ""
set motcmdpre = ""
set motcmdsuf = ""
set ogscmdpre = ""
set ogscmdsuf = ""
set ifilter = ""
set irepeats = ""
set iitime = ""
set icoadds = ""
set est_dither_time = 0
set aomode = ""
set control_lbwfs = ""

# FOR LAB TESTING ONLY
if ($?simall) then
    set aosim
    set aocmdpre = "echo ${cmd}: ao_sim:"
    set aosimsuf = "-m"
    set telsim
    set telcmdpre = "echo ${cmd}: tel_sim:"
    set telsimsuf = "-m"
    #set detsim
    #set detcmdpre = "echo ${cmd}: det_sim:"
    #set detcmdsuf = "-m"
    #set motsim
    #set motcmdpre = "echo ${cmd}: mot_sim:"
    #set motcmdsuf = "-m"
    #set ogssim
    #set ogscmdpre = "echo ${cmd}: ogs_sim:"
    #set ogscmdsuf = "-m"
endif

# Parse command line flags and arguments
osirisScriptMsg -T "${cmd}: Parsing command line arguments."
set noglob
while ($#argv != 0)
    #echo Checking ${1} ...
    switch ($1)
	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

	case -d:
#	    set CheckStatus = `syncheck -command $1 $2 -pattern text...`
	    set CheckStatus = "OK"
	    if ("$CheckStatus" == "OK") then
		### Should check that the first character of the text is not a "-" indicating a new flag.
		set dataset_name = "$2"
		shift
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid dataset name specified <${2}> - using <${dataset_name}>."

		# 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

	case -n:
	    set CheckStatus = `syncheck -command $1 $2 -pattern int:0,999`
	    if ("$CheckStatus" == "OK") then
		set setnum = $2
		shift
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid dataset number specified <${2}> - current setnum will be incremented."

		# 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

	case -T:
	    set obstypelist = "[target,astro,calstar,star,calib]"
	    set CheckStatus = `syncheck -command $1 $2 -pattern $obstypelist`
	    if ("$CheckStatus" == "OK") then
		switch ($2)
		    case "target":
		    case "astro":
			set obstype = "astro"
			shift
			breaksw
		    case "calstar":
		    case "star":
			set obstype = "star"
			shift
			breaksw
		    case "calib":
			set obstype = "calib"
			shift
			breaksw
		    default:
			# Should never get to this case if syncheck is working correctly
			osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid dataset type specified <${2}> - using <${obstype}>."
			# 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
			breaksw
		endsw
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid dataset type specified <${2}> - using <${obstype}>."

		# 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
	case -o:
#	    set CheckStatus = `syncheck -command $1 $2 -pattern text...`
	    set CheckStatus = "OK"
	    if ("$CheckStatus" == "OK") then
		### Should check that the first character of the text is not a "-" indicating a new flag.
		set object = "$2"
		shift
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid object name specified <${2}> - using <${object}>."

		# 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
	case -O:
#	    set CheckStatus = `syncheck -command $1 $2 -pattern text...`
	    set CheckStatus = "OK"
	    if ("$CheckStatus" == "OK") then
		### Should check that the first character of the text is not a "-" indicating a new flag.
		set observer = "$2"
		shift
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid observer name specified <${2}> - using <${observer}>."

		# 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
	case -P:
	    set CheckStatus = `syncheck -command $1 $2 -pattern float`
	    if ("$CheckStatus" == "OK") then
		set pa = $2
		shift
	    else
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Invalid PA specified <${2}> - using {${pa}>."

		# 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
	case -S:
	    set sfiltlist = "[Jbb,Hbb,Kbb,Zbb,Kcb,Jn1,Jn2,Jn3,Jn4,Hn1,Hn2,Hn3,\
			      Hn4,Hn5,Kn1,Kn2,Kn3,Kn4,Kn5,Zn4,Kc3,Kc4,Kc5,Drk]"
			      
	    # JLW up: sitime is float seconds
	    set CheckStatus = \
		`syncheck -command $1 ${argv[2-5]} -pattern $sfiltlist float float int`
	    if ("$CheckStatus" == "OK") then
		set sfilter = $2
		shift
		set sscale = $2
		shift
		set sitime = $2
		shift
		set scoadds = $2
		shift
	    else
		osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid SPEC parameters specified <${argv[2-5]}> - aborting dataset."
		osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		exit 2
	    endif
	    unset Checkstatus
	    breaksw
	case -I:
# need to get this error checking right... see script_notes.txt
	    set CheckStatus = `syncheck -command $1 ${argv[2-3]} -pattern text... int`
	    if ("$CheckStatus" == OK) then
		set imagmode = "$2"
		shift
		set iframes = $2
		shift
	    else
		osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid IMAG mode or iframes specified <${2}> - aborting dataset."
		osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		exit 2
	    endif
	    unset CheckStatus

	    set ifiltlist = "[Opn,Jbb,Hbb,Kbb,Zbb,Jn1,Jn2,Jn3,Hn1,Hn2,Hn3,Hn4,Hn5,\
			      Kn1,Kn2,Kn3,Kn4,Kn5,Zn3,Drk]"
	    set count = 0
	    
	    while ($count < $iframes)
		#echo nargv = $#argv
		@ count++
		if ($#argv >= 4) then
		    set CheckStatus = "OK"   
#		    set CheckStatus = \
#			`syncheck -command imag_params ${argv[2-5]} -pattern $ifiltlist int float int`
		else
		    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Incorrect # of parameters for IMAG frame #${count} - aborting dataset."
		    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		    exit 2
		endif 
		if ("$CheckStatus" == "OK") then
		    if ($?ifilter && $?irepeats && $?iitime && $?icoadds) then
			set ifilter = ($ifilter $2)
			shift
			set irepeats = ($irepeats $2)
			shift
			set iitime = ($iitime $2)
			shift
			set icoadds = ($icoadds $2)
			shift
		    else
			set ifilter = $2
			shift
			set irepeats = $2
			shift
			set iitime = $2
			shift
			set icoadds = $2
			shift
		    endif
		else
		    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid IMAG frame #${count} parameters specified <${argv[2-5]}> - aborting dataset."
		    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		    exit 2
		endif
		unset Checkstatus
	    end
	    breaksw
   	case -OP:
	    set objpttrn = "$2"
            shift
            breaksw
        case -SP:
            set skypttrn = "$2"
            shift
            breaksw
	case -D:
	    set CheckStatus = `syncheck -command $1 ${argv[2-3]} -pattern int [sky,instr]`
	    if ("$CheckStatus" == OK) then
		set sframes = $2
		shift
		set coords = "${2}"
		shift
	    else
		osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid # of dither positions or coordinates specified <${argv[2-3]}> - aborting dataset."
		osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		exit 2
	    endif
	    unset CheckStatus

	    set count = 0

	    while ($count < $sframes)
		@ count++
		if ($#argv >= 3) then
		    set CheckStatus = \
			`syncheck -command dither_pos ${argv[2-4]} -pattern [0,1] float float`
		else
		    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Incorrect # of parameters for dither position #${count} - aborting dataset."
		    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		    exit 2
		endif    
		if ("$CheckStatus" == "OK") then
		    if ($?issky && $?xoff && $?yoff) then
			set issky = ($issky $2)
			shift
			set xoff = ($xoff $2)
			shift
			set yoff = ($yoff $2)
			shift
		    else
			set issky = $2
			shift
			set xoff = $2
			shift
			set yoff = $2
			shift
		    endif
		else
		    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid dither position #${count} parameters specified <${argv[2-4]}> - aborting dataset."
		    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		    exit 2
		endif
		unset Checkstatus
	    end
	    breaksw

	case -A:
	    set modelist = "[NGS,LGS_NOLASER,LGS_FIXED,LGS_DITHER]"
	    set CheckStatus = `syncheck -command $1 $2 -pattern $modelist`
	    if ("$CheckStatus" == "OK") then
		set aomode = $2
		shift
	    else
		osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid AO mode specified <${2}> - aborting dataset."
		osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		exit 2
	    endif
	    unset Checkstatus
	    breaksw

	case -e:
	    set CheckStatus = `syncheck -command $1 $2 -pattern int:0,9999`
	    if ("$CheckStatus" == "OK") then
		set est_dither_time = $2
		shift
		### should check that est_dither_time is non-zero here
	    else
		if ($aomode != "NGS") then
		    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid time estimate per"\
			"dither position <${2}> - aborting dataset."
		    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		    exit 2
		else
		    # 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
	    endif
	    unset Checkstatus
	    breaksw

	case -m:
#	    set CheckStatus = `syncheck -command $1 ${2} -pattern text`
	    set CheckStatus = "OK"
	    if ("$CheckStatus" != "OK") then
		osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid simulate argument specified <${2}> - aborting dataset."
		osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
		exit 2
	    endif
	    unset CheckStatus
	    
	    ## echo $2
	    set valid
	    while ($?valid && ($#argv > 1) )
		#echo Checking simulate argument ${2}...
		switch ($2)
		    case ao:
			set aosim
			set aocmdpre = "echo ${cmd}: ao_sim:"
			set aocmdsuf = "; sleep 10"
			set aosimsuf = "-m"
			breaksw
		    case tel:
			set telsim
			set telcmdpre = "echo ${cmd}: tel_sim:"
			set telcmdsuf = "; sleep 10"
			set telsimsuf = "-m"
			breaksw
		    case det:
			set detsim
			set detcmdpre = "echo ${cmd}: det_sim:"
			set detcmdsuf = "-m"
			breaksw
		    case mot:
			set motsim
			set motcmdpre = "echo ${cmd}: mot_sim:"
			set motcmdsuf = "-m"
			breaksw
		    case ogs:
			set ogssim
			set ogscmdpre = "echo ${cmd}: ogs_sim:"
			set ogscmdsuf = "-m"
			breaksw
		    case -*:
			unset valid
			breaksw
		    default:
			osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Invalid simulate argument specified <${2}> - aborting dataset."
			osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
			exit 2
			breaksw
		endsw
		shift
	    end
	    breaksw
	default:
	    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Unknown flag specified <$1> - aborting dataset."
	    osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	    exit 2
	    breaksw
    endsw
    shift
end
unset noglob

###need to figure out how to check that all needed flags and parameters were set
###for ex.  if -S ... not set, then script won't run well...

#For testing, let's make sure we got all the right variables and values
if ($?test) then
    echo ""
    echo "Current Script Variables:"
    echo dataset_name =    $dataset_name
    echo object =          $object
    if ($?observer) then
      echo observer =        $observer
    endif
    echo idnum =           $idnum
    echo setnum =          $setnum
    echo obstype =         $obstype
    echo pa =              $pa
    echo sfilter =         $sfilter
    echo sscale =          $sscale
    echo sitime =          $sitime
    echo scoadds =         $scoadds
    echo imagmode =        $imagmode
    echo iframes =         $iframes
    echo ifilter =         $ifilter
    echo irepeats =        $irepeats
    echo iitime =          $iitime
    echo icoadds =         $icoadds
    echo sframes =         $sframes
    echo coords =          $coords
    echo issky =           $issky
    echo xoff =            $xoff
    echo yoff =            $yoff
    echo aomode =          $aomode
    echo est_dither_time = $est_dither_time
    echo aocmdpre =        $aocmdpre
    echo aocmdsuf =        $aocmdsuf
    echo telcmdpre =       $telcmdpre
    echo telcmdsuf =       $telcmdsuf
    echo detcmdpre =       $detcmdpre
    echo detcmdsuf =       $detcmdsuf
    echo motcmdpre =       $motcmdpre
    echo motcmdsuf =       $motcmdsuf
    echo ""
    exit
endif

# Check that no other scripts are running
set scriptrun = `show -s osiris -terse scriptrun`
if ($scriptrun) then
    $ogscmdpre modify -s osiris scriptreply="r"
    osirisScriptMsg -t $idnum -T -A "${cmd}: Another script appears to be" \
	"running (scriptrun = 1).  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 "${cmd}: ${reply} detected - resuming script."
	    breaksw
	case N:
	case n:
	    echo ""
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf \
		"${cmd}: Script aborted - dataset not started."
	    exit 3
  	    breaksw
	default:
	    echo ""
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Script" \
		"aborted due to invalid response <${reply}> -" \
		"dataset not started."
	    exit 3
  	    breaksw
	endsw
    # $ogscmdpre modify -s osiris scriptwait=0 #don't think this is needed here... MB 4/28/05
    unset askmsg
endif

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

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

# Set script status keyword
osirisScriptMsg -t $idnum -T -S $ogscmdsuf "Script starting."

# Make sure script abort and pause keywords are set to their defaults
$ogscmdpre modify -s osiris abortafterspec=0
$ogscmdpre modify -s osiris abortspeconly=0
$ogscmdpre modify -s osiris abortimagonly=0
$ogscmdpre modify -s osiris scriptwait=0

# Get the current setnum and increment it if no setnum has been passed in
### Want to replace this with a separate script that gets the next
### available setnum in the outdir, instead of just incrementing
if ($setnum == 1000) then
    ### should figure out how to use $ogscmdpre here if want to sim OGS call
    set cursetnum = `show -s osiris -terse setnum`
    if ($cursetnum < 999) then
	set setnum = `math ${cursetnum} + 1`
    else
	set setnum = 0
	osirisScriptMsg -t $idnum -T -W $ogscmdpre "${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
endif

# Check if we're in IMAG only mode (no SPEC)
if ("$imagmode" == "Independent (Imager only)") then
    set imagonly
    echo "imagonly"
    # Set the AO focus offset for the imager
    osirisScriptMsg -T "${cmd}: Setting AO focus offsets"
    osirisRefocusAO -x imag ${aosimsuf}
    set error = $status
    if ($error != 0) then
      osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
      osirisScriptCleanUp
      osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	"AO focus offsets (osirisRefocusAO error #${error}) -"\
	"aborting dataset."
	### when setting a scripterror, it must be the last keyword set before
	### the script exits, to avoid ODEC problems
	exit $error
    endif
endif

# Check if we're in SPEC only mode (no IMAG)
if ("$imagmode" == "Disabled (Spec only)") then
    set speconly
    echo "speconly"
    set iframes = 0
endif

# Set dataset informational keywords
osirisScriptMsg -T "${cmd}: Setting dataset info keywords"
$ogscmdpre modify -s osiris dataset="${dataset_name}"
$ogscmdpre modify -s osiris object="${object}"
if ($?observer) then
  $ogscmdpre modify -s osiris observer="${observer}"
endif
$ogscmdpre modify -s osiris imagmode="${imagmode}"
$ogscmdpre modify -s osiris sframes=${sframes}
$ogscmdpre modify -s osiris setnum="${setnum}"
$ogscmdpre modify -s osiris sframe=0
$ogscmdpre modify -s osiris iframe=0
$ogscmdpre modify -s osiris sobstype=${obstype}
$ogscmdpre modify -s osiris iobstype=${obstype}
if ($?objpttrn) then
  $ogscmdpre modify -s osiris objpttrn="${objpttrn}"
endif
if ($?skypttrn) then
  $ogscmdpre modify -s osiris skypttrn="${skypttrn}"
endif

# Setup SPEC
if ($?imagonly != 1) then
osirisScriptMsg -S $ogscmdsuf "Configuring SPEC."

    # Setup SPEC Mechanisms
    osirisScriptMsg -T "${cmd}: Moving SPEC mechanisms"
    osirisSetupMech spec -t $idnum -f $sfilter -x $sscale $motcmdsuf
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	osirisScriptCleanUp
	osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "SPEC mechanism keywords (osirisSetupMech error #${error}) -"\
	    "aborting dataset."
	### when setting a scripterror, it must be the last keyword set before
	### the script exits, to avoid ODEC problems
	exit $error
    endif

    # Set the AO focus offsets based upon sscale
    # skip if sfilter=drk
    if ($sfilter !~ [Dd]* ) then
      osirisScriptMsg -T "${cmd}: Setting AO focus offsets"
      osirisRefocusAO -x $sscale ${aosimsuf}
      set error = $status
      if ($error != 0) then
	osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	osirisScriptCleanUp
	osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "AO focus offsets (osirisRefocusAO error #${error}) -"\
	    "aborting dataset."
	### when setting a scripterror, it must be the last keyword set before
	### the script exits, to avoid ODEC problems
	exit $error
      endif
    endif

    # Set the targwave in DCS
    osirisSetTargwave $sfilter $telsimsuf
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	osirisScriptCleanUp
	osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "targwave in DCS (osirisSetTargwave error #${error}) -"\
	    "aborting dataset."
	exit $error
    endif

    # Setup SPEC Exposure & Info Settings
    osirisScriptMsg -T "${cmd}: Setting SPEC detector keywords"
    # JLW up: itime (and sampmode and reads) set in osirisAutoRamp
    osirisAutoRamp spec ${sitime}
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	osirisScriptCleanUp
	osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "spectrometer exposure parameters with autocalc ramp settings: #${error}) -"\
	    "aborting dataset."
	exit $error
    endif
    
    #$detcmdpre modify -s osiris sitime=${sitime}
    $detcmdpre modify -s osiris scoadds=${scoadds}
    $detcmdpre modify -s osiris sobject="${object}"
    $detcmdpre modify -s osiris sframenum=1
endif

# Setup IMAG
if ($?speconly != 1) then
    # Setup IMAG Info keywords
    osirisScriptMsg -T "${cmd}: Setting IMAG info keywords"
    $detcmdpre modify -s osiris iobject="${object}"
    $detcmdpre modify -s osiris iframenum=1

    # Set the targwave in DCS
    osirisSetTargwave $ifilter[1] $telcmdsuf
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -S $ogscmdsuf "Error - dataset not started."
	osirisScriptCleanUp
	osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "targwave in DCS (osirisSetTargwave error #${error}) -"\
	    "aborting dataset."
	exit $error
    endif
endif


# Should verify that the PA on the sky is the same as what was recorded in the DDF...


# Mark the initial telescope position
$telcmdpre mark

# Set up the AO system
### could move all this AO setup stuff to a separate script
osirisScriptMsg -t $idnum -T "${cmd}: Setting up the AO dither settings."
if ($?aosim) then
    set realaomode = 0
else
    set realaomode = `show -s ao -terse aoopsmode`
endif

switch ($realaomode)
    case 0:
	osirisScriptMsg -t $idnum -T "${cmd}: Observations will be performed in NGSAO mode."
	$aocmdpre modify -s ao aolpmove = 0
	$aocmdpre modify -s ao aotsmove = 0
	$aocmdpre modify -s ao aofmmove = 1
	breaksw
    case 1:
	osirisScriptMsg -t $idnum -T "${cmd}: Observations will be performed in dual-NGSAO mode"
	$aocmdpre modify -s ao aolpmove = 0
	$aocmdpre modify -s ao aotsmove = 1
	$aocmdpre modify -s ao aofmmove = 1
	$aocmdpre modify -s ao scittdpos=${est_dither_time}
	set control_lbwfs = "-lgs"
	breaksw
    case 2:
	osirisScriptMsg -t $idnum -T "${cmd}: Observations will be performed in LGSAO mode"
	$aocmdpre modify -s ao aotsmove = 1
	$aocmdpre modify -s ao scittdpos=${est_dither_time}
	set control_lbwfs = "-lgs"
	switch ($aomode)
	    case "LGS_NOLASER":
		osirisScriptMsg -t $idnum -T "${cmd}: No changes to laser dither settings"
		breaksw
	    case "NGS":
	    case "LGS_FIXED":
		osirisScriptMsg -t $idnum -T "${cmd}: During dither, laser is fixed"
		$aocmdpre modify -s ao aofmmove = 0
		$aocmdpre modify -s ao aolpmove = 0
		breaksw
	    case "LGS_DITHER":
		osirisScriptMsg -t $idnum -T "${cmd}: During dither, laser moves with object" 
		$aocmdpre modify -s ao aofmmove = 1
		$aocmdpre modify -s ao aolpmove = 1
		breaksw
	    default:
		#should never get here since aomode values are checked during argument parsing
		osirisScriptMsg -t $idnum -T -W "${cmd}: Unknown LGS dither mode - aborting"\
		    "dataset."
		set aborted
		goto done
		breaksw
	    endsw
	breaksw
    default:
	#pretty unlikely that we ever get here either
	osirisScriptMsg -t $idnum -T $idnum -T -W "${cmd}: Unknown AO Ops Mode - aborting dataset."
	set aborted
	goto done
	breaksw
    endsw

# Loop thru dither positions
set scount = 0
set oldxoff = 0
set oldyoff = 0

while ($scount < $sframes)
    @ scount++

    # Setup IMAG Mechanisms for the first configuration of this dither position
    if ($?speconly != 1) then
	osirisScriptMsg -T "${cmd}: Moving IMAG Mechanisms"
	osirisSetupMech imag -t $idnum -f $ifilter[1] $motcmdsuf
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error setting"\
		"IMAG mechanism keywords (osirisSetupMech error #${error})."\
		"Current dataset (${dataset_name}) will continue with IMAG"\
		"disabled."
	    # Disable IMAG
	    set speconly
	endif

        # Setup IMAG Exposure Settings
	osirisScriptMsg -T "${cmd}: Setting IMAG exposure settings"
	# JLW up: itime passed in as float seconds.  should be integer ms in server.
        # jlyke: use osirisAutoRamp for itime and reads 
	#set tmpItime=`math ${iitime[1]} x 1000`
	#set tmpItime=`round ${tmpItime}`
	#$detcmdpre modify -s osiris iitime=${tmpItime}
        $detcmdpre osirisAutoRamp imag ${iitime[1]} 	
        $detcmdpre modify -s osiris icoadds=${icoadds[1]}
    endif

    # Set the ogs keyword to indicate the current dither position
    $ogscmdpre modify -s osiris sframe=${scount}
    osirisScriptMsg -T "${cmd}: Moving to dither position #${scount} of"\
	"${sframes}"
    osirisScriptMsg -S $ogscmdsuf "Moving to dither position ${scount}."

    # Get the issky flag for this position to determine AO focus
    if ( ${issky[1]} == 1 ) then
      if ($?speconly != 1) then 
        # set AO focus for imager
        osirisScriptMsg -T "${cmd}: Setting AO focus offset for imager."
        osirisRefocusAO -x imag ${aosimsuf}
        set error = $status
        if ($error != 0) then
	  osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "AO focus offsets (osirisRefocusAO error #${error}) -"\
	    "continuing without focus adjustment."
        endif
      endif
    else
      if ($?imagonly != 1) then 
        # set AO focus for $sscale
        osirisScriptMsg -T "${cmd}: Setting AO focus offset for $sscale scale."
        osirisRefocusAO -x $sscale ${aosimsuf}
        set error = $status
        if ($error != 0) then
	  osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Error setting"\
	    "AO focus offsets (osirisRefocusAO error #${error}) -"\
	    "continuing without focus adjustment."
        endif
      endif
    endif
 
    # Time estimate checking for LBWFS
    #echo "Dither Pos "${scount} >> ~/lbwfs_time_check.txt

    # Calculate the relative offset from the previous dither position
    set curxoff = `math ${xoff[1]} - ${oldxoff}`
    set curyoff = `math ${yoff[1]} - ${oldyoff}`

    # Move the telescope
    if ("$coords" == "sky") then
	$telcmdpre en ${curxoff} ${curyoff}
	### check and handle exit status...
    else
	$telcmdpre xy ${curxoff} ${curyoff}
	### check and handle exit status...
    endif

    # Remember the current offsets for the next dither position
    set oldxoff = ${xoff[1]}
    set oldyoff = ${yoff[1]}

    # Set the dither offset keywords in OGS and in FITS headers
    $ogscmdpre modify -s osiris dcoords=${coords} dtotoff1=${xoff[1]} \
	dtotoff2=${yoff[1]} dlstoff1=${curxoff} dlstoff2=${curyoff}
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -t $idnum -T -W "${cmd}: There was a problem setting"\
	    "the dither offset keywords (dtotoff and dlstoff) in the FITS"\
	    "headers.  They may be incorrect for position ${scount} of"\
	    "dataset #${setnum}."
    endif

    # Set the issky flag for this position (for DRS)
    $ogscmdpre modify -s osiris issky=${issky[1]}

    # Set the position angle keywords in OGS and in FITS headers
    osirisHeaderPA $ogscmdsuf
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -t $idnum -T -W "${cmd}: There was a problem setting"\
	    "the PA_SPEC and PA_IMAG keywords in the FITS headers.  They may"
	    "be incorrect for position ${scount} of dataset #${setnum}."
    endif

    # Time estimate checking for LBWFS
    #if ($scount == 1) then
	#echo " " >> ~/lbwfs_time_check.txt
	#echo "Dataset "${setnum}", time estimate = "${est_dither_time} >> ~/lbwfs_time_check.txt
    #endif

    # Start the SPEC exposure if no abort is present
    set specabort = `show -s osiris -terse abortspeconly`
    if ($specabort == 0) then
	if ($?speconly != ($?speconly && $?imagonly)) then
	    # start and wait for the spec if speconly=1 and imagonly=0
	    osirisScriptMsg -T "${cmd}: IMAG mode is Disabled (SPEC only)."
	    osirisScriptMsg -S $ogscmdsuf "Exposing." ### should be set by Goi
	    # start the exposure and wait - control lbwfs if appropriate
	    osirisGoi spec -t $idnum $control_lbwfs $detcmdsuf
	    set error = $status
	    if ($error != 0) then
		osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
		    "starting spec exposure (osirisGoi error #${error})." \
		    "Current dataset (${dataset_name}) will continue with"\
		    "SPEC disabled."
		### should actually abort out of dataset here
		# Disable SPEC
		set imagonly
	    endif
	else
	    if ($?imagonly != 1) then
		osirisScriptMsg -S $ogscmdsuf "Starting SPEC exposure."
		# start the exposure and don't wait - control lbwfs if appropriate
		osirisGoi spec -t $idnum -nw $control_lbwfs $detcmdsuf
		set error = $status
		if ($error != 0) then
		    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
			"starting spec exposure (osirisGoi error #${error})."\
			"Current dataset (${dataset_name}) will continue with"\
			"SPEC disabled."
		    # Disable SPEC
		    set imagonly
		endif
	    endif # endif for: if ($?imagonly != 1) then

	    set icount = 0
	    $ogscmdpre modify -s osiris iframes=${iframes}

	    # Loop thru IMAG frames
	    while ($icount < $iframes)
		@ icount++

		$ogscmdpre modify -s osiris iframe=${icount}
		osirisScriptMsg -T "${cmd}: Starting IMAG frame #${icount}."

		# If iframes > 1, then setup IMAG for those frames
		# The first IMAG setup is done above, to minimize overheads
		if ($icount > 1) then
		    osirisScriptMsg -S $ogscmdsuf "Configuring IMAG."
		    osirisScriptMsg -T "${cmd}: Moving IMAG Mechanisms"
		    osirisSetupMech imag -t $idnum -f $ifilter[${icount}] $motcmdsuf
		    if ($status != 0) then
			set error = $status
			osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error setting IMAG mechanism keywords (osirisSetupMech error #${error})." \
			    "Current dataset (${dataset_name}) will continue with IMAG disabled."
			# Disable IMAG
			set speconly
		    endif

		    # Setup IMAG Exposure Settings
		    osirisScriptMsg -T "${cmd}: Setting IMAG exposure settings"
	            $detcmdpre osirisAutoRamp imag ${iitime[${icount}]} 
                    $detcmdpre modify -s osiris icoadds=${icoadds[${icount}]}
		endif

		# Start IMAG frame if no abort is present
		set abort = `show -s osiris -terse abortimagonly`
		if ($abort == 0) then
		    # Set exposing status message
#		    if ($?imagonly) then
#			osirisScriptMsg -S $ogscmdsuf "IMAG exposing."
#		    else
#			osirisScriptMsg -S $ogscmdsuf "SPEC and IMAG exposing."
#		    endif
		    ### osirisGoi should set IMAG exposing status message

		    # Start and wait for IMAG exposure
		    if ($?imagonly) then
			# we want to start the LBWFS if in imagonly mode
			osirisGoi imag -t $idnum -n ${irepeats[${icount}]} $control_lbwfs $detcmdsuf
			set error = $status
		    else
			# if not imagonly, then LBWFS was already started with the SPEC exposure
			osirisGoi imag -t $idnum -n ${irepeats[${icount}]} $detcmdsuf
			set error = $status
		    endif
		    if ($error != 0) then
			osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
			    "starting imag exposure (osirisGoi error #${error})."\
			    "Current dataset (${dataset_name}) will continue with"\
			    "IMAG disabled."
			# Disable IMAG
			set speconly
		    endif
		endif
		unset abort


		# Check if the last IMAG frame was aborted
		set abort = `show -s osiris -terse abortimagonly`
		if ($abort) then
		    # Send message to observer
		    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: <Abort"\
			"Imager Only> received, IMAG disabled for rest of dataset."
			
		    # Get out of imager loop & disable for rest of dataset
		    set icount = $iframes
		    set speconly
		    
		    # Remember that a user-triggered abort happened
		    set aborted

		    # Reset the abort keyword
		    $ogscmdpre modify -s osiris abortimagonly=0
		endif
		unset abort

		### need to check for exit status

	    end # end
	endif #endif for: if ($?speconly != ($?speconly && $?imagonly))
    endif #endif for: if ($specabort == 0)
    unset specabort

    # Set iframe to 0 until the next dither position so ODEC updates properly
    $ogscmdpre modify -s osiris iframe=0

    # Make sure SPEC frame is done before next dither position
    if ($?imagonly != 1) then
        wfgo spec -t $idnum
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Error"\
		"waiting for spec exposure to finish (wfgo error #${error})."\
		"Dataset will be aborted."
		set aborted
		goto done
	endif
    endif #endif for: if ($?imagonly != 1)

    # Time estimate checking for LBWFS
    #echo -n "all exp done at " >> ~/lbwfs_time_check.txt
    #date >> ~/lbwfs_time_check.txt

    # Shift variables for next dither position
    shift issky
    shift xoff
    shift yoff

    # Check if the last SPEC frame was aborted
    set abort = `show -s osiris -terse abortspeconly`
    if ($abort) then
	# Send message to observer
	osirisScriptMsg -t $idnum -T $ogscmdsuf "${cmd}: <Abort Spec Only> received, Spec"\
	    "disabled for rest of dataset."

        # Disable SPEC for rest of dataset
	set imagonly

	# Remember that a user-triggered abort happened
	set aborted

	# Reset the abort keyword
	$ogscmdpre modify -s osiris abortspeconly=0
    endif
    unset abort

    # Check if both SPEC and IMAG are now aborted
	# This can happen with an Abort All or if the dataset starts with one disabled
	# and then the other is aborted during the dataset
    if ($?speconly && $?imagonly) then
	# Send message to observer
	osirisScriptMsg -t $idnum -T $ogscmdsuf "${cmd}: Both IMAG and SPEC are disabled,"\
	    "ending dataset."
	osirisScriptMsg -S $ogscmdsuf "Aborted by user..."

	# Get out of the dither while loop
	set scount = $sframes

	# Remember that a user-triggered abort happened
	set aborted
    endif

    # Check for "Abort After Current Spec"
    set abort = `show -s osiris -terse abortafterspec`
    if ($abort) then
	# Send message to observer
	osirisScriptMsg -t $idnum -T $ogscmdsuf "${cmd}: <Abort After Current Spec> received,"\
	    "ending dataset."
	osirisScriptMsg -S $ogscmdsuf "Aborted by user..."

	# Get out of the dither while loop
	set scount = $sframes

	# Remember that a user-triggered abort happened
	set aborted

	# Reset the abort keyword
	$ogscmdpre modify -s osiris abortafterspec=0
    endif
    unset abort

    # Check for "Pause After Current Spec"
    set pause = `show -s osiris -terse scriptwait`
    if ($pause) then
	# Send message to observer
	osirisScriptMsg -t $idnum -T $ogscmdsuf "${cmd}: <Pause After Current Spec> received,"\
	    "waiting for <Resume>."
	osirisScriptMsg -S $ogscmdsuf "Paused by user..."
    
	# Wait for resume signal
	set wait = `show -s osiris -terse scriptwait`
	while ($wait)
	    echo -n "."
	    sleep 1
	    set wait = `show -s osiris -terse scriptwait`
	end

	### should there be a timeout here?

	# Alert the observer
	osirisScriptMsg -t $idnum -T $ogscmdsuf "${cmd}: <Resume> received, continuing dataset."
	osirisScriptMsg -S $ogscmdsuf "Script resuming..."
    endif
    unset pause

# End of dither pattern
end

goto done

###############################################################################

abort:
echo Returning to initial telescope position.
gomark
playsound -d
sleep 4
exit 1

###############################################################################

done:
# Put the dark filter in SPEC to minimize persistence effects
# Do this for all datasets
# osirisSetupMech spec -f Drk $motcmdsuf
# osirisScriptMsg -t $idnum -T "${cmd}: Selecting SPEC Dark filter."
# 
# commented out above dark move, so filter wheel is not overused
# RDC, 22 May 2006
#

# Put in the IMAG dark if there were IMAG frames in this dataset
#if ($iframes != 0) then
#    osirisSetupMech imag -f Drk $motcmdsuf
#    osirisScriptMsg -t $idnum -T "${cmd}: Selecting IMAG Dark filter."
#endif
#
# commented out above dark move, so filter wheel is not overused
# jlyke, 04 Nov 2010 


# Return telescope to initial position
osirisScriptMsg -t $idnum -T "${cmd}: Returning to initial telescope position."
osirisScriptMsg -S $ogscmdsuf "Returning telescope to initial position."
$telcmdpre gomark


# Cleanup and reset scripting keywords in OGS
osirisScriptCleanUp $ogscmdsuf


# Alert the user that the script has completed
if ($?aborted) then
    osirisScriptMsg -S $ogscmdsuf "Aborted..."
    osirisScriptMsg -t $idnum -T -E $ogscmdsuf "${cmd}: Dataset #${setnum} (${dataset_name}) was aborted."
    ### when setting a scripterror, it must be the last keyword set before the script exits, to avoid ODEC problems
else
    osirisScriptMsg -t $idnum -T -W $ogscmdsuf "${cmd}: Dataset #${setnum} (${dataset_name}) completed successfully."
    osirisScriptMsg -S $ogscmdsuf "Successfully completed."
    # Set the scriptsuccess keyword so ODEC will clear the current dataset from the queue
    $ogscmdpre modify -s osiris scriptsuccess=${idnum}
endif

# Record finish time to STDOUT
osirisScriptMsg -T "${cmd}: Script done at `date`"

# Ring the bell to alert the user that dataset is done
#xterm -bg orange -geom 150x60+150+125 -e ring_bell
xterm -bg orange -geom 40x10+500+400 -T "Dataset Done" -e ring_bell

exit
