#!/bin/sh  
# \
exec oagwish "$0" "$@"

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath

# Information for menu bar
set CVSRevisionAuthor "\$Revision: 1.2 $ \$Author: emery $"

APSApplication . -name "SRInjectionImageCapture" -version $CVSRevisionAuthor \
  -overview "Capture injection movies shot by gated intensified cameras. Written by B. Yang and L. Emery."

# message window output "stdout"
set VideoCaptureStatus "Initializing ..."
APSScrolledStatus .status -parent .userFrame -width 60 \
  -textVariable VideoCaptureStatus 

proc SetVideoCaptureStatus {text} {
    global SRPlotTrajectoryStatus
    set SRPlotTrajectoryStatus $text
    update
    bell
}

# Widgets design
proc MakeInputFrame {widget args} {
    APSStrictParseArguments {parent}

    # text input   
    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Input parameters"

    APSLabeledEntry .directory -parent $w \
      -label "Output directory:" -textVariable directory \
      -contextHelp "Enter the directory for output image file." -width 60
    APSButton .daily -parent $w.directory -packOption "-side top" \
      -text "daily" -size small \
      -command {set directory [APSGoToDailyDirectory -subdirectory images]}
  
    APSLabeledEntry .filename -parent $w \
      -label "File root name:" -textVariable filename \
      -contextHelp "Enter the file root name. turn numbers will be automatically added." -width 60

    APSLabeledEntry .gain1 -parent $w \
      -label "Starting gain:" -textVariable gain1 \
      -contextHelp "Enter the gain1." -width 50
    APSLabeledEntry .gain2 -parent $w \
      -label "Ending gain:" -textVariable gain2 \
      -contextHelp "Enter the gain2." -width 50

    APSLabeledEntry .frames -parent $w \
      -label "Frames to capture:" -textVariable frames \
      -contextHelp "Frames to capture." -width 50

    # radio button for gated camera selection
    set gatedCamList {BMB BMC1 BMC2 IDA1 IDA2 IDA3}
    global gatedCam
    APSRadioButtonFrame .cameraChoiceFrame -parent $w \
      -orientation  horizontal \
      -packOption {-side top -fill x} \
      -label "Gated Camera   " \
      -variable gatedCam \
      -buttonList $gatedCamList \
      -valueList $gatedCamList \
      -contextHelp "This radio button is used to select a gated camera."

    # radio button for frame grabber selection
    set frameGrabberList {VID1 VID2 VID3}
    global frameGrabber
    APSRadioButtonFrame .frameGrabberChoiceFrame -parent $w \
      -orientation  horizontal \
      -packOption {-side top -fill x} \
      -label "Frame Grabber  " \
      -variable frameGrabber \
      -buttonList $frameGrabberList \
      -valueList $frameGrabberList \
      -contextHelp "This radio button is used to select a video frame grabber."

    # executable command
    APSButton .capture -parent $parent \
      -text "Capture images"  \
      -packOption "-side left" \
      -command {captureVideoData -directory $directory \
                  -filename $filename -frameGrabber $frameGrabber \
                  -frames $frames \
                  -gatedCam $gatedCam \
                  -gain1 $gain1 -gain2 $gain2 \
              -abortVar abortCaptures} \
      -contextHelp "Capture and save first 20 frames images."
    APSButton .abort -parent $parent \
      -text "ABORT"  \
      -packOption "-side left" \
      -command {set abortCaptures 1} \
      -contextHelp "Stops image grabbing."
    APSButton .plot -parent $parent \
      -text "PLOT"  \
      -packOption "-side left" \
      -command {PlotData -directory $directory -file $filename} \
      -contextHelp "Plot data in contour plots."
    return
}

proc PlotData {args} {
    APSParseArguments {directory file}
    if ![file exists $directory/$file] {
        return -code error "Can't find file $file."
    }
    exec sddscontour $directory/$file -col=Index,HLine* -shade=32 -ystring=sparse=20 &
    return
}

