MaxMacros	60
Macro	0
MacroName START_REYES

ClearPersistentVars

Echo
Echo ================================================
Echo ===== INTEGRATED MULTI-GRID PIPELINE =====
Echo ================================================
Echo
Echo This pipeline supports:
Echo - Single-grid and Multi-grid acquisition
Echo - Automated modes: FSD, Screen, Montage
Echo - Manual modes: FSD, Screen (single-grid only)
Echo

Call Setup_Helper

resume_pending := 1
resume_from := 1
If $workflow_type == 1 AND $pipeline_mode != 3
   If $pipeline_mode == 1
      resume_max = 7
   Else
      resume_max = 5
   EndIf

   Echo
   Echo ================================================
   Echo NEW RUN OR RESUME?
   Echo ================================================
   Echo   1 = NEW run, start from the montage (default - just press Enter)
   Echo   0 = RESUME an interrupted run in this SAME base directory
   EnterDefaultedNumber 1 -1 Is this a NEW run? (1 = yes, 0 = no, resume):
   new_run = $reportedValue1
   If $new_run != 0 AND $new_run != 1
      Exit Answer 1 for a new run or 0 to resume
   EndIf

   If $new_run == 0
      Echo
      Echo Restart from which stage?  Pipeline: $pipeline_name
      Echo   1  montage             (an existing montage file is kept, not retaken)
      Echo   2  grid squares        (waits for REyes to write grid_squares\eucentricity.nav)
      Echo   3  eucentricity        (needs grid_squares\eucentricity.nav on disk)
      Echo   4  eucentric plane     (waits for grid_squares\eucentricity_correction.png)
      Echo   5  step-scan           (grid squares already mapped are skipped)
      If $pipeline_mode == 1
         Echo   6  wait for targets    (waits for targets\targets.nav)
         Echo   7  rotation movies     (crystals already collected are skipped)
      EndIf
      Echo
      Echo If you are unsure between two stages, choose the EARLIER one: a stage
      Echo that is already complete costs only the time to walk its done flags.
      Echo Use the SAME base directory and sample name as the interrupted run.
      If $single_grid_mode == 0
         Echo
         Echo MULTI-GRID: the resume applies to the FIRST grid of the slot range
         Echo only (slot $MinSlotNum unless it is SKIPped). Later grids start from
         Echo their montage. The grid must be back IN ITS SLOT, not on the stage.
      EndIf
      EnterOneNumber Restart from which stage number (1 to $resume_max)?
      If $reportedValue1 < 1 OR $reportedValue1 > $resume_max
         Exit Stage must be between 1 and $resume_max for this pipeline
      EndIf
      resume_pending := $reportedValue1
   EndIf
   Echo RUN_START | new_run=$new_run | resume_from=$resume_pending | pipeline=$pipeline_name
EndIf

If $single_grid_mode == 0 AND $workflow_type == 2
   Echo
   Echo ================================================
   Echo ERROR: UNSUPPORTED COMBINATION
   Echo ================================================
   Echo
   Echo Multi-grid manual mode is not yet supported.
   Echo Please use single-grid mode for manual workflows for now.
   Echo
   Echo ================================================
   Exit Multi-grid manual mode not yet supported
Endif

If $single_grid_mode == 0
   Call Slot_Verification_Helper
Endif

Call Directory_Setup_Helper

If $workflow_type == 1
   If $pipeline_mode == 1 OR $pipeline_mode == 2
      Call REyes_Setup_Automated
   ElseIf $pipeline_mode == 3
      Call REyes_Setup_Optional
   Endif
ElseIf $workflow_type == 2
   Echo
   Echo ================================================
   Echo Note: REyes setup will be required after manual grid square selection
   Echo ================================================
Endif

Echo
Echo ================================================
Echo ===== STARTING ACQUISITION =====
Echo ================================================

If $single_grid_mode == 0
   SlotNum = $MinSlotNum
Else
   SlotNum = 0
Endif
successful_grids = 0
failed_grids = 0
skipped_grids = 0

NewArray grid_results 1 $ItrNum
NewArray failure_reasons 1 $ItrNum

Loop $ItrNum slotIndex

   current_sample = $sample_names[$slotIndex]
   current_base_name = $base_names[$slotIndex]

   If $single_grid_mode == 1
      Echo
      Echo ========================================
      Echo ===== PROCESSING SINGLE GRID ==========
      Echo ========================================
   Else
      Echo
      Echo ========================================
      Echo ========== PROCESSING SLOT $SlotNum ==========
      Echo ========================================

      CompareNoCase current_sample SKIP
      If $reportedValue1 == 0
         Echo Skipping slot $SlotNum as requested
         grid_results[$slotIndex] := SKIPPED
         skipped_grids = $skipped_grids + 1
         SlotNum = $SlotNum + 1
         Continue
      Endif
   Endif

   resume_from := $resume_pending
   resume_pending := 1

   Echo Sample: $current_sample
   If $single_grid_mode == 0
      Echo Slot: $SlotNum
   Endif
   ReportDateTime

   If $single_grid_mode == 0
      If $slot_status[$slotIndex] != 1
         Echo WARNING: Skipping slot $SlotNum - Status: $slot_status[$slotIndex]
         grid_results[$slotIndex] := FAILED

         If $slot_status[$slotIndex] == 0
            failure_reasons[$slotIndex] := User_requested_skip
         ElseIf $slot_status[$slotIndex] == -1
            failure_reasons[$slotIndex] := No_grid_in_slot
         ElseIf $slot_status[$slotIndex] == -2
            failure_reasons[$slotIndex] := Directory_creation_error
         Else
            failure_reasons[$slotIndex] := Unknown_setup_error
         Endif

         failed_grids = $failed_grids + 1
         SlotNum = $SlotNum + 1
         Continue
      Endif
   Endif

   samplename := $current_base_name

   sample_dir_path = $base_directory\$current_sample
   Echo Preparing grid: $current_sample
   If $single_grid_mode == 0
      Echo Slot: $SlotNum
   Endif

   log_sep @= _
   grid_log_name @= $current_base_name$log_sep$pipeline_name$log_sep$yyyymmdd
   Echo Opening new log file for: $current_base_name
   SaveLogOpenNew $grid_log_name
   Echo New log opened: $grid_log_name.log

   Try
      SetDirectory $sample_dir_path
      set_directory := $sample_dir_path
      Echo Working directory set to: $sample_dir_path
   Catch
      Echo ERROR: Could not access directory: $sample_dir_path
      If $single_grid_mode == 1
         Exit Cannot proceed without sample directory
      Else
         Echo Skipping slot $SlotNum ($current_sample)
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Directory_access_error
         failed_grids = $failed_grids + 1
         SlotNum = $SlotNum + 1
         Continue
      Endif
   EndTry

   Echo ================================================
   Echo Log file: $grid_log_name.log
   Echo Grid directory: $sample_dir_path
   Echo Sample: $current_sample
   If $single_grid_mode == 0
      Echo Slot: $SlotNum
   Endif
   ReportDateTime
   Echo ================================================

   If $single_grid_mode == 0
      Echo Loading cartridge from slot $SlotNum...
      Try
         SetColumnOrGunValve 0
         LoadCartridge $SlotNum
         Echo Successfully loaded cartridge from slot $SlotNum
         Delay 3 sec
         stage_settled = 0
         Loop 120
            ReportStageBusy
            If $reportedValue1 == 0
               stage_settled = 1
               Break
            EndIf
            Delay 1 sec
         EndLoop
         If $stage_settled == 0
            Echo WARNING: the stage still reports busy 2 min after the exchange
         EndIf
      Catch
         Echo ERROR: Failed to load cartridge from slot $SlotNum
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Cartridge_load_error
         failed_grids = $failed_grids + 1
         SlotNum = $SlotNum + 1
         Continue
      EndTry
   Else
      Echo Using grid already loaded on stage
   Endif

   partial_completion := 0

   If $workflow_type == 1
      Try
         Call Automated_Pipeline_Helper

         If $partial_completion == 1
            Echo Outcome recorded by the pipeline helper
         Else
            grid_results[$slotIndex] := SUCCESS
            failure_reasons[$slotIndex] := None
            successful_grids = $successful_grids + 1
            Echo SUCCESS: $current_sample completed without errors
         Endif

      Catch
         Echo
         Echo !!!!! ERROR DURING PIPELINE EXECUTION !!!!!
         If $single_grid_mode == 0
            Echo Grid: $current_sample (Slot $SlotNum)
         Else
            Echo Grid: $current_sample
         Endif
         Echo The pipeline encountered an error and stopped
         Echo Check individual log files for details
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Pipeline_execution_error
         failed_grids = $failed_grids + 1
      EndTry

   ElseIf $workflow_type == 2

      Try
         Call Manual_Pipeline_Part1
      Catch
         Echo
         Echo !!!!! ERROR DURING MONTAGE ACQUISITION !!!!!
         Echo Grid: $current_sample
         Echo Check log files for details
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Montage_acquisition_error
         failed_grids = $failed_grids + 1
         Continue
      EndTry

      Echo
      Echo ================================================
      Echo ===== MANUAL INTERVENTION REQUIRED =====
      Echo ================================================
      Echo
      Echo CRITICAL: You must now MANUALLY select grid squares
      Echo
      Echo The montage has been acquired and is in the Navigator.
      Echo
      Echo Instructions:
      Echo 1. Open the Navigator window (if not already open)
      Echo 2. Review the montage that was just acquired
      Echo 3. Manually ADD POINT ITEMS for desired grid squares
      Echo 4. Make sure points are added to the navigator
      Echo 5. You can add as many or as few points as you want
      Echo 6. A dialog will appear asking if grid squares have been added
      Echo 7. Click NO to add them manually (script stays paused)
      Echo 8. When completely done, click YES to continue the pipeline
      Echo
      Echo ================================================

      Pause Have the grid squares been already added? (Press NO to add them manually)

      Echo
      Echo User confirmed manual grid square selection is complete

      Try
         Call Manual_Pipeline_Part2

         If $partial_completion == 1
            Echo Outcome recorded by the pipeline helper
         Else
            grid_results[$slotIndex] := SUCCESS
            failure_reasons[$slotIndex] := None
            successful_grids = $successful_grids + 1
            Echo SUCCESS: $current_sample completed without errors
         Endif

      Catch
         Echo
         Echo !!!!! ERROR DURING PIPELINE EXECUTION !!!!!
         Echo Grid: $current_sample
         Echo The pipeline encountered an error and stopped
         Echo Check individual log files for details
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Pipeline_execution_error
         failed_grids = $failed_grids + 1
      EndTry

   Endif

   If $workflow_type == 1 AND $single_grid_mode == 0
      Try
         CloseNavigator
         Echo Navigator closed for this grid
      Catch
         Echo Note: Navigator was already closed or could not be closed
      EndTry
   Else
      If $single_grid_mode == 1
         Echo Single-grid mode: Navigator remains open
      Else
         Echo Manual mode: Navigator remains open
      Endif
   Endif

   Echo Grid processing complete: $current_base_name
   Echo ================================================

   If $single_grid_mode == 0
      SlotNum = $SlotNum + 1

      If $SlotNum <= $MaxSlotNum
         Echo
         Echo Preparing for next grid...
         Echo Brief pause to ensure system is ready...
         Delay 5 sec
      Endif
   Endif

EndLoop

Echo All grids processed - opening summary log
log_sep @= _
summary_tag @= _summary
If $single_grid_mode == 1
   grid_prefix @= SingleGrid
Else
   grid_prefix @= MultiGrid
Endif
summary_log_name @= $grid_prefix$log_sep$pipeline_name$log_sep$yyyymmdd$summary_tag
SaveLogOpenNew $summary_log_name

SetDirectory $base_directory
Echo ================================================
Echo SUMMARY LOG
Echo Directory: $base_directory
Echo ================================================

Echo
Echo ============= CLEANUP =============

If $single_grid_mode == 0
   Echo Unloading final grid back to autoloader...
   Try
      SetColumnOrGunValve 0
      UnloadCartridge
      Echo Successfully unloaded final grid
   Catch
      Echo WARNING: Could not unload final grid - may need manual unload
   EndTry
Else
   Echo Single grid mode - grid remains on stage
   Echo Please unload manually when ready
Endif

Echo
Echo
Echo ================================================
Echo ============= PROCESSING COMPLETE ==============
Echo ================================================
If $single_grid_mode == 1
   Echo Acquisition mode: Single Grid
Else
   Echo Acquisition mode: Multi-Grid
Endif
If $workflow_type == 1
   Echo Workflow: Automated
Else
   Echo Workflow: Manual
Endif
Echo Pipeline mode: $pipeline_name
If $single_grid_mode == 1
   Echo Total grids: 1
Else
   Echo Total grids in range: $ItrNum
Endif
Echo Successful: $successful_grids
Echo Failed: $failed_grids
If $single_grid_mode == 0
   Echo Skipped: $skipped_grids
Endif
Echo
Echo Detailed Results:
Echo ------------------------------------------------
Echo (PARTIAL = screening completed but no targets found)
Echo

If $single_grid_mode == 1
   Echo Grid ($sample_names[1]): $grid_results[1] - $failure_reasons[1]
Else
   SlotNum = $MinSlotNum
   Loop $ItrNum slotIndex
      Echo Slot $SlotNum ($sample_names[$slotIndex]): $grid_results[$slotIndex] - $failure_reasons[$slotIndex]
      SlotNum = $SlotNum + 1
   EndLoop
Endif

Echo ================================================
Echo
Echo Next Steps:
If $pipeline_mode == 1
   Echo - Check movie data in movies\ subdirectory for each sample
   Echo - Review diffraction patterns in StepScan folders
   Echo - Analyze data with REyes processing pipeline
ElseIf $pipeline_mode == 2
   Echo - Review diffraction patterns in StepScan folders
   Echo - Select targets manually if needed for movie collection
ElseIf $pipeline_mode == 3
   Echo - Review montage images in each sample directory
   Echo - Assess grid quality and ice thickness
Endif
Echo - Check individual log files in each sample directory
Echo - Check log file: $summary_log_name.log

SetColumnOrGunValve 0
Echo
Echo Column valve closed for safety
Echo All processing complete!

SaveLog
EndMacro
Macro	1
ScriptName BatchED_Main

ClearPersistentVars

Echo
Echo ================================================
Echo ===== BATCHED - UNIFIED SETUP =====
Echo ================================================
Echo

Echo Choose acquisition mode:
Echo 1 = Diffraction (Record mode - parallel beam)
Echo 2 = Imaging (Search mode - imaging beam)
Echo
EnterOneNumber Enter acquisition mode (1 = Diffraction, 2 = Imaging):
If $reportedValue1 != 1 AND $reportedValue1 != 2
   Exit Acquisition mode must be 1 (Diffraction) or 2 (Imaging)
Endif
acq_mode := $reportedValue1

If $acq_mode == 1
   Echo Mode: DIFFRACTION (Record)

   Echo
   Echo Choose diffraction type:
   Echo 1 = Continuous rotation (tilt during exposure)
   Echo 2 = Still snapshot (no tilt during exposure)
   Echo 3 = Multi-angle snapshots (5 angles: +60, +30, 0, -30, -60)
   Echo
   EnterOneNumber Enter diffraction type (1 = Rotation, 2 = Still, 3 = Multi-angle):
   If $reportedValue1 != 1 AND $reportedValue1 != 2 AND $reportedValue1 != 3
      Exit Diffraction type must be 1 (Rotation), 2 (Still), or 3 (Multi-angle)
   Endif
   diff_type := $reportedValue1

   If $diff_type == 1
      Echo Type: CONTINUOUS ROTATION
   ElseIf $diff_type == 2
      Echo Type: STILL SNAPSHOT
   ElseIf $diff_type == 3
      Echo Type: MULTI-ANGLE SNAPSHOTS (+60, +30, 0, -30, -60)
   Endif

ElseIf $acq_mode == 2
   Echo Mode: IMAGING (Search)
   diff_type := 0
Endif

ReportDirectory
set_directory := $reportedValue1
Echo Working directory: $set_directory

Echo
EnterString compound_name Enter your compound/sample name:
compoundname := $compound_name
Echo Compound name: $compoundname

Echo
Echo Navigator Setup:
Echo - You should have already added your target points
Echo - The script needs to know where your targets start
Echo
EnterOneNumber Enter the LAST navigator item number BEFORE your targets were added:
If $reportedValue1 < 0
   Exit Navigator offset must be positive
Endif
xtalct := $reportedValue1
Echo Starting from navigator item: $xtalct

EnterOneNumber Enter the NUMBER of targets you want to collect:
If $reportedValue1 < 1
   Exit Must collect at least 1 target
Endif
nitems := $reportedValue1
Echo Number of targets: $nitems

Echo
Echo Frame Acquisition Rate:
Echo - Time per frame in seconds
Echo - Typical values: 0.5 to 2.0 seconds
Echo
EnterOneNumber Enter frame time in seconds:
If $reportedValue1 < 0.1 or $reportedValue1 > 10
   Exit Frame time must be between 0.1 and 10 seconds
Endif
acqrate := $reportedValue1
Echo Frame time: $acqrate seconds per frame

Echo
Echo Camera Binning:
Echo - Recommended values: 2, 4, or 8
Echo - Higher binning = faster readout, lower resolution
Echo - Maximum binning: 16
Echo
EnterOneNumber Enter binning factor (1, 2, 4, 8, or 16):
If $reportedValue1 != 1 AND $reportedValue1 != 2 AND $reportedValue1 != 4 AND $reportedValue1 != 8 AND $reportedValue1 != 16
   Exit Binning must be 1, 2, 4, 8, or 16
Endif
binning := $reportedValue1
Echo Binning: $binning

If $acq_mode == 1 AND $diff_type == 1

   Echo
   Echo Tilt Range:
   Echo - Typical values: 30-60 degrees
   Echo - Range: 5 to 70 degrees
   Echo
   EnterOneNumber Enter maximum positive tilt angle:
   If $reportedValue1 < 5 or $reportedValue1 > 70
      Exit Tilt angle must be between 5 and 70 degrees
   Endif
   startangle := $reportedValue1
   finalangle := -1 * $startangle
   tiltrange := 2 * $startangle
   range := P$startangletoN$finalangle
   Echo Tilt range: +$startangle to $finalangle degrees

   Echo
   Echo Rotation Rate:
   Echo - Typical values: 0.3 to 2.0 dps (degrees per second)
   Echo - Slower = better signal but longer exposure
   Echo
   EnterOneNumber Enter rotation rate in degrees per second:
   If $reportedValue1 < 0.1 or $reportedValue1 > 5
      Exit Rotation rate must be between 0.1 and 5 dps
   Endif
   rotrate := $reportedValue1
   Echo Rotation rate: $rotrate dps

   rotincr := $rotrate / 30
   Echo Rotation increment: $rotincr

   recordtime := $tiltrange / $rotrate
   Echo Exposure time: $recordtime seconds