proc captureVideoData {args} {
    set directory ""
    set filename  ""
    set frames 20
    set gain1 500
    set gain2 500
    set gatedCam ""
    set frameGrabber ""
    set abortVar ""
    APSParseArguments {frameGrabber gatedCam directory filename \
                         frames gain1 gain2 abortVar}

    global $abortVar
    if {![string length $directory] || ![string length $filename]} {
        return -code error "captureVideoData: Invalid syntax."
    }
    if ![file exists $directory] {
        return -code error "captureVideoData: Can't find directory $directory."
    }
    if [file exists $directory/$filename] {
        return -code error "captureVideoData: $frameGrabber/$filename already exists."
    }

    ##############################################################
    # Save old frame grabber settings and load temporary setting #
    ##############################################################

    APSSetVarAndUpdate VideoCaptureStatus "Saving frame grabber / gated camera settings."
    set dirPV  "S:${frameGrabber}:imageFilePath"
    set rootPV "S:${frameGrabber}:fileIndexRoot"
    set fIndexPV "S:${frameGrabber}:fileIndexNum"
    set saveButton "S:${frameGrabber}:saveImageToFileC"
    set camIndexPV "S:${frameGrabber}:CAL:cameraIndexC"
    set oldValues [exec cavget -list=$dirPV,$camIndexPV]
    set oldcwd [lindex $oldValues 0]
    set oldcam [lindex $oldValues 1]
    set tmpDir /home/helios4/image_data/$frameGrabber
    exec cavput -list=$dirPV=$tmpDir,$rootPV=$filename
    
    # Select control screens and calibration files
    switch $gatedCam {
        BMB  {set gatedCamRoot Sr
            set camIndex 113
        }
        BMC1 {set gatedCamRoot Sr
            set camIndex 109
        }
        BMC2 {set gatedCamRoot Sr
            set camIndex 110
        }
        IDA1 {set gatedCamRoot SrId
            set camIndex 121
        }
        IDA2 {set gatedCamRoot SrId
            set camIndex 122
        }
        IDA3 {set gatedCamRoot SrId
            set camIndex 123
        }
    }
    set gatedCamManualMode ${gatedCamRoot}:GatedCam:ManualModeBO.VAL
    set gatedCamGain       ${gatedCamRoot}:GatedCam:GainAO.VAL    
    set oldValues [exec cavget -list=$gatedCamManualMode,$gatedCamGain]
    set oldMode [lindex $oldValues 0]
    set oldGain [lindex $oldValues 1]
    exec cavput -list=$gatedCamManualMode=1,$camIndexPV=$camIndex

    #################
    #   Take data   #
    #################
    APSSetVarAndUpdate VideoCaptureStatus "Start taking data."

    set turnPV S35I:DG3:aTurnsAO.VAL
    set gaindelta [expr ($gain2 - $gain1)/($frames - 1)]
    for {set fIndex 0} {$fIndex < $frames} {incr fIndex} {
        if {[info exists $abortVar] && [set $abortVar]} {
            APSSetVarAndUpdate VideoCaptureStatus "Aborting..."
            continue
        }
        APSSetVarAndUpdate VideoCaptureStatus "Saving frame No. $fIndex."
        set gain [expr ($gain1 + $fIndex * $gaindelta)]
        exec cavput -list=$fIndexPV=$fIndex,$turnPV=$fIndex,$gatedCamGain=$gain
        after 2000
        exec cavput -list=$saveButton=1
        # requires a long time for the operation to complete.
        after 4000
        set file [file root $filename]-[format %04ld $fIndex][file extension $filename] 
        lappend fileList $tmpDir/$file
        lappend targetList $directory/$file
    }

    APSSetVarAndUpdate VideoCaptureStatus "Transfering data..."
    eval exec sddscombine $fileList $directory/$filename
    ##########################################
    #   restore setting and copy data files  #
    ##########################################
    APSSetVarAndUpdate VideoCaptureStatus "Restoring frame grabber / gated camera settings."
    exec cavput -list=$dirPV=$oldcwd,$camIndexPV=$oldcam,$gatedCamManualMode=$oldMode,$gatedCamGain=$oldGain
    APSSetVarAndUpdate VideoCaptureStatus "Done."
    return
}



set directory .
set filename beamImage.sdds
set gain1 1000
set gain2 1000
set frameGrabber VID3
set gatedCam BMB
set frames 20
set abortCaptures 0

MakeInputFrame .input -parent .userFrame