Endif

If $acq_mode == 1
   Echo
   Echo Multiple Sweeps:
   Echo - Collect multiple acquisitions on the same crystal
   Echo - Typically 1 (single collection per target)
   Echo
   EnterOneNumber Enter number of sweeps per target:
   If $reportedValue1 < 1 or $reportedValue1 > 10
      Exit Number of sweeps must be between 1 and 10
   Endif
   nsweeps := $reportedValue1
   Echo Sweeps per target: $nsweeps
Endif

If $acq_mode == 1
   ReportSpotSize
   spsz := $reportedValue1
   Echo Spot size: $spsz

   ReportCameraLength
   dist := $reportedValue1 * 1000
   Echo Talos camera length: $dist mm

   If $dist == 420
      apollodist := 560
   ElseIf $dist == 960
      apollodist := 1280
   Else
      Echo Warning: Unusual camera length detected
      apollodist := $dist
   Endif
   Echo Apollo camera length: $apollodist mm

   temp := c
Endif

Echo
Echo ================================================
Echo ===== ACQUISITION SUMMARY =====
Echo ================================================
Echo Compound: $compoundname

If $acq_mode == 1
   If $diff_type == 1
      Echo Mode: DIFFRACTION - CONTINUOUS ROTATION
      Echo Tilt range: +$startangle to $finalangle degrees ($tiltrange total)
      Echo Rotation rate: $rotrate dps
      Echo Exposure time: $recordtime seconds
   ElseIf $diff_type == 2
      Echo Mode: DIFFRACTION - STILL SNAPSHOT
   ElseIf $diff_type == 3
      Echo Mode: DIFFRACTION - MULTI-ANGLE SNAPSHOTS
      Echo Angles: +60, +30, 0, -30, -60 degrees (5 per target)
   Endif
   Echo Frame time: $acqrate s/frame
   Echo Binning: $binning
   Echo Sweeps per target: $nsweeps
   Echo Camera length: $apollodist mm (Apollo)
   Echo Spot size: $spsz
ElseIf $acq_mode == 2
   Echo Mode: IMAGING (Search)
   Echo Frame time: $acqrate s/frame
   Echo Binning: $binning
Endif

Echo Starting navigator item: $xtalct
Echo Number of targets: $nitems
Echo ================================================
Echo

YesNoBox Ready to start BatchED acquisition?
If $reportedValue1 == 0
   Exit User cancelled acquisition
Endif

SaveLogOpenNew $compoundname_BatchED
Echo
Echo Starting BatchED acquisition...
Echo
ReportDateTime

If $acq_mode == 1 AND $diff_type == 1
   MakeDirectory $set_directory\movies
   Echo Created subdirectory: movies
   Echo Dispatching to: BatchED_Rotation
   Call BatchED_Rotation
ElseIf $acq_mode == 1 AND $diff_type == 2
   MakeDirectory $set_directory\snapshots
   Echo Created subdirectory: snapshots
   Echo Dispatching to: BatchED_Still
   Call BatchED_Still
ElseIf $acq_mode == 1 AND $diff_type == 3
   MakeDirectory $set_directory\snapshots
   Echo Created subdirectory: snapshots
   Echo Dispatching to: BatchED_MultiAngle
   Call BatchED_MultiAngle
ElseIf $acq_mode == 2
   MakeDirectory $set_directory\imaging
   Echo Created subdirectory: imaging
   Echo Dispatching to: BatchED_Imaging
   Call BatchED_Imaging
Endif

Echo
Echo ================================================
Echo BATCHED ACQUISITION COMPLETE
Echo ================================================
Echo
Echo Processed $nitems targets
Echo
ReportDateTime
ReportClock

TiltTo 0
ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

Echo
Echo Scope returned to safe state
Echo - Tilt: 0 degrees
Echo - Screen: Down
Echo - Beam: Blanked
Echo - Column valve: Closed
Echo
Echo BatchED complete!

SaveLog
EndMacro
Macro	2
MacroName REYES_Setup_Standalone

ClearPersistentVars
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

Echo
Echo ================================================
Echo ===== REYES PARAMETER SETUP =====
Echo ================================================
Echo
Echo This script establishes parameters for REyes helpers
Echo Use this when reopening SerialEM to continue work
Echo

ReportDateTime
yyyymmdd := $reportedValue1
Echo Date: $yyyymmdd

UserSetDirectory [Choose the sample directory where files are saved]
set_directory := $reportedValue1
SetDirectory $set_directory
Echo Chosen directory: $set_directory

EnterString sample_name What is your sample name?
samplename := $sample_name
Echo Sample name: $samplename

Echo
Echo ================================================
Echo ===== MONTAGE PARAMETERS =====
Echo ================================================
Echo

Echo Enter montage dimension (used by REyes_MNT)
If $reyes_detector == 1
   Echo - Creates an NxN grid montage at 115x magnification
ElseIf $reyes_detector == 2
   Echo - Creates an NxN grid montage at 210x LM magnification (CETA)
Endif
Echo - Typical values: 3x3, 4x4, or 5x5
Echo - Range: 2 to 9
Echo
EnterOneNumber Enter desired montage dimension:
If $reportedValue1 < 2 or $reportedValue1 > 9
   Exit Montage size must be between 2 and 9
Endif
mnt_size := $reportedValue1
Echo Montage size: $mnt_size x $mnt_size

Echo
Echo ================================================
Echo ===== DIFFRACTION MAP PARAMETERS =====
Echo ================================================
Echo

Echo Enter diffraction map dimension (used by REyes_STPSCN)
Echo - Recommended: Odd numbers (3, 5, 7, 9, etc.)
Echo - Typical values: 5x5 or 7x7
Echo - Range: 3 to 21
Echo
EnterOneNumber Enter desired map dimension (odd values recommended):
If $reportedValue1 < 3 or $reportedValue1 > 21
   Exit Map size must be between 3 and 21
Endif
map_size := $reportedValue1
Echo Diffraction map size: $map_size x $map_size

Echo
Echo ================================================
Echo ===== TILT RANGE PARAMETERS =====
Echo ================================================
Echo

Echo Enter tilt range for continuous rotation movies (used by REyes_DFMV)
Echo - This sets the maximum tilt angle (+/-) for diffraction data
Echo - REyes_DFMV will rotate from +angle to -angle
Echo - Typical values: 50-60 degrees
Echo - Range: 5 to 70 degrees
Echo
EnterOneNumber Enter max positive tilt angle:
If $reportedValue1 < 5 or $reportedValue1 > 70
   Exit Tilt angle must be between 5 and 70 degrees
Endif
selected_tilt := $reportedValue1

Echo Tilt range: +$selected_tilt to -$selected_tilt degrees

Echo
Echo ================================================
Echo ===== SETUP COMPLETE =====
Echo ================================================
Echo
Echo Parameters established:
Echo - Sample name: $samplename
Echo - Working directory: $set_directory
Echo - Montage size: $mnt_size x $mnt_size
Echo - Diffraction map size: $map_size x $map_size
Echo - Tilt range: +$selected_tilt to -$selected_tilt degrees
Echo
Echo You can now run:
Echo - REyes_MNT (for grid montage)
Echo - REyes_STPSCN (for diffraction mapping)
Echo - REyes_DFMV (for target movie collection)
Echo - Or any other REyes helper macro
Echo
Echo ================================================

YesNoBox Do you want to open a new log file for this session?
If $reportedValue1 == 1
   SaveLogOpenNew $samplename_resumed_$yyyymmdd
   Echo Log file opened: $samplename_resumed_$yyyymmdd.log
   Echo Working directory: $set_directory
   Echo Sample: $samplename
   ReportDateTime
Else
   Echo No log file opened - you can start logging manually if needed
Endif

Echo
Echo Setup complete! Ready to run REyes macros.

SaveLog
EndMacro
Macro	3

EndMacro
Macro	4
MacroName Setup_Helper
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

ReportDateTime
yyyymmdd := $reportedValue1
Echo Date: $yyyymmdd

Echo
Echo ================================================
Echo ========== PIPELINE SETUP ==========
Echo ================================================
Echo
Echo Starting Pipeline Handler....
Echo Please provide the following information:

Echo
Echo Choose acquisition mode:
Echo 1 = Single Grid (grid already loaded on stage)
Echo 2 = Multi-Grid (use autoloader for multiple grids)
EnterOneNumber Enter acquisition mode (1 for Single, 2 for Multi-Grid):
If $reportedValue1 < 1 or $reportedValue1 > 2
   Exit Acquisition mode must be 1 (Single) or 2 (Multi-Grid)
Endif
acquisition_mode := $reportedValue1

If $acquisition_mode == 1
   Echo Acquisition mode: SINGLE GRID (grid already on stage)
   single_grid_mode := 1
   ItrNum := 1
ElseIf $acquisition_mode == 2
   Echo Acquisition mode: MULTI-GRID (autoloader)
   single_grid_mode := 0
Endif

Echo
Echo Choose workflow type:
Echo 1 = Automated (no manual intervention)
Echo 2 = Manual (pause for manual grid square selection)
EnterOneNumber Enter workflow type (1 for Automated, 2 for Manual):
If $reportedValue1 < 1 or $reportedValue1 > 2
   Exit Workflow type must be 1 (Automated) or 2 (Manual)
Endif
workflow_type := $reportedValue1

If $workflow_type == 1
   Echo Workflow: AUTOMATED
Else
   Echo Workflow: MANUAL
Endif

Echo
Echo ================================================

If $single_grid_mode == 1
   Echo ========== SINGLE GRID PRE-FLIGHT ==========
   Echo ================================================
   Echo
   Echo CRITICAL PRE-FLIGHT CHECKS:
   Echo
   Echo 1. Align beam and check microscope settings
   Echo 2. LOAD your grid onto the stage
   Echo 3. Ensure grid is properly centered
   Echo 4. Check focus and beam settings
   Echo
   Echo ================================================

   YesNoBox Is a grid LOADED on the stage and ready for acquisition? Click YES to continue.
   If $reportedValue1 == 0
      Echo
      Echo User indicated grid is NOT ready on stage
      Echo Please load grid and verify microscope is ready
      Exit User aborted - Pre-flight checks not complete
   Endif
Else
   Echo ========== MULTI-GRID PRE-FLIGHT ==========
   Echo ================================================
   Echo
   Echo CRITICAL PRE-FLIGHT CHECKS:
   Echo
   Echo 1. Align beam and check microscope settings
   Echo 2. UNLOAD any grid currently in the stage
   Echo 3. Ensure all grids are in autoloader slots only
   Echo 4. If a grid is loaded, the script will skip that slot
   Echo
   Echo ================================================

   YesNoBox Is the stage EMPTY and all grids in the autoloader? Click YES to continue.
   If $reportedValue1 == 0
      Echo
      Echo User indicated stage is NOT empty or setup incomplete
      Echo Please unload any grid and verify autoloader is ready
      Exit User aborted - Pre-flight checks not complete
   Endif
Endif

UserSetDirectory [Choose the BASE directory where files will be saved]
base_directory := $reportedValue1
Echo Base directory: $base_directory

DoesFileExist $base_directory\grid_squares
looks_like_session = $reportedValue1
DoesFileExist $base_directory\targets
If $reportedValue1 == 1
   looks_like_session = 1
Endif
If $looks_like_session == 1
   Echo
   Echo ############################################################
   Echo # WARNING: this looks like a SESSION folder, not a base folder
   Echo #   $base_directory
   Echo #
   Echo # It already contains grid_squares\ or targets\.
   Echo # REyes appends -reyes itself, so this would create
   Echo #   $base_directory\<sample>-reyes
   Echo # and the run would look for its files one level too deep.
   Echo # You probably want the PARENT of this folder.
   Echo ############################################################
   Echo
   YesNoBox Use this directory anyway? NO lets you re-choose.
   If $reportedValue1 == 0
      Exit Re-run and choose the PARENT directory
   Endif
Endif

If $single_grid_mode == 0
   EnterOneNumber Enter minimum slot number (typically 1-12):
   If $reportedValue1 < 1 or $reportedValue1 > 12
      Exit Minimum slot number must be between 1 and 12
   Endif
   MinSlotNum := $reportedValue1
   Echo Minimum slot: $MinSlotNum

   EnterOneNumber Enter maximum slot number (must be >= minimum):
   If $reportedValue1 < $MinSlotNum or $reportedValue1 > 12
      Exit Maximum slot must be >= minimum slot and <= 12
   Endif
   MaxSlotNum := $reportedValue1
   Echo Maximum slot: $MaxSlotNum

   ItrNum := $MaxSlotNum - $MinSlotNum + 1
   Echo Will process $ItrNum slots (slots $MinSlotNum to $MaxSlotNum)
Endif

Echo
If $workflow_type == 1
   Echo Choose pipeline mode:
   Echo 1 = FSD (Montage -> Eucentricity -> StepScan -> Targets -> Movies)
   Echo 2 = Screen (Montage -> Eucentricity -> StepScan, NO movies)
   Echo 3 = Montage Only (Grid overview images ONLY, no processing)
   EnterOneNumber Enter pipeline mode (1 FSD, 2 Screen, 3 Montage):
   If $reportedValue1 < 1 or $reportedValue1 > 3
      Exit Pipeline mode must be 1 (FSD), 2 (Screen) or 3 (Montage)
   Endif
Else
   Echo Choose pipeline mode for MANUAL workflow:
   Echo 1 = Manual FSD (Montage -> PAUSE -> Manual Selection -> Full Pipeline with Movies)
   Echo 2 = Manual Screen (Montage -> PAUSE -> Manual Selection -> Screen Pipeline, NO movies)
   EnterOneNumber Enter pipeline mode (1 for Manual FSD, 2 for Manual Screen):
   If $reportedValue1 < 1 or $reportedValue1 > 2
      Exit Pipeline mode must be 1 (Manual FSD) or 2 (Manual Screen)
   Endif
Endif
pipeline_mode := $reportedValue1

If $pipeline_mode == 1
   If $workflow_type == 1
      Echo Pipeline mode: AUTOMATED FSD (with diffraction movies)
      pipeline_name := FSD
   Else
      Echo Pipeline mode: MANUAL FSD (with diffraction movies)
      pipeline_name := Manual_FSD
   Endif
ElseIf $pipeline_mode == 2
   If $workflow_type == 1
      Echo Pipeline mode: AUTOMATED SCREEN (no movies)
      pipeline_name := Screen
   Else
      Echo Pipeline mode: MANUAL SCREEN (no movies)
      pipeline_name := Manual_Screen
   Endif
ElseIf $pipeline_mode == 3
   Echo Pipeline mode: MONTAGE ONLY (overview images)
   pipeline_name := Montage
Endif

If $single_grid_mode == 1
   EnterDefaultedNumber 8 -1 Enter desired montage dimension (between 2 and 9):
Else
   EnterDefaultedNumber 8 -1 Enter desired montage dimension for ALL grids (between 2 and 9):
Endif
If $reportedValue1 < 2 or $reportedValue1 > 9
   Exit Montage size must be between 2 and 9
Endif
mnt_size := $reportedValue1
If $single_grid_mode == 1
   Echo Montage size: $mnt_size
Else
   Echo Montage size for all grids: $mnt_size
Endif

If $pipeline_mode == 1 or $pipeline_mode == 2
   If $single_grid_mode == 1
      EnterDefaultedNumber 11 -1 Enter desired map dimension (odd values recommended, 3-21):
   Else
      EnterDefaultedNumber 11 -1 Enter desired map dimension for ALL grids (odd values recommended, 3-21):
   Endif
   If $reportedValue1 < 3 or $reportedValue1 > 21
      Exit Map size must be between 3 and 21
   Endif
   map_size := $reportedValue1
   If $single_grid_mode == 1
      Echo StepScan map size: $map_size
   Else
      Echo StepScan map size for all grids: $map_size
   Endif
Endif

If $pipeline_mode == 1
   EnterDefaultedNumber 50 -1 Enter max positive tilt angle for movies (5-70 degrees):
   If $reportedValue1 < 5 or $reportedValue1 > 70
      Exit Tilt angle must be between 5 and 70 degrees
   Endif
   selected_tilt := $reportedValue1
   If $single_grid_mode == 1
      Echo Tilt range: +/- $selected_tilt degrees
   Else
      Echo Tilt range for all grids: +/- $selected_tilt degrees
   Endif

If $reyes_detector == 1
      tilt_rate_default = 1
      tilt_frame_default = 1

      EnterDefaultedNumber $tilt_rate_default 2 Rotation rate in deg/s:
      If $reportedValue1 < 0.1 or $reportedValue1 > 10
         Exit Rotation rate must be between 0.1 and 10 deg/s
      Endif
      dfmv_rotrate := $reportedValue1

      EnterDefaultedNumber $tilt_frame_default 2 Frame time in s (rate x frametime should be 1 deg):
      If $reportedValue1 < 0.02 or $reportedValue1 > 5
         Exit Frame time must be between 0.02 and 5 s
      Endif
      dfmv_acqrate := $reportedValue1
      Echo Rotation: $dfmv_rotrate deg/s at $dfmv_acqrate s per frame
ElseIf $reyes_detector == 2
      Echo
      Echo Ceta-D rotation: the stage turns at the rate you enter. The camera reads
      Echo out for ~4.4 s after every exposure while the stage keeps turning, so
      Echo 0.12 deg/s with 3 s frames gives 0.89 deg per frame = APPARENT 0.3 deg/s.
      Echo Only 0.12 deg/s with 3 s frames has been calibrated and tested.
      EnterDefaultedNumber 0.12 2 Stage rotation rate in deg/s (0.12 = apparent 0.3 deg/s):
      If $reportedValue1 < 0.03 or $reportedValue1 > 1
         Exit Stage rotation rate must be between 0.03 and 1 deg/s
      Endif
      dfmv_rotrate := $reportedValue1

      EnterDefaultedNumber 3 1 Exposure per frame in s (3 = calibrated):
      If $reportedValue1 < 0.5 or $reportedValue1 > 10
         Exit Exposure per frame must be between 0.5 and 10 s
      Endif
      dfmv_acqrate := $reportedValue1
      Echo Rotation: stage $dfmv_rotrate deg/s, $dfmv_acqrate s exposure per frame
      If $dfmv_rotrate != 0.12 OR $dfmv_acqrate != 3
         Echo WARNING: ROTATION_UNCALIBRATED - only 0.12 deg/s with 3 s frames has been
         Echo   calibrated and tested on the Ceta-D. Other values assume the same 4.4 s
         Echo   readout per frame; check the oscillation autoprocess uses.
      Endif
Endif
Endif

If $pipeline_mode == 1 OR $pipeline_mode == 2
   Echo
   Echo Spot size the DIFFRACTION should be collected at (NOT the LM value).
   Echo   The guard verifies this after every LM -> SA transition. It never
   Echo   SETS the spot size -- it only refuses to collect at the wrong one.
If $reyes_detector == 1
      EnterDefaultedNumber 8 -1 Expected diffraction spot size:
ElseIf $reyes_detector == 2
      EnterDefaultedNumber 10 -1 Expected diffraction spot size:
Endif
   If $reportedValue1 < 1 or $reportedValue1 > 11
      Exit Spot size must be between 1 and 11
   Endif
   spot_expected := $reportedValue1
   Echo Expected spot size: $spot_expected

   EnterDefaultedNumber 1 -1 Spot size mismatch policy (1 abort, 2 continue):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Policy must be 1 (abort) or 2 (continue)
   Endif
   spot_mismatch_policy := $reportedValue1
Endif

stpscn_redo_all := 0
dfmv_redo_all := 0

Echo
If $single_grid_mode == 1
   Echo Enter sample name for the grid on stage:
   EnterString temp_name Sample name:
   base_sample_name := $temp_name
   full_sample_name = $temp_name-reyes
   Echo Sample: $temp_name (folder: $full_sample_name)
   NewArray sample_names 1 1
   NewArray base_names 1 1
   sample_names[1] := $full_sample_name
   base_names[1] := $base_sample_name
Else
   Echo Now entering sample names for each slot...
   NewArray sample_names 1 $ItrNum
   NewArray base_names 1 $ItrNum
   SlotNum = $MinSlotNum

   Loop $ItrNum slotIndex
      Echo Enter sample name for slot $SlotNum (or 'SKIP' to skip this slot):
      EnterString temp_name Sample name for slot $SlotNum:

      CompareNoCase temp_name SKIP
      If $reportedValue1 == 0
         Echo Slot $SlotNum will be skipped
         sample_names[$slotIndex] := SKIP
         base_names[$slotIndex] := SKIP
      Else
         full_sample_name = $temp_name-reyes
         Echo Slot $SlotNum: $temp_name (folder: $full_sample_name)
         sample_names[$slotIndex] := $full_sample_name
         base_names[$slotIndex] := $temp_name
      Endif

      SlotNum = $SlotNum + 1
   EndLoop
Endif

Echo
Echo ============= CONFIRMATION =============
Echo Base directory: $base_directory
If $single_grid_mode == 1
   Echo Acquisition mode: Single Grid (on stage)
Else
   Echo Acquisition mode: Multi-Grid (autoloader)
   Echo Slots to process: $MinSlotNum to $MaxSlotNum ($ItrNum total)
Endif
If $workflow_type == 1
   Echo Workflow: Automated
Else
   Echo Workflow: Manual
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
ElseIf $reyes_detector == 2
   Echo Detector: Ceta-D
Endif
Echo Pipeline mode: $pipeline_name
Echo Montage size: $mnt_size x $mnt_size
If $pipeline_mode == 1 or $pipeline_mode == 2
   Echo StepScan map size: $map_size x $map_size
Endif
If $pipeline_mode == 1
   Echo Tilt range: +/- $selected_tilt degrees
If $reyes_detector == 1
      Echo Rotation: $dfmv_rotrate deg/s at $dfmv_acqrate s per frame
ElseIf $reyes_detector == 2
      Echo Rotation: stage $dfmv_rotrate deg/s, $dfmv_acqrate s exposure per frame
Endif
Endif
If $pipeline_mode != 3
   Echo Expected diffraction spot size: $spot_expected
Endif
Echo
If $single_grid_mode == 1
   Echo Sample folder name (with -reyes suffix for database):
   Echo   $sample_names[1]
Else
   Echo Sample folder names (with -reyes suffix for database):
   SlotNum = $MinSlotNum
   Loop $ItrNum slotIndex
      Echo   Slot $SlotNum: $sample_names[$slotIndex]
      SlotNum = $SlotNum + 1
   EndLoop
Endif
Echo =======================================

YesNoBox Do you want to proceed with these settings?
If $reportedValue1 == 0
   Exit User cancelled the operation
Endif

SetDirectory $base_directory
log_sep @= _
If $single_grid_mode == 1
   grid_prefix @= SingleGrid
Else
   grid_prefix @= MultiGrid
Endif
setup_log_name @= $grid_prefix$log_sep$pipeline_name$log_sep$yyyymmdd
SaveLogOpenNew $setup_log_name
EndMacro
Macro	5
MacroName Slot_Verification_Helper

Echo
Echo ============= STEP 1: SLOT VERIFICATION =============
Echo Checking autoloader slots for grids...
Echo

SlotNum = $MinSlotNum
missing_grids = 0
NewArray slot_status 1 $ItrNum

Loop $ItrNum slotIndex
   current_sample = $sample_names[$slotIndex]

   CompareNoCase current_sample SKIP
   If $reportedValue1 == 0
      Echo Slot $SlotNum: SKIP (user requested)
      slot_status[$slotIndex] := 0
      SlotNum = $SlotNum + 1
      Continue
   Endif

   Echo Checking slot $SlotNum ($current_sample)...
   ReportSlotStatus $SlotNum

   If $reportedValue1 != 1
      Echo   ERROR: No grid detected in slot $SlotNum!
      slot_status[$slotIndex] := -1
      missing_grids = $missing_grids + 1
   Else
      Echo   OK: Grid present in slot $SlotNum
      slot_status[$slotIndex] := 1
   Endif

   SlotNum = $SlotNum + 1
EndLoop

Echo
Echo Slot verification complete
Echo Grids detected: $ItrNum - $missing_grids
Echo Missing grids: $missing_grids

If $missing_grids > 0
   Echo
   Echo ================================================
   Echo WARNING: MISSING GRIDS DETECTED
   Echo ================================================
   Echo The following slots are missing grids:
   Echo
   SlotNum = $MinSlotNum
   Loop $ItrNum slotIndex
      If $slot_status[$slotIndex] == -1
         Echo   Slot $SlotNum: $sample_names[$slotIndex] - NO GRID FOUND
      Endif
      SlotNum = $SlotNum + 1
   EndLoop
   Echo
   Echo ================================================
   YesNoBox Load missing grids now? Click NO to abort, or YES to recheck slots.
   If $reportedValue1 == 0
      Exit User aborted - Missing grids in autoloader
   Else
      Echo
      Echo Please load the missing grids into their slots
      Echo Then click OK to verify all grids are present
      Pause Load missing grids, then click OK to recheck

      Echo
      Echo Rechecking all slots...
      SlotNum = $MinSlotNum
      missing_grids = 0

      Loop $ItrNum slotIndex
         current_sample = $sample_names[$slotIndex]

         CompareNoCase current_sample SKIP
         If $reportedValue1 == 0
            SlotNum = $SlotNum + 1
            Continue
         Endif

         If $slot_status[$slotIndex] == -1
            Echo Rechecking slot $SlotNum ($current_sample)...
            ReportSlotStatus $SlotNum

            If $reportedValue1 != 1
               Echo   STILL MISSING: No grid in slot $SlotNum!
               missing_grids = $missing_grids + 1
            Else
               Echo   FIXED: Grid now present in slot $SlotNum
               slot_status[$slotIndex] := 1
            Endif
         Endif

         SlotNum = $SlotNum + 1
      EndLoop

      If $missing_grids > 0
         Echo
         Echo ERROR: $missing_grids grids still missing after recheck
         Exit Cannot proceed - Missing grids in autoloader
      Else
         Echo
         Echo SUCCESS: All grids are now present!
      Endif
   Endif
Endif

Echo
Echo Slot verification complete
EndMacro
Macro	6
MacroName Directory_Setup_Helper

Echo
Echo ============= STEP 2: DIRECTORY SETUP =============

If $single_grid_mode == 1
   Echo Creating sample directory...
   sample_dir_path = $base_directory\$sample_names[1]
   Echo Creating directory: $sample_dir_path

   Try
      MakeDirectory $sample_dir_path
      Echo   SUCCESS: Created $sample_dir_path
   Catch
      Echo   ERROR: Could not create directory $sample_dir_path
      Exit Cannot proceed without sample directory
   EndTry

   NewArray slot_status 1 1
   slot_status[1] := 1
Else
   Echo Creating sample directories for verified grids...

   SlotNum = $MinSlotNum
   setup_failures = 0

   Loop $ItrNum slotIndex
      current_sample = $sample_names[$slotIndex]

      If $slot_status[$slotIndex] != 1
         Echo Slot $SlotNum: Skipping directory creation (no grid or skipped)
         SlotNum = $SlotNum + 1
         Continue
      Endif

      sample_dir_path = $base_directory\$current_sample
      Echo Creating directory for slot $SlotNum: $sample_dir_path

      Try
         MakeDirectory $sample_dir_path
         Echo   SUCCESS: Created $sample_dir_path
      Catch
         Echo   ERROR: Could not create directory $sample_dir_path
         setup_failures = $setup_failures + 1
         slot_status[$slotIndex] := -2
      EndTry

      SlotNum = $SlotNum + 1
   EndLoop

   Echo
   Echo Directory setup complete

   If $setup_failures > 0
      Echo WARNING: $setup_failures directories could not be created
      YesNoBox Continue anyway? (Failed samples will be skipped during acquisition)
      If $reportedValue1 == 0
         Exit User cancelled due to directory creation failures
      Endif
   Endif
Endif
EndMacro
Macro	7
MacroName Automated_Pipeline_Helper
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

Echo
Echo ====== STARTING AUTOMATED PIPELINE FOR $current_sample ======

grid_blocks_aside = 0
grid_items_aside = 0

If $pipeline_mode == 1
   Echo Running FULL FSD Pipeline (7 steps total)
   Echo This will take several hours per grid
   total_steps := 7
ElseIf $pipeline_mode == 2
   Echo Running SCREEN Pipeline (5 steps total)
   Echo This will take 1-3 hours per grid
   total_steps := 5
ElseIf $pipeline_mode == 3
   Echo Running MONTAGE ONLY (1 step)
   Echo This will take ~5-10 minutes per grid
   total_steps := 1
Endif

IsVariableDefined resume_from
If $reportedValue1 == 0
   resume_from := 1
EndIf

If $resume_from > $total_steps
   Echo RESUME | stage $resume_from does not exist in this pipeline ($total_steps stages)
   Exit Cannot resume from stage $resume_from: this pipeline has $total_steps stages
EndIf

If $resume_from > 1
   Echo
   Echo RESUME | from_stage=$resume_from - earlier stages will be SKIPPED
   Echo

If $reyes_detector == 1
      rs_montage = _115LM_$mnt_sizex$mnt_size
ElseIf $reyes_detector == 2
      rs_montage = _210LM_$mnt_sizex$mnt_size
Endif
   rs_navtail = _nav.nav
   rs_nav_file = $samplename$rs_montage$rs_navtail
   ReportIfNavOpen
   If $reportedValue1 == 0
      DoesFileExist $rs_nav_file
      If $reportedValue1 == 0
         Echo
         Echo RESUME | no navigator is open and $rs_nav_file is not in
         Echo          $set_directory
         Echo Check the base directory, the sample name and the montage size:
         Echo all three must match the interrupted run.
         Exit Cannot resume: no navigator is open and its file was not found
      EndIf
      ReadNavFile $rs_nav_file
      Echo RESUME | navigator=read_from_file | file=$rs_nav_file
   Else
      Echo RESUME | navigator=already_open (expected: $rs_nav_file)
   EndIf
   ReportNumTableItems
   rs_nav_items = $reportedValue1
   Echo RESUME | navigator_items=$rs_nav_items

   If $resume_from == 2 OR $resume_from == 3
      rs_extra = $rs_nav_items - 1
      If $rs_extra > 0
         Echo RESUME | removing $rs_extra item(s): eucentricity starts from the montage map alone
         Loop $rs_extra
            DeleteNavigatorItem -1
         EndLoop
         SaveNavigator
      EndIf
   EndIf

   If $resume_from == 5
      If $rs_nav_items <= 1
         Echo RESUME | navigator holds no grid squares - merging grid_squares.nav again
         Call REyes_postECNT
         SaveNavigator
      Else
         rs_ok = 0
         OpenTextFile RSRANGE T 0 targets\range_dfmv.txt
         If $reportedValue1 == 1
            ReadLineToArray RSRANGE rs_vals
            rs_ok = $reportedValue1
            CloseTextFile RSRANGE
         EndIf
         If $rs_ok == 1
            rs_drop = $rs_nav_items - $rs_vals[1] + 1
            If $rs_drop > 0 AND $rs_vals[1] >= 3
               Echo RESUME | removing $rs_drop crystal target item(s) from $rs_vals[1] on - the step-scan walks grid squares only
               Loop $rs_drop
                  DeleteNavigatorItem -1
               EndLoop
               RemoveFile targets\range_dfmv.txt
               SaveNavigator
            EndIf
         EndIf
      EndIf
   EndIf
EndIf

If $resume_from <= 1
   Echo [1/$total_steps] Starting grid montage acquisition...
   Call REyes_MNT
   Echo [1/$total_steps] Grid montage completed successfully
   Echo STAGE_DONE | stage=MNT
Else
   Echo [1/$total_steps] SKIPPED (resuming from stage $resume_from)
EndIf

If $pipeline_mode == 1 or $pipeline_mode == 2

   If $resume_from <= 2
      Echo [2/$total_steps] Finding grid squares in the montage...
      Call ECNT_nav_ready
      Echo [2/$total_steps] Grid squares found successfully
      Echo STAGE_DONE | stage=GRIDSQUARES
   Else
      Echo [2/$total_steps] SKIPPED (resuming from stage $resume_from)
   Endif

   If $resume_from <= 3
      Echo [3/$total_steps] Determining eucentricity for the grid...
      Call REyes_ECNT
      Echo [3/$total_steps] Eucentricity points determined successfully
      Echo STAGE_DONE | stage=ECNT
   Else
      Echo [3/$total_steps] SKIPPED (resuming from stage $resume_from)
   Endif

   If $resume_from <= 4
   Echo [4/$total_steps] Processing eucentricity data...
   Call ECNT_corrected
   Call REyes_postECNT
   SaveNavigator
   Echo [4/$total_steps] Eucentric plane found successfully
   Echo STAGE_DONE | stage=POSTECNT
   Else
      Echo [4/$total_steps] SKIPPED (resuming from stage $resume_from)
   Endif

   If $resume_from > 5
      Echo [5/$total_steps] SKIPPED (resuming from stage $resume_from)
   Endif
   If $resume_from <= 5
      Echo [5/$total_steps] Performing StepScan...
      If $reyes_detector == 2
         Call REyes_STPSCN_CETA
      Else
         Call REyes_STPSCN_Apollo
      Endif
      If $reyes_spot_ok == 0
         Echo
         Echo StepScan abandoned: the microscope is not in a usable state.
         Echo NOTHING was mapped for this grid.
         Echo
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := Spot_guard_stopped_stepscan
         failed_grids = $failed_grids + 1
         partial_completion := 1
         Return
      Endif
      If $stpscn_collected == 0
         Echo
         Echo StepScan finished with NO grid square mapped - every square was set aside.
         Echo Not waiting for targets. See BLOCK_SKIPPED lines in the block logs.
         Echo
         grid_results[$slotIndex] := FAILED
         failure_reasons[$slotIndex] := All_blocks_failed
         failed_grids = $failed_grids + 1
         partial_completion := 1
         Return
      Endif
      grid_blocks_aside = $stpscn_set_aside
      If $stpscn_set_aside > 0
         Echo [5/$total_steps] $stpscn_set_aside grid square(s) set aside - continuing with the $stpscn_collected that have data
      Endif
      Echo [5/$total_steps] All grid squares mapped
   Endif

Endif

If $pipeline_mode == 1
   If $resume_from <= 6
      Echo [6/7] Processing Diffraction Map...
      Call Targets_nav_ready

      If $targets_found == 0
         Echo
         Echo Skipping movie collection for this grid
         Echo
         grid_results[$slotIndex] := PARTIAL
         failure_reasons[$slotIndex] := No_targets_found
         successful_grids = $successful_grids + 1
         partial_completion := 1
         Echo PARTIAL SUCCESS: $current_sample completed screening but no targets for movies

         Return
      Endif

      Echo [6/7] All targets identified successfully
   Else
      Echo [6/7] SKIPPED (resuming from stage $resume_from)
   Endif

   Echo [7/7] Collecting continuous rotation data...
   If $reyes_detector == 2
      Call REyes_DFMV_CETA
   Else
      Call REyes_DFMV_Apollo
   Endif
   If $reyes_spot_ok == 0
      Echo
      Echo Movie collection abandoned: the microscope is not in a usable state.
      Echo NO rotation data was collected for this grid.
      Echo
      grid_results[$slotIndex] := FAILED
      failure_reasons[$slotIndex] := Spot_guard_stopped_dfmv
      failed_grids = $failed_grids + 1
      partial_completion := 1
      Return
   Endif
   grid_items_aside = $grid_items_aside + $dfmv_set_aside
   Echo [7/7] All movies collected

   Echo ====== FSD PIPELINE COMPLETED FOR $current_sample ======
ElseIf $pipeline_mode == 2
   Echo ====== SCREEN PIPELINE COMPLETED FOR $current_sample ======
ElseIf $pipeline_mode == 3
   Echo ====== MONTAGE COMPLETED FOR $current_sample ======
Endif

grid_aside_total = $grid_blocks_aside + $grid_items_aside
If $grid_aside_total > 0
   sa_blocks_txt @= Blocks_set_aside_
   sa_items_txt @= Items_set_aside_
   sa_sep @= _
   grid_results[$slotIndex] := SUCCESS
   If $grid_blocks_aside > 0 AND $grid_items_aside > 0
      failure_reasons[$slotIndex] := $sa_blocks_txt$grid_blocks_aside$sa_sep$sa_items_txt$grid_items_aside
   ElseIf $grid_blocks_aside > 0
      failure_reasons[$slotIndex] := $sa_blocks_txt$grid_blocks_aside
   Else
      failure_reasons[$slotIndex] := $sa_items_txt$grid_items_aside
   Endif
   successful_grids = $successful_grids + 1
   partial_completion := 1
   Echo SUCCESS: $current_sample completed - $grid_blocks_aside grid square(s) and $grid_items_aside item(s) set aside
Endif

SaveNavigator
SaveLog
EndMacro
Macro	8
MacroName Manual_Pipeline_Part1

Echo
Echo ====== STARTING MANUAL PIPELINE FOR $current_sample ======

If $pipeline_mode == 1
   Echo Running MANUAL FSD Pipeline (7 steps total)
   Echo This will take several hours
   total_steps := 7
ElseIf $pipeline_mode == 2
   Echo Running MANUAL SCREEN Pipeline (5 steps total)
   Echo This will take 1-3 hours
   total_steps := 5
Endif

Echo
Echo ================================================
Echo ===== PART 1: MONTAGE ACQUISITION =====
Echo ================================================

Echo [1/$total_steps] Starting grid montage acquisition...
Call REyes_MNT
Echo [1/$total_steps] Grid montage completed successfully

Echo
Echo Montage complete - returning to main script for manual selection
Echo
EndMacro
Macro	9
MacroName Manual_Pipeline_Part2
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

grid_blocks_aside = 0
grid_items_aside = 0

Echo
Echo ================================================
Echo ===== CONTINUING MANUAL PIPELINE AFTER PAUSE =====
Echo ================================================
Echo
Echo NOTE: Ensure a REyes job (local terminal or HPC) is monitoring the sample directory:
Echo   $base_directory\$current_sample
Echo
Echo REyes will process the manually selected grid squares.
Echo

Echo
Echo ================================================
Echo ===== PART 2: CONTINUING PIPELINE =====
Echo ================================================

Echo [2/$total_steps] Saving manually added grid squares to navigator...
Call REyes_saveNAV
Call Manual_ready
Echo [2/$total_steps] Navigator saved and selected squares are ready

Echo Preparing navigator for eucentricity...
Call REyes_premanualECNT
Echo Navigator is ready for Eucentricity step

Echo Processing manually selected grid squares...
Call ECNT_nav_ready
Echo Manual grid squares processed successfully

Echo [3/$total_steps] Determining eucentricity for the grid...
Call REyes_ECNT
Echo [3/$total_steps] Eucentricity points determined successfully

Echo [4/$total_steps] Processing eucentricity data...
Call ECNT_corrected
Call REyes_postECNT
Echo [4/$total_steps] Eucentric plane found successfully

Echo [5/$total_steps] Performing StepScan...
If $reyes_detector == 2
   Call REyes_STPSCN_CETA
Else
   Call REyes_STPSCN_Apollo
Endif
If $reyes_spot_ok == 0
   Echo
   Echo StepScan abandoned: the microscope is not in a usable state.
   Echo NOTHING was mapped for this grid.
   Echo
   grid_results[$slotIndex] := FAILED
   failure_reasons[$slotIndex] := Spot_guard_stopped_stepscan
   failed_grids = $failed_grids + 1
   partial_completion := 1
   Return
Endif
If $stpscn_collected == 0
   Echo
   Echo StepScan finished with NO grid square mapped - every square was set aside.
   Echo Not waiting for targets. See BLOCK_SKIPPED lines in the block logs.
   Echo
   grid_results[$slotIndex] := FAILED
   failure_reasons[$slotIndex] := All_blocks_failed
   failed_grids = $failed_grids + 1
   partial_completion := 1
   Return
Endif
grid_blocks_aside = $stpscn_set_aside
If $stpscn_set_aside > 0
   Echo [5/$total_steps] $stpscn_set_aside grid square(s) set aside - continuing with the $stpscn_collected that have data
Endif
Echo [5/$total_steps] All grid squares mapped

If $pipeline_mode == 1
   Echo [6/7] Processing Diffraction Map...
   Call Targets_nav_ready

   If $targets_found == 0
      Echo
      Echo Skipping movie collection for this grid
      Echo
      grid_results[$slotIndex] := PARTIAL
      failure_reasons[$slotIndex] := No_targets_found
      successful_grids = $successful_grids + 1
      partial_completion := 1
      Echo PARTIAL SUCCESS: $current_sample completed screening but no targets for movies
      Echo Status: PARTIAL - Screening completed but no targets for movies
      Echo Steps completed: 1-5 (montage through StepScan)
      Echo Steps skipped: 6-7 (target selection and movie collection)

      Return
   Endif

   Echo [6/7] All targets identified successfully

   Echo [7/7] Collecting continuous rotation data...
   If $reyes_detector == 2
      Call REyes_DFMV_CETA
   Else
      Call REyes_DFMV_Apollo
   Endif
   If $reyes_spot_ok == 0
      Echo
      Echo Movie collection abandoned: the microscope is not in a usable state.
      Echo NO rotation data was collected for this grid.
      Echo
      grid_results[$slotIndex] := FAILED
      failure_reasons[$slotIndex] := Spot_guard_stopped_dfmv
      failed_grids = $failed_grids + 1
      partial_completion := 1
      Return
   Endif
   grid_items_aside = $grid_items_aside + $dfmv_set_aside
   Echo [7/7] All movies collected

   Echo
   Echo ================================================
   Echo ===== MANUAL FSD PIPELINE COMPLETED =====
   Echo ================================================
ElseIf $pipeline_mode == 2
   Echo
   Echo ================================================
   Echo ===== MANUAL SCREEN PIPELINE COMPLETED =====
   Echo ================================================
Endif

grid_aside_total = $grid_blocks_aside + $grid_items_aside
If $grid_aside_total > 0
   sa_blocks_txt @= Blocks_set_aside_
   sa_items_txt @= Items_set_aside_
   sa_sep @= _
   grid_results[$slotIndex] := SUCCESS
   If $grid_blocks_aside > 0 AND $grid_items_aside > 0
      failure_reasons[$slotIndex] := $sa_blocks_txt$grid_blocks_aside$sa_sep$sa_items_txt$grid_items_aside
   ElseIf $grid_blocks_aside > 0
      failure_reasons[$slotIndex] := $sa_blocks_txt$grid_blocks_aside
   Else
      failure_reasons[$slotIndex] := $sa_items_txt$grid_items_aside
   Endif
   successful_grids = $successful_grids + 1
   partial_completion := 1
   Echo SUCCESS: $current_sample completed - $grid_blocks_aside grid square(s) and $grid_items_aside item(s) set aside
Endif
EndMacro
Macro	10
MacroName REyes_Setup_Automated
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

Echo
Echo ================================================
Echo ============= IMPORTANT: REYES SETUP ===========
Echo ================================================
Echo
Echo CRITICAL STEP - READ CAREFULLY:
Echo
Echo 1. A SEPARATE REyes job must now be watching EACH sample
Echo    directory that was just created. It can run in a terminal
Echo    on this PC or as a job on an HPC / processing server.
Echo
Echo 2. Directory created:
Echo
If $single_grid_mode == 1
   Echo    - $base_directory\$sample_names[1]
Else
   SlotNum = $MinSlotNum
   Loop $ItrNum slotIndex
      current_sample = $sample_names[$slotIndex]
      If $slot_status[$slotIndex] == 1
         Echo    - $base_directory\$current_sample
      Endif
      SlotNum = $SlotNum + 1
   EndLoop
Endif
Echo
Echo 3. Each REyes job must monitor its own sample directory
If $reyes_detector == 1
   Echo    and run with --microscope Arctica-Apollo-SM.
ElseIf $reyes_detector == 2
   Echo    and run with --microscope Arctica-CETA.
Endif
Echo
Echo 4. Do NOT proceed until EVERY REyes job is running and
Echo    ready to process data.
Echo
Echo 5. Check that each job is actively monitoring: its startup
Echo    messages in the terminal, or its log / queue status on the HPC.
Echo
Echo ================================================

YesNoBox Is a REyes job initiated for EVERY sample folder (local terminal or HPC job)?
If $reportedValue1 == 0
   Echo
   Echo User indicated REyes is NOT ready
   Echo ABORTING: Please start a REyes job for every sample folder and run the script again
   Echo No data has been acquired - you can safely restart
   Exit User aborted - REyes jobs not ready
Endif

Echo
Echo User confirmed a REyes job is initiated for every sample folder
If $single_grid_mode == 0
   Echo Proceeding with multi-grid acquisition...
Else
   Echo Proceeding with acquisition...
Endif
EndMacro
Macro	11
MacroName REyes_Setup_Optional

Echo
Echo ================================================
Echo Montage-only mode selected - REyes NOT required
Echo Proceeding directly to acquisition...
Echo ================================================
EndMacro
Macro	13
ScriptName BatchED_Rotation

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 1
SetExposure R $recordtime
SetBinning R $binning
SetFrameTime R $acqrate

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1

      movdir = $compoundname-mov$xtalct_$apollodistmm_$rotratedps_$acqratespf_$range_sp$spszg8_sweep$sweepcount_$temp
      SetFolderForFrames $movdir

      movname = $compoundname-mov$xtalct_$apollodist_$rotrate_$acqrate_$range_g8sp$spsz_$temp.mrc

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Movie folder: $movdir
      Echo Movie name: $movname

      MoveToNavItem $xtalct
      Delay 1 sec

      TiltTo $startangle + 3
      TiltTo $startangle
      Delay 2 sec

      ReportTiltAngle
      Echo Starting tilt angle: $reportedValue1

      GoToLowDoseArea R

      UseContinuousFrames 1

      ReportStageXYZ
      Echo Stage position before tilt: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      Echo STARTING TILT
      ReportClock

      BackgroundTilt $finalangle $rotincr

      Record

      StopContinuous

      Echo END TILT
      Echo Movie folder: $movdir
      Echo Acquired movie: $movname
      ReportClock

      ReportStageXYZ
      Echo Stage position after tilt: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      TiltTo 0
      ReportTiltAngle
      Echo Returned to tilt: $reportedValue1

      Delay 5 sec
      RunInShell mkdir $set_directory\movies\$movdir
      RunInShell copy D:\DEOutput\Apollo\$movdir $set_directory\movies\$movdir
      If $reportedValue1 != 0
         Echo WARNING: Error copying frames for $movdir
      Endif

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	14
ScriptName BatchED_Still

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 0
SetExposure R $acqrate
SetBinning R $binning
SetFrameTime R $acqrate

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1

      MoveToNavItem $xtalct
      Delay 1 sec

      GoToLowDoseArea R

      ReportTiltAngle
      currentangle = $reportedValue1
      Echo Current tilt angle: $currentangle

      movdir = $compoundname-mov$xtalct_$apollodistmm_$acqratespf_sp$spsz_$currentangle_sweep$sweepcount_$temp
      SetFolderForFrames $movdir

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Frame folder: $movdir

      ReportStageXYZ
      Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      Echo ACQUIRING SNAPSHOT
      ReportClock

      Record

      Echo Frame folder: $movdir
      ReportClock

      Delay 5 sec
      RunInShell mkdir $set_directory\snapshots\$movdir
      RunInShell copy D:\DEOutput\Apollo\$movdir $set_directory\snapshots\$movdir
      If $reportedValue1 != 0
         Echo WARNING: Error copying frames for $movdir
      Endif

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	15
ScriptName BatchED_MultiAngle

angles = {60 30 0 -30 -60}
angleslabel = P60P30Z0N30N60

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 0
SetExposure R $acqrate
SetBinning R $binning
SetFrameTime R $acqrate

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1

      MoveToNavItem $xtalct
      Delay 1 sec

      GoToLowDoseArea R

      movdir = $compoundname-mov$xtalct_$apollodistmm_$acqratespf_sp$spsz_$angleslabel_sweep$sweepcount_$temp
      SetFolderForFrames $movdir

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Frame folder: $movdir
      Echo Collecting 5 angles: +60, +30, 0, -30, -60 degrees

      ReportStageXYZ
      Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      Loop 5 idx
         tiltangle = $angles[$idx]

         Echo Tilting to $tiltangle degrees...
         TiltTo $tiltangle
         Delay 2 sec

         ReportTiltAngle
         Echo Acquiring snapshot at tilt angle: $reportedValue1
         ReportClock

         Record

         Echo Snapshot $idx of 5 complete (angle: $tiltangle)
      EndLoop

      Echo Frame folder: $movdir
      ReportClock

      TiltTo 0
      ReportTiltAngle
      Echo Returned to tilt: $reportedValue1

      Delay 5 sec
      RunInShell mkdir $set_directory\snapshots\$movdir
      RunInShell copy D:\DEOutput\Apollo\$movdir $set_directory\snapshots\$movdir
      If $reportedValue1 != 0
         Echo WARNING: Error copying frames for $movdir
      Endif

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	16
ScriptName BatchED_Imaging

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous S 0
SetExposure S $acqrate
SetBinning S $binning
SetFrameTime S $acqrate

Loop $nitems
   xtalct := $xtalct + 1

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   MoveToNavItem $xtalct
   Delay 1 sec

   searchdir = $compoundname_item$xtalct
   SetFolderForFrames $searchdir

   Echo Frame folder: $searchdir

   GoToLowDoseArea S

   ReportStageXYZ
   Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

   Echo ACQUIRING SEARCH IMAGE
   ReportClock

   Search

   Echo Frame folder: $searchdir
   ReportClock

   Delay 5 sec
   RunInShell mkdir $set_directory\imaging\$searchdir
   RunInShell copy D:\DEOutput\Apollo\$searchdir $set_directory\imaging\$searchdir
   If $reportedValue1 != 0
      Echo WARNING: Error copying frames for $searchdir
   Endif

   Echo Completed target: $xtalct
   Echo

EndLoop
EndMacro
Macro	19
MacroName AutoloaderScreen
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

If $reyes_detector == 1
   MinSlotNum    := 2
   MaxSlotNum  := 5
ElseIf $reyes_detector == 2
   MinSlotNum    := 3
   MaxSlotNum  := 6
Endif

ItrNum := $MaxSlotNum - $MinSlotNum + 1
SlotNum = $MinSlotNum

Loop $ItrNum

   ReportSlotStatus $SlotNum
   If $reportedValue1 == 1

      SetColumnOrGunValve 0
      LoadCartridge $SlotNum
      SetColumnOrGunValve 1
      TiltTo 0
      MoveStageTo 0 0 20
      M
      NewMap

   ElseIf $SlotNum == $MinSlotNum

      SetColumnOrGunValve 1
      TiltTo 0
      MoveStageTo 0 0 20
      M
      NewMap

   Endif

   SlotNum = $SlotNum + 1

EndLoop

SetColumnOrGunValve 0
EndMacro
Macro	20
ScriptName BatchED_Main_CETA

ClearPersistentVars

Echo
Echo ================================================
Echo ===== BATCHED - UNIFIED SETUP (CETA-M) =====
Echo ================================================
Echo

Echo Choose acquisition mode:
Echo 1 = Diffraction (Record mode - parallel beam)
Echo 2 = Imaging (Search mode - imaging beam)
Echo
EnterOneNumber Enter acquisition mode (1 = Diffraction, 2 = Imaging):
If $reportedValue1 != 1 AND $reportedValue1 != 2
   Exit Acquisition mode must be 1 (Diffraction) or 2 (Imaging)
Endif
acq_mode := $reportedValue1

If $acq_mode == 1
   Echo Mode: DIFFRACTION (Record)

   Echo
   Echo Choose diffraction type:
   Echo 1 = Continuous rotation (tilt during exposure)
   Echo 2 = Still snapshot (no tilt during exposure)
   Echo 3 = Multi-angle snapshots (5 angles: +60, +30, 0, -30, -60)
   Echo
   EnterOneNumber Enter diffraction type (1 = Rotation, 2 = Still, 3 = Multi-angle):
   If $reportedValue1 != 1 AND $reportedValue1 != 2 AND $reportedValue1 != 3
      Exit Diffraction type must be 1 (Rotation), 2 (Still), or 3 (Multi-angle)
   Endif
   diff_type := $reportedValue1

   If $diff_type == 1
      Echo Type: CONTINUOUS ROTATION
   ElseIf $diff_type == 2
      Echo Type: STILL SNAPSHOT
   ElseIf $diff_type == 3
      Echo Type: MULTI-ANGLE SNAPSHOTS (+60, +30, 0, -30, -60)
   Endif

ElseIf $acq_mode == 2
   Echo Mode: IMAGING (Search)
   diff_type := 0
Endif

ReportDirectory
set_directory := $reportedValue1
Echo Working directory: $set_directory

Echo
EnterString compound_name Enter your compound/sample name:
compoundname := $compound_name
Echo Compound name: $compoundname

Echo
Echo Navigator Setup:
Echo - You should have already added your target points
Echo - The script needs to know where your targets start
Echo
EnterOneNumber Enter the LAST navigator item number BEFORE your targets were added:
If $reportedValue1 < 0
   Exit Navigator offset must be positive
Endif
xtalct := $reportedValue1
Echo Starting from navigator item: $xtalct

EnterOneNumber Enter the NUMBER of targets you want to collect:
If $reportedValue1 < 1
   Exit Must collect at least 1 target
Endif
nitems := $reportedValue1
Echo Number of targets: $nitems

Echo
Echo Frame Acquisition Rate:
Echo - Time per frame in seconds
Echo - CETA-M typical: 3.0 seconds (calibrated)
Echo - Range: 0.5 to 10 seconds
Echo
EnterOneNumber Enter frame time in seconds:
If $reportedValue1 < 0.1 or $reportedValue1 > 10
   Exit Frame time must be between 0.1 and 10 seconds
Endif
acqrate := $reportedValue1
Echo Frame time: $acqrate seconds per frame

Echo
Echo Camera Binning:
Echo - CETA-M recommended: 2x
Echo - Options: 1, 2, 4, 8, or 16
Echo - Higher binning = faster readout, lower resolution
Echo
EnterOneNumber Enter binning factor (1, 2, 4, 8, or 16):
If $reportedValue1 != 1 AND $reportedValue1 != 2 AND $reportedValue1 != 4 AND $reportedValue1 != 8 AND $reportedValue1 != 16
   Exit Binning must be 1, 2, 4, 8, or 16
Endif
binning := $reportedValue1
Echo Binning: $binning

If $acq_mode == 1 AND $diff_type == 1

   Echo
   Echo Tilt Range:
   Echo - Typical values: 30-60 degrees
   Echo - Range: 5 to 70 degrees
   Echo
   EnterOneNumber Enter maximum positive tilt angle:
   If $reportedValue1 < 5 or $reportedValue1 > 70
      Exit Tilt angle must be between 5 and 70 degrees
   Endif
   startangle := $reportedValue1
   finalangle := -1 * $startangle
   tiltrange := 2 * $startangle
   range := P$startangletoN$finalangle
   Echo Tilt range: +$startangle to $finalangle degrees

   Echo
   Echo Rotation Rate:
   Echo - CETA-M typical: 0.3 dps (calibrated)
   Echo - Range: 0.1 to 5.0 dps
   Echo - Slower = better signal but longer exposure
   Echo
   EnterOneNumber Enter rotation rate in degrees per second:
   If $reportedValue1 < 0.1 or $reportedValue1 > 5
      Exit Rotation rate must be between 0.1 and 5 dps
   Endif
   rotrate := $reportedValue1
   Echo Rotation rate: $rotrate dps

   rotincr := 0.004 * ($rotrate / 0.3)
   Echo Rotation increment: $rotincr (calibrated for CETA-M frame overhead)

   recordtime := $tiltrange / $rotrate
   Echo Exposure time: $recordtime seconds

Endif

If $acq_mode == 1
   Echo
   Echo Multiple Sweeps:
   Echo - Collect multiple acquisitions on the same crystal
   Echo - Typically 1 (single collection per target)
   Echo
   EnterOneNumber Enter number of sweeps per target:
   If $reportedValue1 < 1 or $reportedValue1 > 10
      Exit Number of sweeps must be between 1 and 10
   Endif
   nsweeps := $reportedValue1
   Echo Sweeps per target: $nsweeps
Endif

If $acq_mode == 1
   ReportSpotSize
   spsz := $reportedValue1
   Echo Spot size: $spsz

   ReportCameraLength
   dist := $reportedValue1 * 1000
   Echo Talos camera length: $dist mm

   If $dist == 840
      cetadist := 790
   ElseIf $dist == 960
      cetadist := 960
   Else
      Echo Warning: Unusual camera length detected
      cetadist := $dist
   Endif
   Echo CETA calibrated camera length: $cetadist mm

   temp := c
Endif

Echo
Echo ================================================
Echo ===== ACQUISITION SUMMARY =====
Echo ================================================
Echo Compound: $compoundname

If $acq_mode == 1
   If $diff_type == 1
      Echo Mode: DIFFRACTION - CONTINUOUS ROTATION (CETA-M)
      Echo Tilt range: +$startangle to $finalangle degrees ($tiltrange total)
      Echo Rotation rate: $rotrate dps
      Echo Rotation increment: $rotincr (CETA-M calibrated)
      Echo Exposure time: $recordtime seconds
   ElseIf $diff_type == 2
      Echo Mode: DIFFRACTION - STILL SNAPSHOT
   ElseIf $diff_type == 3
      Echo Mode: DIFFRACTION - MULTI-ANGLE SNAPSHOTS
      Echo Angles: +60, +30, 0, -30, -60 degrees (5 per target)
   Endif
   Echo Frame time: $acqrate s/frame
   Echo Binning: $binning
   Echo Sweeps per target: $nsweeps
   Echo Camera length: $cetadist mm (CETA-M calibrated)
   Echo Spot size: $spsz
   Echo Temperature: $temp
ElseIf $acq_mode == 2
   Echo Mode: IMAGING (Search)
   Echo Frame time: $acqrate s/frame
   Echo Binning: $binning
Endif

Echo Starting navigator item: $xtalct
Echo Number of targets: $nitems
Echo ================================================
Echo

YesNoBox Ready to start BatchED acquisition?
If $reportedValue1 == 0
   Exit User cancelled acquisition
Endif

SaveLogOpenNew $compoundname_BatchED_CETA
Echo
Echo Starting BatchED acquisition for CETA-M camera...
Echo
ReportDateTime

If $acq_mode == 1 AND $diff_type == 1
   MakeDirectory $set_directory\movies
   Echo Created subdirectory: movies
   Echo Dispatching to: BatchED_Rotation_CETA
   Call BatchED_Rotation_CETA
ElseIf $acq_mode == 1 AND $diff_type == 2
   MakeDirectory $set_directory\snapshots
   Echo Created subdirectory: snapshots
   Echo Dispatching to: BatchED_Still_CETA
   Call BatchED_Still_CETA
ElseIf $acq_mode == 1 AND $diff_type == 3
   MakeDirectory $set_directory\snapshots
   Echo Created subdirectory: snapshots
   Echo Dispatching to: BatchED_MultiAngle_CETA
   Call BatchED_MultiAngle_CETA
ElseIf $acq_mode == 2
   MakeDirectory $set_directory\imaging
   Echo Created subdirectory: imaging
   Echo Dispatching to: BatchED_Imaging_CETA
   Call BatchED_Imaging_CETA
Endif

Echo
Echo ================================================
Echo BATCHED ACQUISITION COMPLETE
Echo ================================================
Echo
Echo Processed $nitems targets
Echo
ReportDateTime
ReportClock

TiltTo 0
ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

Echo
Echo Scope returned to safe state
Echo - Tilt: 0 degrees
Echo - Screen: Down
Echo - Beam: Blanked
Echo - Column valve: Closed
Echo
Echo BatchED complete!

SaveLog
EndMacro
Macro	21
ScriptName BatchED_Rotation_CETA

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 1
SetExposure R $acqrate
SetBinning R $binning

nframes = $tiltrange / ($rotrate * $acqrate)
Echo Calculated frames to save: $nframes
Echo (Based on rotation rate $rotrate dps, frame time $acqrate s)

ReportCameraLength
dist := $reportedValue1 * 1000
Echo Talos camera length: $dist mm

If $dist == 840
   cetadist := 790
ElseIf $dist == 960
   cetadist := 960
Else
   Echo Warning: Unusual camera length detected
   cetadist := $dist
Endif
Echo CETA calibrated camera length: $cetadist mm

MakeDirectory movies
ReportDateTime
yyyymmdd := $reportedValue1
movnum = 20000

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1
      movnum = $movnum + 1

      movdir = $compoundname-mov$xtalct_$cetadistmm_$rotratedps_$acqratespf_$range_sp$spszg8_sweep$sweepcount_$temp
      MakeDirectory movies\$movdir

      movname = $compoundname-mov$xtalct_$cetadist_$rotrate_$acqrate_$range_g8sp$spsz_$temp.mrc

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Movie folder: $movdir
      Echo Movie name: $movname

      MoveToNavItem $xtalct
      Delay 1 sec

      TiltTo $startangle + 3
      TiltTo $startangle
      Delay 2 sec

      ReportTiltAngle
      Echo Starting tilt angle: $reportedValue1

      GoToLowDoseArea R

      UseContinuousFrames 1

      ReportStageXYZ
      Echo Stage position before tilt: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      OpenNewFile movies\$movdir\$yyyymmdd_$movnum_integrated_movie.mrc
      ReportCurrentFilename

      Echo STARTING TILT
      ReportClock

      Record

      StartFrameWaitTimer -1
      WaitForNextFrame
      Save

      BackgroundTilt $finalangle $rotincr

      Loop $nframes
         StartFrameWaitTimer -1
         WaitForNextFrame
         Save
      EndLoop

      StopContinuous
      CloseFile

      Echo END TILT
      Echo Movie folder: $movdir
      Echo Acquired movie: $movname
      ReportClock

      ReportStageXYZ
      Echo Stage position after tilt: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      TiltTo 0
      ReportTiltAngle
      Echo Returned to tilt: $reportedValue1

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

      Delay 5 sec

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	22
ScriptName BatchED_Still_CETA

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 0
SetExposure R $acqrate
SetBinning R $binning

ReportDateTime
yyyymmdd := $reportedValue1
snapnum = 30000

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1
      snapnum = $snapnum + 1

      MoveToNavItem $xtalct
      Delay 1 sec

      GoToLowDoseArea R

      ReportTiltAngle
      currentangle = $reportedValue1
      Echo Current tilt angle: $currentangle

      movdir = $compoundname-mov$xtalct_$cetadistmm_$acqratespf_sp$spsz_$currentangle_sweep$sweepcount_$temp
      MakeDirectory snapshots\$movdir

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Frame folder: $movdir

      ReportStageXYZ
      Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      Echo ACQUIRING SNAPSHOT
      ReportClock

      OpenNewFile snapshots\$movdir\$yyyymmdd_$snapnum_snapshot.mrc
      ReportCurrentFilename
      Record
      Save
      CloseFile

      Echo Frame folder: $movdir
      ReportClock

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

      Delay 2 sec

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	23
ScriptName BatchED_MultiAngle_CETA

angles = {60 30 0 -30 -60}
angleslabel = P60P30Z0N30N60

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous R 0
SetExposure R $acqrate
SetBinning R $binning

ReportDateTime
yyyymmdd := $reportedValue1
snapnum = 30000

Loop $nitems
   xtalct := $xtalct + 1
   sweepcount = 0

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   Loop $nsweeps
      sweepcount = $sweepcount + 1
      snapnum = $snapnum + 1

      MoveToNavItem $xtalct
      Delay 1 sec

      GoToLowDoseArea R

      movdir = $compoundname-mov$xtalct_$cetadistmm_$acqratespf_sp$spsz_$angleslabel_sweep$sweepcount_$temp
      MakeDirectory snapshots\$movdir

      Echo Sweep $sweepcount of $nsweeps for target $xtalct
      Echo Frame folder: $movdir
      Echo Collecting 5 angles: +60, +30, 0, -30, -60 degrees

      ReportStageXYZ
      Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

      OpenNewFile snapshots\$movdir\$yyyymmdd_$snapnum_multiangle.mrc
      ReportCurrentFilename

      Loop 5 idx
         tiltangle = $angles[$idx]

         Echo Tilting to $tiltangle degrees...
         TiltTo $tiltangle
         Delay 2 sec

         ReportTiltAngle
         Echo Acquiring snapshot at tilt angle: $reportedValue1
         ReportClock

         Record
         Save

         Echo Snapshot $idx of 5 complete (angle: $tiltangle)
      EndLoop

      CloseFile

      Echo Frame folder: $movdir
      ReportClock

      TiltTo 0
      ReportTiltAngle
      Echo Returned to tilt: $reportedValue1

      Echo Completed sweep $sweepcount for target $xtalct
      Echo

      Delay 5 sec

   EndLoop

   Echo Completed all sweeps for target $xtalct
   Echo

EndLoop
EndMacro
Macro	24
ScriptName BatchED_Imaging_CETA

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

SetContinuous S 0
SetExposure S $acqrate
SetBinning S $binning

ReportDateTime
yyyymmdd := $reportedValue1
imgnum = 40000

Loop $nitems
   xtalct := $xtalct + 1
   imgnum = $imgnum + 1

   Echo
   Echo ================================================
   Echo Processing target: $xtalct
   Echo ================================================

   MoveToNavItem $xtalct
   Delay 1 sec

   searchdir = $compoundname_item$xtalct
   MakeDirectory imaging\$searchdir

   Echo Frame folder: $searchdir

   GoToLowDoseArea S

   ReportStageXYZ
   Echo Stage position: X=$reportedValue1 Y=$reportedValue2 Z=$reportedValue3

   Echo ACQUIRING SEARCH IMAGE
   ReportClock

   OpenNewFile imaging\$searchdir\$yyyymmdd_$imgnum_search.mrc
   ReportCurrentFilename
   Search
   Save
   CloseFile

   Echo Frame folder: $searchdir
   ReportClock

   Echo Completed target: $xtalct
   Echo

   Delay 2 sec

EndLoop
EndMacro
Macro	25
MacroName REyes_STPSCN_Apollo

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

stpscn = _stepscan

log_stpscn_file_name = $samplename$stpscn$log_ext

DoesFileExist $log_stpscn_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$stpscn

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$stpscn

Endif

Echo Chosen directory: $set_directory
Echo Current sample: $samplename

stpscn_collected := 0
stpscn_set_aside := 0

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_open == 0
   Exit Could not locate Navigator.

Endif

ReportNumTableItems
nitems := $reportedValue1 - 1
Echo Current number of items: $nitems

posoffset = 1
posct = $posoffset
Echo Current position: $posct

imgnum = 10000

offset_x = 0
offset_y = 0

increment_x = 5 # microns
increment_y = 5 # microns

num_loopsx = $map_size # steps in x
num_loopsy =  $map_size # steps in y

half_loopsx = nearint ( $num_loopsx / 2)
half_loopsy = nearint ( $num_loopsy / 2 )

x_travel =  $num_loopsx * ( 0 - $increment_x)
y_travel = $num_loopsy * ( 0 - $increment_y)

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

stage_name @= STPSCN
IsVariableDefined spot_expected
If $reportedValue1 == 0
   stage_spot_expected := 0
Else
   stage_spot_expected := $spot_expected
Endif
Call REyes_SpotGuard
If $reyes_spot_ok == 0
   Echo StepScan abandoned by the spot guard -- see the reason above
   Return
Endif

SetContinuous R 0
frame_check = 1
stp_exp = 0.25
stp_fix_step = 0
n_multiframe = 0
SetExposure R $stp_exp
SetBinning R 4
SetFrameTime R $stp_exp
If $frame_check == 1
   stp_ft = $reportedValue1
   ReportExposure R
   Echo STPSCN_CAMERA | requested=$stp_exp | frame_time=$stp_ft | exposure=$reportedValue1
Endif

valve_check = 1
n_valve_lost = 0

shell_verify = 1

n_collected = 0
n_skipped = 0
n_set_aside = 0

IsVariableDefined stpscn_redo_all
If $reportedValue1 == 0
   EnterDefaultedNumber 0 -1 Resume mode: 0 = skip grid squares already mapped, 1 = redo all:
   stpscn_redo_all := $reportedValue1
Endif

inject_enabled = 0
inject_fail_square = 0
inject_valve_square = 0
If $inject_enabled == 1
   EnterDefaultedNumber 0 0 DRY RUN: grid square to FAIL with an error (0 = none, -1 = every square):
   inject_fail_square = $reportedValue1
   EnterDefaultedNumber 0 0 DRY RUN: grid square to report VALVE CLOSED (0 = none, -1 = every square):
   inject_valve_square = $reportedValue1
   Echo DRYRUN_INJECT | stage=STPSCN | fail_square=$inject_fail_square | valve_square=$inject_valve_square
Endif

Loop $nitems

   posname = $posct
   posct = $posct + 1

   sq_state = 0
   sq_valve = 0
   sq_phase @= resume_check

   Try
      DoesFileExist $set_directory\$samplename_$posname\stpscn_done.flag
      If $reportedValue1 == 1 AND $stpscn_redo_all == 0
         sq_state = 1
         n_skipped = $n_skipped + 1
         Echo RESUME | stage=STPSCN | square=$posname | action=skipped
         ChangeItemNote $posct REYES_DONE_STPSCN
      Endif

      If $sq_state == 0
         sq_phase @= open_log
         SaveLogOpenNew $samplename_$posname
         SetFolderForFrames $samplename_$posname

         sq_phase @= valve_reopen
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               Echo VALVE_REOPENED | stage=STPSCN | square=$posname
               SetColumnOrGunValve 1
               Delay 2 sec
            Endif
         Endif

         frame_checks_left = 3

         sq_phase @= move
         move_ok = 0
         Loop 5
            Loop 60
               ReportStageBusy
               If $reportedValue1 == 0
                  Break
               EndIf
               Delay 1 sec
            EndLoop
            Try
               MoveToNavItem $posct
               move_ok = 1
            Catch
               Echo STAGE_RETRY | the stage refused: MoveToNavItem $posct
               Echo STAGE_RETRY | waiting 20 s before trying again
               Delay 20 sec
            EndTry
            If $move_ok == 1
               Break
            EndIf
         EndLoop
         If $move_ok == 0
            Throw The stage stayed busy or not ready through 5 attempts: MoveToNavItem $posct
         EndIf

         ReportStageXYZ

         Delay 1 sec

         x_temp = $offset_x - ( $half_loopsx * $increment_x )
         y_temp = $offset_y - ( $half_loopsy * $increment_y )

         MoveStage $x_temp $y_temp

         sq_phase @= acquire
         sq_row = 0
         Loop $num_loopsy

            Delay 1 sec

            Loop $num_loopsx

               imgnum = $imgnum + 1
               MoveStage $increment_x 0

               Delay 1 sec

               Record
               ReportStageXYZ

               If $frame_check == 1 AND $frame_checks_left > 0
                  Try
                     ReportNumFramesSaved
                     stp_frames = $reportedValue1
                  Catch
                     stp_frames = -1
                  EndTry
                  If $stp_frames == 1
                     frame_checks_left = 0
                     Echo STPSCN_FRAMES | square=$posname | image=$imgnum | frames=1 | exposure=$stp_exp | action=none
                  ElseIf $stp_frames < 1
                     frame_checks_left = 0
                     Echo STPSCN_FRAMES | square=$posname | image=$imgnum | frames=unknown | exposure=$stp_exp | action=none
                  Else
                     n_multiframe = $n_multiframe + 1
                     stp_fix_step = $stp_fix_step + 1
                     frame_checks_left = $frame_checks_left - 1
                     stp_was = $stp_exp
                     If $stp_fix_step == 1
                        stp_exp = 0.25
                     ElseIf $stp_fix_step == 2
                        stp_exp = 0.26
                     ElseIf $stp_fix_step == 3
                        stp_exp = 0.24
                     Else
                        stp_exp = 0.25
                        frame_checks_left = 0
                     Endif
                     SetExposure R $stp_exp
                     SetFrameTime R $stp_exp
                     stp_ft = $reportedValue1
                     If $stp_fix_step <= 3
                        Echo STPSCN_FRAMES | square=$posname | image=$imgnum | frames=$stp_frames | exposure=$stp_was | action=repair_$stp_fix_step | next_exposure=$stp_exp | frame_time=$stp_ft
                     Else
                        Echo STPSCN_FRAMES | square=$posname | image=$imgnum | frames=$stp_frames | exposure=$stp_was | action=gave_up | next_exposure=$stp_exp | frame_time=$stp_ft
                        Echo WARNING: the Apollo is saving $stp_frames frames per exposure and no repair
                        Echo          changed that. Continuing at 0.25 s; dif-map-2 sums the stack.
                     Endif
                  Endif
               Endif

            EndLoop

            MoveStage (-1 * $num_loopsx * $increment_x ) $increment_y
            ReportClock

            sq_row = $sq_row + 1
            If $inject_enabled == 1 AND $sq_row == 1
               If $inject_fail_square == $posname OR $inject_fail_square < 0
                  Throw DRYRUN injected failure in grid square $posname
               Endif
            Endif

         EndLoop

         sq_phase @= valve_check
         stp_valve_ok = 1
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               stp_valve_ok = 0
            Endif
         Endif
         If $inject_enabled == 1
            If $inject_valve_square == $posname OR $inject_valve_square < 0
               stp_valve_ok = 0
            Endif
         Endif

         If $stp_valve_ok == 0
            sq_valve = 1
            sq_state = 3
         Else
            sq_phase @= copy
            RunInShell mkdir $set_directory\$samplename_$posname
            RunInShell copy D:\DEOutput\Apollo\$samplename_$posname $set_directory\$samplename_$posname
            If $shell_verify == 1 AND $reportedValue1 != 0
               Throw Error creating StepScan directory for grid square $posname
            Endif
            sq_phase @= done_flag
            MakeDirectory $set_directory\$samplename_$posname
            OpenTextFile STPDONE O 0 $set_directory\$samplename_$posname\stpscn_done.flag
            WriteLineToFile STPDONE done
            CloseTextFile STPDONE
            ChangeItemNote $posct REYES_DONE_STPSCN
            sq_state = 2
            n_collected = $n_collected + 1

            Echo Completed StepScan for current grid square
         Endif
      Endif
   Catch
      If $sq_state != 2 AND $sq_state != 1
         sq_state = 3
      Endif
   EndTry

   If $sq_state == 3
      n_set_aside = $n_set_aside + 1
      If $sq_valve == 1
         n_valve_lost = $n_valve_lost + 1
         sq_reason @= valve_closed
         sq_suffix @= -VALVECLOSED
         Echo VALVE_CLOSED | stage=STPSCN | square=$posname | action=not_copied_not_marked_done
         Echo WARNING: the column valve was closed when square $posname finished.
         Echo          Its frames are set aside; it will be mapped again on a resume.
      Else
         sq_reason @= error_$sq_phase
         sq_suffix @= -SKIPPED
         Echo WARNING: grid square $posname failed during $sq_phase and is set aside.
         Echo          The grid goes on; it will be mapped again on a resume.
      Endif
      Echo BLOCK_SKIPPED | stage=STPSCN | square=$posname | item=$posct | reason=$sq_reason
      Try
         RunInShell cmd /c ren D:\DEOutput\Apollo\$samplename_$posname $samplename_$posname$sq_suffix
      Catch
         Echo WARNING: could not rename the staging folder of grid square $posname
      EndTry
      Try
         SetColumnOrGunValve 1
         Delay 2 sec
      Catch
         Echo WARNING: could not re-open the column valve after grid square $posname
      EndTry
   Endif

   If $sq_state >= 2
      Try
         SaveNavigator
         SaveLog
      Catch
         Echo WARNING: could not save the navigator or the log after grid square $posname
      EndTry
   Endif

EndLoop

Echo STOPPING

ReportClock

Echo STPSCN_SUMMARY | squares=$nitems | collected=$n_collected | skipped=$n_skipped | set_aside=$n_set_aside
Echo STPSCN_CHECKS | multiframe_exposures=$n_multiframe | final_exposure=$stp_exp | valve_lost=$n_valve_lost

n_with_data = $n_collected + $n_skipped
If $nitems <= 0 OR $n_with_data == 0
   stp_result @= failed
ElseIf $n_set_aside > 0
   stp_result @= partial
Else
   stp_result @= complete
Endif
Echo STPSCN_RESULT | result=$stp_result | collected=$n_with_data | set_aside=$n_set_aside
stpscn_collected := $n_with_data
stpscn_set_aside := $n_set_aside

If $nitems <= 0 OR $n_with_data == 0
   Echo
   Echo ############################################################
   Echo # NOT reporting completion: NO grid square has data.
   Echo #   squares=$nitems  mapped=$n_collected  skipped=$n_skipped  set_aside=$n_set_aside
   Echo # Either the navigator held no grid squares, or every square
   Echo # failed. The grid is FAILED (All_blocks_failed). Re-run to map
   Echo # them again; squares already mapped are skipped.
   Echo ############################################################
   Echo
   ScreenDown
   SetBeamBlank 1
   SetColumnOrGunValve 0
   SaveNavigator
   SaveLog
   Return
Endif

If $n_set_aside > 0
   Echo $n_set_aside of $nitems grid square(s) set aside - the grid goes on with the other $n_with_data
Endif

Echo Completed StepScan for all grid squares

ReportDateTime

ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

SaveNavigator
SaveLog
EndMacro
Macro	26
MacroName REyes_STPSCN_CETA

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

stpscn = _stepscan

log_stpscn_file_name = $samplename$stpscn$log_ext

DoesFileExist $log_stpscn_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$stpscn

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$stpscn

Endif

Echo Chosen directory: $set_directory
Echo Current sample: $samplename

stpscn_collected := 0
stpscn_set_aside := 0

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_open == 0
   Exit Could not locate Navigator.

Endif

ReportNumTableItems
nitems := $reportedValue1 - 1
Echo Current number of items: $nitems

posoffset = 1
posct = $posoffset
Echo Current position: $posct

imgnum = 10000

offset_x = 0
offset_y = 0

increment_x = 5 # microns
increment_y = 5 # microns

num_loopsx = $map_size # steps in x
num_loopsy =  $map_size # steps in y

half_loopsx = nearint ( $num_loopsx / 2)
half_loopsy = nearint ( $num_loopsy / 2 )

x_travel =  $num_loopsx * ( 0 - $increment_x)
y_travel = $num_loopsy * ( 0 - $increment_y)

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

stage_name @= STPSCN
IsVariableDefined spot_expected
If $reportedValue1 == 0
   stage_spot_expected := 0
Else
   stage_spot_expected := $spot_expected
Endif
Call REyes_SpotGuard
If $reyes_spot_ok == 0
   Echo StepScan abandoned by the spot guard -- see the reason above
   Return
Endif

SetContinuous R 0
SetExposure R 1
SetBinning R 2

valve_check = 1
n_valve_lost = 0

n_collected = 0
n_skipped = 0
n_set_aside = 0

IsVariableDefined stpscn_redo_all
If $reportedValue1 == 0
   EnterDefaultedNumber 0 -1 Resume mode: 0 = skip grid squares already mapped, 1 = redo all:
   stpscn_redo_all := $reportedValue1
Endif

inject_enabled = 0
inject_fail_square = 0
inject_valve_square = 0
If $inject_enabled == 1
   EnterDefaultedNumber 0 0 DRY RUN: grid square to FAIL with an error (0 = none, -1 = every square):
   inject_fail_square = $reportedValue1
   EnterDefaultedNumber 0 0 DRY RUN: grid square to report VALVE CLOSED (0 = none, -1 = every square):
   inject_valve_square = $reportedValue1
   Echo DRYRUN_INJECT | stage=STPSCN | fail_square=$inject_fail_square | valve_square=$inject_valve_square
Endif

Loop $nitems

   posname = $posct
   posct = $posct + 1

   sq_state = 0
   sq_valve = 0
   sq_file_open = 0
   sq_phase @= resume_check

   Try
      DoesFileExist $set_directory\$samplename_$posname\stpscn_done.flag
      If $reportedValue1 == 1 AND $stpscn_redo_all == 0
         sq_state = 1
         n_skipped = $n_skipped + 1
         Echo RESUME | stage=STPSCN | square=$posname | action=skipped
         ChangeItemNote $posct REYES_DONE_STPSCN
      Endif

      If $sq_state == 0
         sq_phase @= open_log
         SaveLogOpenNew $samplename_$posname
         MakeDirectory $samplename_$posname

         sq_phase @= valve_reopen
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               Echo VALVE_REOPENED | stage=STPSCN | square=$posname
               SetColumnOrGunValve 1
               Delay 2 sec
            Endif
         Endif

         sq_phase @= move
         move_ok = 0
         Loop 5
            Loop 60
               ReportStageBusy
               If $reportedValue1 == 0
                  Break
               EndIf
               Delay 1 sec
            EndLoop
            Try
               MoveToNavItem $posct
               move_ok = 1
            Catch
               Echo STAGE_RETRY | the stage refused: MoveToNavItem $posct
               Echo STAGE_RETRY | waiting 20 s before trying again
               Delay 20 sec
            EndTry
            If $move_ok == 1
               Break
            EndIf
         EndLoop
         If $move_ok == 0
            Throw The stage stayed busy or not ready through 5 attempts: MoveToNavItem $posct
         EndIf

         ReportStageXYZ

         Delay 1 sec

         x_temp = $offset_x - ( $half_loopsx * $increment_x )
         y_temp = $offset_y - ( $half_loopsy * $increment_y )

         MoveStage $x_temp $y_temp

         sq_phase @= acquire
         sq_row = 0
         Loop $num_loopsy

            Delay 1 sec

            Loop $num_loopsx

               imgnum = $imgnum + 1
               MoveStage $increment_x 0

               Delay 1 sec

               sq_file_open = 1
               OpenNewFile $samplename_$posname\$yyyymmdd_$imgnum_integrated_movie$mrc_ext
               ReportCurrentFilename
               Record
               Save
               CloseFile
               ReportStageXYZ
               sq_file_open = 0

            EndLoop

            MoveStage (-1 * $num_loopsx * $increment_x ) $increment_y
            ReportClock

            sq_row = $sq_row + 1
            If $inject_enabled == 1 AND $sq_row == 1
               If $inject_fail_square == $posname OR $inject_fail_square < 0
                  Throw DRYRUN injected failure in grid square $posname
               Endif
            Endif

         EndLoop

         sq_phase @= valve_check
         stp_valve_ok = 1
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               stp_valve_ok = 0
            Endif
         Endif
         If $inject_enabled == 1
            If $inject_valve_square == $posname OR $inject_valve_square < 0
               stp_valve_ok = 0
            Endif
         Endif

         If $stp_valve_ok == 0
            sq_valve = 1
            sq_state = 3
         Else
            sq_phase @= done_flag
            OpenTextFile STPDONE O 0 $set_directory\$samplename_$posname\stpscn_done.flag
            WriteLineToFile STPDONE done
            CloseTextFile STPDONE
            ChangeItemNote $posct REYES_DONE_STPSCN
            sq_state = 2
            n_collected = $n_collected + 1

            Echo Completed StepScan for current grid square
         Endif
      Endif
   Catch
      If $sq_state != 2 AND $sq_state != 1
         sq_state = 3
      Endif
   EndTry

   If $sq_state == 3
      n_set_aside = $n_set_aside + 1
      If $sq_valve == 1
         n_valve_lost = $n_valve_lost + 1
         sq_reason @= valve_closed
         sq_suffix @= -VALVECLOSED
         Echo VALVE_CLOSED | stage=STPSCN | square=$posname | action=not_marked_done
         Echo WARNING: the column valve was closed when square $posname finished.
         Echo          Its patterns are set aside; it will be mapped again on a resume.
      Else
         sq_reason @= error_$sq_phase
         sq_suffix @= -SKIPPED
         Echo WARNING: grid square $posname failed during $sq_phase and is set aside.
         Echo          The grid goes on; it will be mapped again on a resume.
      Endif
      Echo BLOCK_SKIPPED | stage=STPSCN | square=$posname | item=$posct | reason=$sq_reason
      If $sq_file_open == 1
         Try
            CloseFile
         Catch
            Echo WARNING: could not close the open image file of grid square $posname
         EndTry
      Endif
      Try
         RunInShell cmd /c ren "$set_directory\$samplename_$posname" "$samplename_$posname$sq_suffix"
      Catch
         Echo WARNING: could not rename the folder of grid square $posname
      EndTry
      Try
         SetColumnOrGunValve 1
         Delay 2 sec
      Catch
         Echo WARNING: could not re-open the column valve after grid square $posname
      EndTry
   Endif

   If $sq_state >= 2
      Try
         SaveNavigator
         SaveLog
      Catch
         Echo WARNING: could not save the navigator or the log after grid square $posname
      EndTry
   Endif

EndLoop

Echo STOPPING

ReportClock

Echo STPSCN_SUMMARY | squares=$nitems | collected=$n_collected | skipped=$n_skipped | set_aside=$n_set_aside
Echo STPSCN_CHECKS | camera=CETA | exposure=1 | binning=2 | valve_lost=$n_valve_lost

n_with_data = $n_collected + $n_skipped
If $nitems <= 0 OR $n_with_data == 0
   stp_result @= failed
ElseIf $n_set_aside > 0
   stp_result @= partial
Else
   stp_result @= complete
Endif
Echo STPSCN_RESULT | result=$stp_result | collected=$n_with_data | set_aside=$n_set_aside
stpscn_collected := $n_with_data
stpscn_set_aside := $n_set_aside

If $nitems <= 0 OR $n_with_data == 0
   Echo
   Echo ############################################################
   Echo # NOT reporting completion: NO grid square has data.
   Echo #   squares=$nitems  mapped=$n_collected  skipped=$n_skipped  set_aside=$n_set_aside
   Echo # Either the navigator held no grid squares, or every square
   Echo # failed. The grid is FAILED (All_blocks_failed). Re-run to map
   Echo # them again; squares already mapped are skipped.
   Echo ############################################################
   Echo
   ScreenDown
   SetBeamBlank 1
   SetColumnOrGunValve 0
   SaveNavigator
   SaveLog
   Return
Endif

If $n_set_aside > 0
   Echo $n_set_aside of $nitems grid square(s) set aside - the grid goes on with the other $n_with_data
Endif

Echo Completed StepScan for all grid squares

ReportDateTime

ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

SaveNavigator
SaveLog
EndMacro
Macro	27
MacroName REyes_DFMV_Apollo

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

trgts = _targets
targets_file_name = targets\targets$nav_ext
log_dfmv_file_name = $samplename$trgts$log_ext

DoesFileExist $log_dfmv_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$trgts

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$trgts

Endif

Echo Chosen directory: $set_directory
Echo Current sample: $samplename

dfmv_set_aside := 0

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_open == 0
   Exit Could not locate Navigator.

Endif

   ReportNumTableItems

   nsqrs = $reportedValue1

   Echo Current number of items: $nsqrs

   DoesFileExist $targets_file_name
   targets_file_exists = $reportedValue1

   If $targets_file_exists == 1
      MergeNavFile $targets_file_name

   ElseIf $targets_file_exists == 0
      Exit $targets_file_name was not found

   Endif

   ReportNumTableItems

   all_items = $reportedValue1

   Echo Total number of items with targets: $all_items

   nitems := $all_items - $nsqrs

   Echo Current number of crystal targets: $nitems

   If $nitems > 0
      dfmv_rng_first = $nsqrs + 1
      MakeDirectory targets
      OpenTextFile DFMVRNG O 0 targets\range_dfmv.txt
      WriteLineToFile DFMVRNG $dfmv_rng_first $all_items
      CloseTextFile DFMVRNG
      Echo DFMV_RANGE | first_item=$dfmv_rng_first | last_item=$all_items | source=merge
   Else
      OpenTextFile DFMVRNG T 0 targets\range_dfmv.txt
      If $reportedValue1 == 1
         ReadLineToArray DFMVRNG dfmv_rng
         dfmv_rng_read = $reportedValue1
         CloseTextFile DFMVRNG
         If $dfmv_rng_read == 1
            nsqrs = $dfmv_rng[1] - 1
            nitems := $dfmv_rng[2] - $dfmv_rng[1] + 1
            Echo DFMV_RANGE | first_item=$dfmv_rng[1] | last_item=$dfmv_rng[2] | source=file
            Echo The targets were merged by an earlier run - resuming on the same block
            Echo Current number of crystal targets: $nitems
         Endif
      Endif
   Endif

If $nitems <= 0
   Echo
   Echo ############################################################
   Echo # STOPPING: NO NEW TARGETS WERE MERGED
   Echo #
   Echo # $targets_file_name added 0 items, which means this navigator
   Echo # already contains them -- almost always a re-run after a pause --
   Echo # and targets\range_dfmv.txt, which records the block an earlier
   Echo # merge added, was not found either.
   Echo #
   Echo # NOTHING HAS BEEN COLLECTED. Choose one:
   Echo #   - to resume, delete the merged target items from the navigator
   Echo #     and run again: crystals whose folder carries dfmv_done.flag
   Echo #     are skipped
   Echo #   - to start over, do the same and answer 1 to "redo all"
   Echo ############################################################
   Echo
   Exit No new targets merged - nothing collected, see the log
Endif

offset = $nsqrs

Echo Offset: $offset

xtalct := $offset

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

stage_name @= DFMV
IsVariableDefined dfmv_spot_expected
If $reportedValue1 == 1
   stage_spot_expected := $dfmv_spot_expected
Else
   IsVariableDefined spot_expected
   If $reportedValue1 == 1
      stage_spot_expected := $spot_expected
   Else
      stage_spot_expected := 0
   Endif
Endif
Call REyes_SpotGuard
If $reyes_spot_ok == 0
   Echo Movie collection abandoned by the spot guard -- see the reason above
   Return
Endif

Echo DFMV will write movie folders named $samplename-mov<n>_...

startangle := $selected_tilt
finalangle := -$selected_tilt
range := P$startangletoN$finalangle
tiltrange := $selected_tilt * 2
nsweeps := 1
spsz := $reyes_spot_actual

rotrate_default = 1
acqrate_default = 1

IsVariableDefined dfmv_rotrate
If $reportedValue1 == 0
   EnterDefaultedNumber $rotrate_default 2 Rotation rate in deg/s:
   dfmv_rotrate := $reportedValue1
Endif
IsVariableDefined dfmv_acqrate
If $reportedValue1 == 0
   EnterDefaultedNumber $acqrate_default 2 Frame time in s (rotrate x frametime should be 1 deg):
   dfmv_acqrate := $reportedValue1
Endif

IsVariableDefined dfmv_write_settle
If $reportedValue1 == 0
   dfmv_write_settle := 5
Endif
IsVariableDefined dfmv_tail_settle
If $reportedValue1 == 0
   dfmv_tail_settle := 20
Endif

rotrate := $dfmv_rotrate
acqrate := $dfmv_acqrate
rotincr := 0.033 * $rotrate
deg_per_frame = $rotrate * $acqrate

Echo DFMV_ROTATION | rotrate=$rotrate | rotincr=$rotincr | acqrate=$acqrate | deg_per_frame=$deg_per_frame

If $deg_per_frame > 1.05 OR $deg_per_frame < 0.95
   Echo
   Echo WARNING: rotrate x frametime = $deg_per_frame deg per frame, not 1.
   Echo Angular sampling differs from every previous dataset, which changes
   Echo how the movies integrate. Continue only if this is intended.
   Echo
Endif

ReportCameraLength
dist := $reportedValue1 * 1000
temp := c #c for cryo or rt for room temp
recordtime := $tiltrange / $rotrate

If $dist == 420
   apollodist := 560
ElseIf $dist == 960
   apollodist := 1280
Else
   apollodist := $dist
   Echo
   Echo WARNING: camera length $dist mm has no calibrated Apollo equivalent.
   Echo   Known pairs are 420 -> 560 and 960 -> 1280. Falling back to the
   Echo   nominal value, so movie FILENAMES will carry $dist rather than a
   Echo   calibrated length. The data are unaffected; the names are not.
   Echo   A value of 0 means the column is not in diffraction mode.
   Echo
Endif

Echo Talos camera length is $dist
Echo Apollo camera length is $apollodist

SetContinuous R 1
SetExposure R $recordtime
SetBinning R 4
SetFrameTime R $acqrate

ReportExposure R
expsr = $acqrate

movtime = ($startangle - $finalangle) / $rotrate
nframes = ($startangle - $finalangle) / ($rotrate * $expsr)

MakeDirectory movies
Delay 2 sec

shell_verify = 1

n_collected = 0
n_skipped = 0

valve_check = 1
n_valve_lost = 0
n_set_aside = 0

IsVariableDefined dfmv_redo_all
If $reportedValue1 == 0
   EnterDefaultedNumber 0 -1 Resume mode: 0 = skip crystals already collected, 1 = redo all:
   dfmv_redo_all := $reportedValue1
Endif

inject_enabled = 0
inject_fail_item = 0
If $inject_enabled == 1
   EnterDefaultedNumber 0 0 DRY RUN: movie (crystal) to FAIL, counted from 1 in the block (0 = none, -1 = every crystal):
   inject_fail_item = $reportedValue1
   Echo DRYRUN_INJECT | stage=DFMV | fail_item=$inject_fail_item
Endif

Loop $nitems
   xtalct := $xtalct + 1
   sweepcnt = 1
   movdir = $samplename_mov$xtalct_$distmm_$rotratedps_$acqratespf_sp$spsz_$range_sweep$sweepcnt_$temp
   movname = $samplename-mov$xtalct_$apollodist_$rotrate_$expsr_$range_g8sp$spsz_$temp$mrc_ext
   item_state = 0
   item_valve = 0
   item_phase @= resume_check
   dfmv_valve_ok = 1

   Try
      DoesFileExist $set_directory\movies\$movdir\dfmv_done.flag
      If $reportedValue1 == 1 AND $dfmv_redo_all == 0
         item_state = 1
         n_skipped = $n_skipped + 1
         Echo RESUME | stage=DFMV | item=$xtalct | action=skipped | folder=$movdir
         SaveLog
      Endif

      If $item_state == 0
         item_phase @= valve_reopen
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               Echo VALVE_REOPENED | stage=DFMV | item=$xtalct
               SetColumnOrGunValve 1
               Delay 2 sec
            Endif
         Endif

         SetFolderForFrames $movdir
         item_phase @= move
         move_ok = 0
         Loop 5
            Loop 60
               ReportStageBusy
               If $reportedValue1 == 0
                  Break
               EndIf
               Delay 1 sec
            EndLoop
            Try
               MoveToNavItem $xtalct
               move_ok = 1
            Catch
               Echo STAGE_RETRY | the stage refused: MoveToNavItem $xtalct
               Echo STAGE_RETRY | waiting 20 s before trying again
               Delay 20 sec
            EndTry
            If $move_ok == 1
               Break
            EndIf
         EndLoop
         If $move_ok == 0
            Throw The stage stayed busy or not ready through 5 attempts: MoveToNavItem $xtalct
         EndIf

         Loop $nsweeps
            sweepcnt = $sweepcnt + 1
            item_phase @= tilt
            pretilt = $startangle + 3
            TiltTo $pretilt
            TiltTo $startangle
            Delay 1 sec
            ReportTiltAngle
            GoToLowDoseArea R
            UseContinuousFrames 1
            echo STARTING TILT
            item_phase @= acquire
            BackgroundTilt $finalangle $rotincr

            Record

            StopContinuous

            echo END TILT

            If $inject_enabled == 1
               inject_pos = $xtalct - $offset
               If $inject_fail_item == $inject_pos OR $inject_fail_item < 0
                  Throw DRYRUN injected failure in movie item $xtalct
               Endif
            Endif

            item_phase @= valve_check
            If $valve_check == 1
               ReportColumnOrGunValve
               If $reportedValue1 != 1
                  dfmv_valve_ok = 0
               Endif
            Endif
            If $dfmv_valve_ok == 1
               echo Movie folder: $movdir
               echo Acquired movie: $movname
               item_phase @= copy
               ReportClock t_ws_start
               Delay $dfmv_write_settle sec
               ReportClock t_ws_done
               TiltTo 0
               ReportClock
               ReportStageXYZ
               Delay 1 sec
               ReportClock t_copy_start
               RunInShell mkdir $set_directory\movies\$movdir
               RunInShell copy D:\DEOutput\Apollo\$movdir $set_directory\movies\$movdir
               If $shell_verify == 1 AND $reportedValue1 != 0
                  Throw Error creating movies directory for $movdir
               Endif
               ReportClock t_copy_done
               t_ws_actual = $t_ws_done - $t_ws_start
               t_copy_actual = $t_copy_done - $t_copy_start
               Echo DFMV_TIMING | movie=$movname | write_settle_req=$dfmv_write_settle | write_settle_act=$t_ws_actual | t_copy=$t_copy_actual | nframes=$nframes

               item_phase @= done_flag
               MakeDirectory $set_directory\movies\$movdir
               OpenTextFile DFMVDONE O 0 $set_directory\movies\$movdir\dfmv_done.flag
               WriteLineToFile DFMVDONE done
               CloseTextFile DFMVDONE
               ChangeItemNote $xtalct REYES_DONE_DFMV
               If $item_state != 2
                  item_state = 2
                  n_collected = $n_collected + 1
               Endif
               Echo Completed movie acquisition
               SaveLog
            Endif
         EndLoop

         If $dfmv_valve_ok == 0
            item_valve = 1
            item_state = 3
         Else
            Echo RESUME | stage=DFMV | item=$xtalct | action=collected | folder=$movdir
         Endif
      Endif
   Catch
      If $item_state != 2 AND $item_state != 1
         item_state = 3
      Endif
   EndTry

   If $item_state == 3
      n_set_aside = $n_set_aside + 1
      If $item_valve == 1
         n_valve_lost = $n_valve_lost + 1
         item_reason @= valve_closed
         item_suffix @= -VALVECLOSED
         Echo VALVE_CLOSED | stage=DFMV | item=$xtalct | folder=$movdir | action=not_copied_not_marked_done
         Echo WARNING: the column valve was closed when this movie finished.
         Echo          Its frames are set aside; it will be collected again on a resume.
      Else
         item_reason @= error_$item_phase
         item_suffix @= -SKIPPED
         Echo WARNING: crystal $xtalct failed during $item_phase and is set aside.
         Echo          Movie collection goes on; it will be collected again on a resume.
         Try
            StopContinuous
         Catch
            Echo WARNING: StopContinuous failed after crystal $xtalct
         EndTry
      Endif
      Echo ITEM_SKIPPED | stage=DFMV | item=$xtalct | reason=$item_reason
      Try
         TiltTo 0
      Catch
         Echo WARNING: could not tilt back to 0 after crystal $xtalct
      EndTry
      Try
         RunInShell cmd /c ren D:\DEOutput\Apollo\$movdir $movdir$item_suffix
      Catch
         Echo WARNING: could not rename the staging folder of crystal $xtalct
      EndTry
      Try
         SetColumnOrGunValve 1
         Delay 2 sec
      Catch
         Echo WARNING: could not re-open the column valve after crystal $xtalct
      EndTry
   Endif

   If $item_state >= 2
      Try
         SaveNavigator
         SaveLog
      Catch
         Echo WARNING: could not save the navigator or the log after crystal $xtalct
      EndTry
   Endif
EndLoop

Echo STOPPING

Delay $dfmv_tail_settle sec
ReportClock

Echo DFMV_SUMMARY | targets=$nitems | collected=$n_collected | skipped=$n_skipped | set_aside=$n_set_aside
Echo DFMV_CHECKS | valve_lost=$n_valve_lost
dfmv_set_aside := $n_set_aside

accounted = $n_collected + $n_skipped
If $n_set_aside > 0
   Echo $n_set_aside of $nitems crystal(s) set aside - $accounted have movies
Endif

Echo Completed acquiring tilt movies for all crystals!

ReportDateTime

ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

SaveNavigator
SaveLog

If $accounted == 0
   Exit DFMV collected nothing - all $nitems crystals were set aside
Endif
EndMacro
Macro	28
MacroName REyes_DFMV_CETA

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

trgts = _targets
targets_file_name = targets\targets$nav_ext
log_dfmv_file_name = $samplename$trgts$log_ext

DoesFileExist $log_dfmv_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$trgts

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$trgts

Endif

Echo Chosen directory: $set_directory
Echo Current sample: $samplename

dfmv_set_aside := 0

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_open == 0
   Exit Could not locate Navigator.

Endif

ReportNumTableItems

nsqrs = $reportedValue1

Echo Current number of items: $nsqrs

DoesFileExist $targets_file_name
targets_file_exists = $reportedValue1

If $targets_file_exists == 1
   MergeNavFile $targets_file_name

ElseIf $targets_file_exists == 0
   Exit $targets_file_name was not found

Endif

ReportNumTableItems

all_items = $reportedValue1

Echo Total number of items with targets: $all_items

nitems := $all_items - $nsqrs

Echo Current number of crystal targets: $nitems

If $nitems > 0
   dfmv_rng_first = $nsqrs + 1
   MakeDirectory targets
   OpenTextFile DFMVRNG O 0 targets\range_dfmv.txt
   WriteLineToFile DFMVRNG $dfmv_rng_first $all_items
   CloseTextFile DFMVRNG
   Echo DFMV_RANGE | first_item=$dfmv_rng_first | last_item=$all_items | source=merge
Else
   OpenTextFile DFMVRNG T 0 targets\range_dfmv.txt
   If $reportedValue1 == 1
      ReadLineToArray DFMVRNG dfmv_rng
      dfmv_rng_read = $reportedValue1
      CloseTextFile DFMVRNG
      If $dfmv_rng_read == 1
         nsqrs = $dfmv_rng[1] - 1
         nitems := $dfmv_rng[2] - $dfmv_rng[1] + 1
         Echo DFMV_RANGE | first_item=$dfmv_rng[1] | last_item=$dfmv_rng[2] | source=file
         Echo The targets were merged by an earlier run - resuming on the same block
         Echo Current number of crystal targets: $nitems
      Endif
   Endif
Endif

If $nitems <= 0
   Echo
   Echo ############################################################
   Echo # STOPPING: NO NEW TARGETS WERE MERGED
   Echo #
   Echo # $targets_file_name added 0 items, which means this navigator
   Echo # already contains them -- almost always a re-run after a pause --
   Echo # and targets\range_dfmv.txt, which records the block an earlier
   Echo # merge added, was not found either.
   Echo #
   Echo # NOTHING HAS BEEN COLLECTED. Choose one:
   Echo #   - to resume, delete the merged target items from the navigator
   Echo #     and run again: crystals whose folder carries dfmv_done.flag
   Echo #     are skipped
   Echo #   - to start over, do the same and answer 1 to "redo all"
   Echo ############################################################
   Echo
   Exit No new targets merged - nothing collected, see the log
Endif

offset = $nsqrs

Echo Offset: $offset

xtalct := $offset

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

stage_name @= DFMV
IsVariableDefined dfmv_spot_expected
If $reportedValue1 == 1
   stage_spot_expected := $dfmv_spot_expected
Else
   IsVariableDefined spot_expected
   If $reportedValue1 == 1
      stage_spot_expected := $spot_expected
   Else
      stage_spot_expected := 0
   Endif
Endif
Call REyes_SpotGuard
If $reyes_spot_ok == 0
   Echo Movie collection abandoned by the spot guard -- see the reason above
   Return
Endif

startangle := $selected_tilt
finalangle := -$selected_tilt
range := P$startangletoN$finalangle
tiltrange := $selected_tilt * 2
nsweeps := 1
spsz := $reyes_spot_actual
IsVariableDefined dfmv_rotrate
If $reportedValue1 == 0
   EnterDefaultedNumber 0.12 2 Stage rotation rate in deg/s (0.12 = apparent 0.3 deg/s):
   dfmv_rotrate := $reportedValue1
Endif
IsVariableDefined dfmv_acqrate
If $reportedValue1 == 0
   EnterDefaultedNumber 3 1 Exposure per frame in s (3 = calibrated):
   dfmv_acqrate := $reportedValue1
Endif
stage_rate = $dfmv_rotrate
rotincr := $stage_rate / 30
ceta_readout = 4.4
ReportCameraLength
dist := $reportedValue1 * 1000
temp := c #c for cryo or rt for room temp

Echo Talos camera length is $dist

SetContinuous R 1
SetExposure R $dfmv_acqrate
SetBinning R 2

ReportExposure R
expsr = $reportedValue1

If $stage_rate == 0.12 AND $dfmv_acqrate == 3
   rot_calibrated = 1
   rotrate := 0.3
   acqrate := 0.33
Else
   rot_calibrated = 0
   rotrate := $stage_rate * ($expsr + $ceta_readout) / $expsr
   acqrate := 1 / $expsr
Endif
deg_per_frame = $stage_rate * ($expsr + $ceta_readout)
deg_exposed = $stage_rate * $expsr

movtime = ($startangle - $finalangle) / $rotrate
nframes = ($startangle - $finalangle) / ($rotrate * $expsr)

Echo DFMV_ROTATION | camera=CETA | rotrate_apparent=$rotrate | stage_rate=$stage_rate | rotincr=$rotincr | frame_exposure=$expsr | nframes=$nframes | deg_per_frame=$deg_per_frame | deg_exposed=$deg_exposed | calibrated=$rot_calibrated
If $rot_calibrated == 0
   Echo ROTATION_UNCALIBRATED | stage_rate=$stage_rate | exposure=$expsr | apparent_rate=$rotrate | readout_assumed=$ceta_readout
   Echo WARNING: only 0.12 deg/s with 3 s frames has been calibrated and tested on the
   Echo   Ceta-D. The apparent rate in the movie names assumes the same 4.4 s readout;
   Echo   check the oscillation autoprocess uses for these movies.
Endif

MakeDirectory movies
movnum = 20000
Delay 2 sec

n_collected = 0
n_skipped = 0
n_set_aside = 0

valve_check = 1
n_valve_lost = 0

IsVariableDefined dfmv_redo_all
If $reportedValue1 == 0
   EnterDefaultedNumber 0 -1 Resume mode: 0 = skip crystals already collected, 1 = redo all:
   dfmv_redo_all := $reportedValue1
Endif

inject_enabled = 0
inject_fail_item = 0
If $inject_enabled == 1
   EnterDefaultedNumber 0 0 DRY RUN: movie (crystal) to FAIL, counted from 1 in the block (0 = none, -1 = every crystal):
   inject_fail_item = $reportedValue1
   Echo DRYRUN_INJECT | stage=DFMV | fail_item=$inject_fail_item
Endif

Loop $nitems
   xtalct := $xtalct + 1
   movnum = $movnum + 1
   sweepcnt = 1
   movdir = $samplename_$distmm_sp$spsz_$rotratedps_$acqratefps_$range_mov$xtalct_sweep$sweepcnt_$temp
   movname = $samplename-mov$xtalct_$dist_$rotrate_$expsr_$range_g8sp$spsz_$temp$mrc_ext
   item_state = 0
   item_valve = 0
   item_streaming = 0
   item_file_open = 0
   item_phase @= resume_check
   dfmv_valve_ok = 1

   Try
      DoesFileExist $set_directory\movies\$movdir\dfmv_done.flag
      If $reportedValue1 == 1 AND $dfmv_redo_all == 0
         item_state = 1
         n_skipped = $n_skipped + 1
         Echo RESUME | stage=DFMV | item=$xtalct | action=skipped | folder=$movdir
         SaveLog
      Endif

      If $item_state == 0
         item_phase @= valve_reopen
         If $valve_check == 1
            ReportColumnOrGunValve
            If $reportedValue1 != 1
               Echo VALVE_REOPENED | stage=DFMV | item=$xtalct
               SetColumnOrGunValve 1
               Delay 2 sec
            Endif
         Endif

         MakeDirectory movies\$movdir
         item_phase @= move
         move_ok = 0
         Loop 5
            Loop 60
               ReportStageBusy
               If $reportedValue1 == 0
                  Break
               EndIf
               Delay 1 sec
            EndLoop
            Try
               MoveToNavItem $xtalct
               move_ok = 1
            Catch
               Echo STAGE_RETRY | the stage refused: MoveToNavItem $xtalct
               Echo STAGE_RETRY | waiting 20 s before trying again
               Delay 20 sec
            EndTry
            If $move_ok == 1
               Break
            EndIf
         EndLoop
         If $move_ok == 0
            Throw The stage stayed busy or not ready through 5 attempts: MoveToNavItem $xtalct
         EndIf

         Loop $nsweeps
            sweepcnt = $sweepcnt + 1
            item_phase @= tilt
            TiltTo $startangle
            Delay 1 sec
            ReportTiltAngle
            GoToLowDoseArea R
            UseContinuousFrames 1

            item_phase @= acquire
            item_file_open = 1
            OpenNewFile movies\$movdir\$yyyymmdd_$movnum_integrated_movie$mrc_ext
            ReportCurrentFilename
            item_streaming = 1
            Record
            StartFrameWaitTimer -1
            WaitForNextFrame
            Save
            echo STARTING TILT
            BackgroundTilt $finalangle $rotincr

            Loop $nframes
               StartFrameWaitTimer -1
               WaitForNextFrame
               Save
            EndLoop

            StopContinuous
            item_streaming = 0
            CloseFile
            item_file_open = 0

            echo END TILT

            If $inject_enabled == 1
               inject_pos = $xtalct - $offset
               If $inject_fail_item == $inject_pos OR $inject_fail_item < 0
                  Throw DRYRUN injected failure in movie item $xtalct
               Endif
            Endif

            item_phase @= valve_check
            If $valve_check == 1
               ReportColumnOrGunValve
               If $reportedValue1 != 1
                  dfmv_valve_ok = 0
               Endif
            Endif
            If $dfmv_valve_ok == 1
               echo Movie folder: $movdir
               echo Acquired movie: $movname
               item_phase @= settle
               Delay 120 sec
               TiltTo 0
               ReportClock
               ReportStageXYZ
               Delay 2 sec

               item_phase @= done_flag
               OpenTextFile DFMVDONE O 0 $set_directory\movies\$movdir\dfmv_done.flag
               WriteLineToFile DFMVDONE done
               CloseTextFile DFMVDONE
               ChangeItemNote $xtalct REYES_DONE_DFMV
               If $item_state != 2
                  item_state = 2
                  n_collected = $n_collected + 1
               Endif
               Echo Completed movie acquisition
               SaveLog
            Endif
         EndLoop

         If $dfmv_valve_ok == 0
            item_valve = 1
            item_state = 3
         Else
            Echo RESUME | stage=DFMV | item=$xtalct | action=collected | folder=$movdir
         Endif
      Endif
   Catch
      If $item_state != 2 AND $item_state != 1
         item_state = 3
      Endif
   EndTry

   If $item_state == 3
      n_set_aside = $n_set_aside + 1
      If $item_valve == 1
         n_valve_lost = $n_valve_lost + 1
         item_reason @= valve_closed
         item_suffix @= -VALVECLOSED
         Echo VALVE_CLOSED | stage=DFMV | item=$xtalct | folder=$movdir | action=not_marked_done
         Echo WARNING: the column valve was closed when this movie finished.
         Echo          Its frames are set aside; it will be collected again on a resume.
      Else
         item_reason @= error_$item_phase
         item_suffix @= -SKIPPED
         Echo WARNING: crystal $xtalct failed during $item_phase and is set aside.
         Echo          Movie collection goes on; it will be collected again on a resume.
      Endif
      Echo ITEM_SKIPPED | stage=DFMV | item=$xtalct | reason=$item_reason
      If $item_streaming == 1
         Try
            StopContinuous
         Catch
            Echo WARNING: StopContinuous failed after crystal $xtalct
         EndTry
      Endif
      If $item_file_open == 1
         Try
            CloseFile
         Catch
            Echo WARNING: could not close the movie file of crystal $xtalct
         EndTry
      Endif
      Try
         TiltTo 0
      Catch
         Echo WARNING: could not tilt back to 0 after crystal $xtalct
      EndTry
      Try
         RunInShell cmd /c ren "$set_directory\movies\$movdir" "$movdir$item_suffix"
      Catch
         Echo WARNING: could not rename the movie folder of crystal $xtalct
      EndTry
      Try
         SetColumnOrGunValve 1
         Delay 2 sec
      Catch
         Echo WARNING: could not re-open the column valve after crystal $xtalct
      EndTry
   Endif

   If $item_state >= 2
      Try
         SaveNavigator
         SaveLog
      Catch
         Echo WARNING: could not save the navigator or the log after crystal $xtalct
      EndTry
   Endif
EndLoop

Echo STOPPING

Delay 900 sec
ReportClock

Echo DFMV_SUMMARY | targets=$nitems | collected=$n_collected | skipped=$n_skipped | set_aside=$n_set_aside
Echo DFMV_CHECKS | valve_lost=$n_valve_lost
dfmv_set_aside := $n_set_aside

accounted = $n_collected + $n_skipped
If $n_set_aside > 0
   Echo $n_set_aside of $nitems crystal(s) set aside - $accounted have movies
Endif

Echo Completed acquiring tilt movies for all crystals!

ReportDateTime

ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

SaveNavigator
SaveLog

If $accounted == 0
   Exit DFMV collected nothing - all $nitems crystals were set aside
Endif
EndMacro
Macro	30
MacroName REyes_MNT
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

If $reyes_detector == 1
   montage = _115LM_$mnt_sizex$mnt_size
ElseIf $reyes_detector == 2
   montage = _210LM_$mnt_sizex$mnt_size
Endif
navigator = _nav

log_file_name = $samplename$montage$log_ext
nav_file_name := $samplename$montage$navigator$nav_ext
mnt_file_name = $samplename$montage$mrc_ext
mdoc_file_name = $mnt_file_name$mdoc_ext

DoesFileExist $log_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$montage

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$montage

Endif

Echo Chosen directory: $set_directory
Echo Sample name: $samplename
Echo Montage size: $mnt_size

DoesFileExist $nav_file_name
nav_file_exists = $reportedValue1

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_exists == 0 and $nav_file_open == 0
   OpenNavigator $samplename$montage$navigator$nav_ext

ElseIf $nav_file_exists == 1 and $nav_file_open == 0
   ReadNavFile $nav_file_name

ElseIf $nav_file_exists == 0 and $nav_file_open == 1
   SaveNavigator $samplename$montage$navigator$nav_ext

Endif

SetNewFileType 0

DoesFileExist $mnt_file_name
If $reportedValue1 == 0

   SetColumnOrGunValve 1
   ScreenUp
   SetBeamBlank 0

   Eucentricity 1
   ReportStageXYZ
   z_value_rough = $reportedValue3

   If $reyes_detector == 2
      SetLowDoseMode 1
   Endif
   OpenNewMontage $mnt_size $mnt_size $mnt_file_name

   If $reyes_detector == 1
      Echo Starting 115x LM montage collection
   ElseIf $reyes_detector == 2
      Echo Starting 210x LM montage collection
   Endif
   ReportDateTime
   ReportNumMontagePieces

   SetColumnOrGunValve 1
   TiltTo 0
   MoveStageTo 0 0 $z_value_rough

   Delay 1 sec

   SetContinuous M 0
   If $reyes_detector == 1
      SetExposure M 1
      SetBinning M 4
   ElseIf $reyes_detector == 2
      SetExposure M 3
      SetBinning M 2
   Endif

   M
   NewMap

   ScreenDown

   SetBeamBlank 1
   SetColumnOrGunValve 0

   If $reyes_detector == 1
      Echo Completed 115x LM montage data collection
   ElseIf $reyes_detector == 2
      Echo Completed 210x LM montage data collection
   Endif
   ReportDateTime

ElseIf $reportedValue1 == 1
   Echo You have already acquired grid montage

Endif

DoesFileExist $mdoc_file_name
mdoc_file_exists = $reportedValue1

If $mdoc_file_exists == 0
   Echo .mdoc file for montage was not found. Please check settings.
ElseIf $mdoc_file_exists == 1
   Echo .mdoc file for montage has been saved successfully.
Endif

SaveNavigator
SaveLog
EndMacro
Macro	31
MacroName REyes_ECNT
IsVariableDefined reyes_detector
If $reportedValue1 == 0
   Echo
   Echo Which detector is this microscope using?
   Echo   1 = DE Apollo   (REyes --microscope Arctica-Apollo-SM)
   Echo   2 = Ceta-D      (REyes --microscope Arctica-CETA)
   EnterOneNumber Detector (1 DE Apollo, 2 Ceta-D):
   If $reportedValue1 != 1 and $reportedValue1 != 2
      Exit Detector must be 1 (DE Apollo) or 2 (Ceta-D)
   Endif
   reyes_detector := $reportedValue1
Endif
If $reyes_detector == 1
   Echo Detector: DE Apollo
Else
   Echo Detector: Ceta-D
Endif

mrc_ext =  .mrc
nav_ext = .nav
log_ext = .log
mdoc_ext = .mdoc

sqrs = _grid_squares
sqrs_file_name = grid_squares\eucentricity$nav_ext

log_sqrs_file_name = $samplename$sqrs$log_ext

DoesFileExist $log_sqrs_file_name
log_file_exists = $reportedValue1

If $log_file_exists == 0
   SaveLogOpenNew $samplename$sqrs

ElseIf $log_file_exists == 1
   Echo Log file with this name already exists and will be saved with an increment index
   SaveLogOpenNew $samplename$sqrs

Endif

Echo Chosen directory: $set_directory
Echo Current sample: $samplename

ReportIfNavOpen
nav_file_open = $reportedValue1

If $nav_file_open == 0
   Exit Could not locate Navigator.

Endif

DoesFileExist $sqrs_file_name
sqrs_file_exists = $reportedValue1

If $sqrs_file_exists == 1
   MergeNavFile $sqrs_file_name

ElseIf $sqrs_file_exists == 0
   Exit $sqrs_file_name was not found

Endif

ReportNumTableItems

Echo $reportedValue1

nitems := $reportedValue1 - 1

Echo Current number of items: $nitems

posoffset = 0
posct = $posoffset + 1

Echo Current position: $posct

SetColumnOrGunValve 1
SetBeamBlank 0
ScreenUp

Loop $nitems

   posct = $posct + 1

   move_ok = 0
   Loop 5
      Loop 60
         ReportStageBusy
         If $reportedValue1 == 0
            Break
         EndIf
         Delay 1 sec
      EndLoop
      Try
         MoveToNavItem $posct
         move_ok = 1
      Catch
         Echo STAGE_RETRY | the stage refused: MoveToNavItem $posct
         Echo STAGE_RETRY | waiting 20 s before trying again
         Delay 20 sec
      EndTry
      If $move_ok == 1
         Break
      EndIf
   EndLoop
   If $move_ok == 0
      Exit The stage stayed busy or not ready through 5 attempts: MoveToNavItem $posct
   EndIf

   Echo Moved to Navigator item $posct

   Delay 1 sec

   SetContinuous V 0
   If $reyes_detector == 1
      SetExposure V 0.5
      SetBinning V 4
      SetFrameTime V 0.5
   ElseIf $reyes_detector == 2
      SetExposure V 1.5
      SetBinning V 2
   Endif

   Eucentricity 3

   UpdateItemZ $posct

   ReportStageXYZ

EndLoop

Echo STOPPING

ReportClock

Echo Completed fine eucentricity for all grid squares

ReportDateTime

ScreenDown
SetBeamBlank 1
SetColumnOrGunValve 0

SaveNavigator
SaveLog
EndMacro
Macro	34
MacroName REyes_SpotGuard

reyes_spot_ok := 1
reyes_lowdose_ok := 1

IsVariableDefined stage_name
If $reportedValue1 == 0
    stage_name @= unnamed-stage
EndIf

IsVariableDefined stage_spot_expected
If $reportedValue1 == 0
    stage_spot_expected := 0
EndIf

IsVariableDefined spot_mismatch_policy
If $reportedValue1 == 0
    spot_mismatch_policy := 1
EndIf

ScreenUp

ReportLowDose
lowdose_on = $reportedValue1
lowdose_area = $reportedValue2

If $lowdose_on == 0
    Echo
    Echo ############################################################
    Echo # STOPPING: LOW DOSE IS OFF  (stage $stage_name)
    Echo #
    Echo # GoToLowDoseArea does nothing while Low Dose is off, so the
    Echo # optics stay wherever the previous stage left them and the
    Echo # spot check below would pass while reporting the LM value.
    Echo # Turn Low Dose on and re-run this stage.
    Echo ############################################################
    Echo
    reyes_lowdose_ok := 0
    reyes_spot_ok := 0
    Return
EndIf

GoToLowDoseArea R

ReportSpotSize
reyes_spot_actual := $reportedValue1

Echo SPOT_GUARD | stage=$stage_name | lowdose=$lowdose_on | area=$lowdose_area | spot_expected=$stage_spot_expected | spot_actual=$reyes_spot_actual

If $stage_spot_expected == 0
    Echo Spot size $reyes_spot_actual recorded for $stage_name (no expectation declared)
    Return
EndIf

If $reyes_spot_actual == $stage_spot_expected
    Echo Spot size verified for $stage_name: $reyes_spot_actual
    Return
EndIf

Echo
Echo ############################################################
Echo # WARNING: SPOT SIZE MISMATCH  (stage $stage_name)
Echo #   expected $stage_spot_expected  but the microscope reports $reyes_spot_actual
Echo #
Echo # Collecting at an unintended spot size changes the dose several-fold.
Echo # It does not stop the run, but it breaks frame classification after
Echo # the fact, and the value is recorded only in the per-frame .mdoc.
Echo #
Echo # If this IS intended, declare it as this stage's expected value
Echo # rather than overriding the guard, so the log records the intent.
Echo ############################################################
Echo

If $spot_mismatch_policy == 1
    Echo ABORTING on spot size mismatch. To run anyway, choose "continue"
    Echo for the spot-mismatch policy at setup.
    reyes_spot_ok := 0
    Return
EndIf

Echo Continuing at spot size $reyes_spot_actual despite the mismatch (policy = continue)

EndMacro
Macro	40
MacroName REyes_postECNT

ReportNumTableItems
Echo Number of Navigator lines: $reportedValue1

nitems := $reportedValue1 - 1
Echo Current number of items: $nitems

Loop $nitems

   DeleteNavigatorItem -1

EndLoop

all_squares = $set_directory\grid_squares\grid_squares.nav
Echo Eucentricity corrected file: $all_squares
MergeNavFile $all_squares

SaveLog
EndMacro
Macro	41
MacroName REyes_premanualECNT

ReportNumTableItems
Echo Number of Navigator lines: $reportedValue1

nitems := $reportedValue1 - 1
Echo Current number of items: $nitems

Loop $nitems

   DeleteNavigatorItem -1

EndLoop

SaveLog
EndMacro
Macro	42
MacroName REyes_saveNAV

Echo $nav_file_name
SaveNavigator $nav_file_name
SaveLog
EndMacro
Macro	43
MacroName ECNT_nav_ready

nav_file_exists = 0
poll_errors = 0
poll_n = 0
Loop 20
   poll_n = $poll_n + 1
   Try
      DoesFileExist grid_squares\eucentricity.nav
      nav_file_exists = $reportedValue1
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=ecnt_nav | errors=$poll_errors
   EndTry

   If $nav_file_exists == 1
      Try
         Delay 5 sec
      Catch
         poll_errors = $poll_errors + 1
         Echo WAIT_POLL_ERROR | wait=ecnt_nav | errors=$poll_errors
      EndTry
      Break
   EndIf

   Try
      Delay 30 sec
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=ecnt_nav | errors=$poll_errors
   EndTry

EndLoop

If $nav_file_exists == 0
   Exit REyes got stuck and Navigator file was not generated. Please, check REyes log.
EndIf
EndMacro
Macro	44
MacroName ECNT_corrected

correction_file_exists = 0
poll_errors = 0
poll_n = 0
Loop 20
   poll_n = $poll_n + 1
   Try
      DoesFileExist grid_squares\eucentricity_correction.png
      correction_file_exists = $reportedValue1
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=ecnt_corrected | errors=$poll_errors
   EndTry

   If $correction_file_exists == 1
      Try
         Delay 15 sec
      Catch
         poll_errors = $poll_errors + 1
         Echo WAIT_POLL_ERROR | wait=ecnt_corrected | errors=$poll_errors
      EndTry
      Break
   EndIf

   Try
      Delay 30 sec
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=ecnt_corrected | errors=$poll_errors
   EndTry

EndLoop

If $correction_file_exists == 0
   Exit REyes got stuck and eucentricity was not corrected. Please, check REyes log.
EndIf
EndMacro
Macro	45
MacroName Targets_nav_ready

inject_enabled = 0
inject_poll_error = 0
If $inject_enabled == 1
   EnterDefaultedNumber 0 0 DRY RUN: targets wait - poll number to raise an error on (0 = none):
   inject_poll_error = $reportedValue1
   Echo DRYRUN_INJECT | stage=WAIT | wait=targets_nav | poll_error=$inject_poll_error
EndIf

nav_file_exists = 0
poll_errors = 0
poll_n = 0
Loop 50
   poll_n = $poll_n + 1
   Try
      If $inject_enabled == 1 AND $inject_poll_error == $poll_n
         Throw DRYRUN injected error on poll $poll_n
      EndIf
      DoesFileExist targets\targets.nav
      nav_file_exists = $reportedValue1
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=targets_nav | errors=$poll_errors
   EndTry

   If $nav_file_exists == 1
      Try
         Delay 5 sec
      Catch
         poll_errors = $poll_errors + 1
         Echo WAIT_POLL_ERROR | wait=targets_nav | errors=$poll_errors
      EndTry
      Break
   EndIf

   Try
      Delay 30 sec
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=targets_nav | errors=$poll_errors
   EndTry

EndLoop

If $nav_file_exists == 0
   Echo WARNING: targets.nav file was not generated after 25 minutes
   Echo This usually means no viable targets were identified
   targets_found := 0
Else
   targets_found := 1
EndIf
EndMacro
Macro	46
MacroName Manual_ready

manual_file_exists = 0
poll_errors = 0
poll_n = 0
Loop 20
   poll_n = $poll_n + 1
   Try
      DoesFileExist grid_squares\manual_grid_overlay.png
      manual_file_exists = $reportedValue1
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=manual_ready | errors=$poll_errors
   EndTry

   If $manual_file_exists == 1
      Try
         Delay 5 sec
      Catch
         poll_errors = $poll_errors + 1
         Echo WAIT_POLL_ERROR | wait=manual_ready | errors=$poll_errors
      EndTry
      Break
   EndIf

   Try
      Delay 30 sec
   Catch
      poll_errors = $poll_errors + 1
      Echo WAIT_POLL_ERROR | wait=manual_ready | errors=$poll_errors
   EndTry

EndLoop

If $manual_file_exists == 0
   Exit REyes got stuck and list of squares has not been updated. Please, check REyes log.
EndIf
EndMacro
