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

# $Log: not supported by cvs2svn $
# Revision 1.2  2002/07/24 04:59:02  emery
# Added option to do a coarse scan.
#

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)]
APSStandardSetup


set CVSRevisionAuthor "\$Revision: 1.3 $ \$Author: emery $"
APSApplication . -name scanCerenkovTiming -version $CVSRevisionAuthor \
  -overview {Scan the cerenkov detector timing to determine the correct timing for the first turn.}

set status Working
APSScrolledStatus .status -parent .userFrame -textVariable status -width 50

proc MakeInputFrame {widget args} {
    APSStrictParseArguments {parent}

    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Input parameters"
    APSLabeledEntry .initial -parent $w \
      -label "Relative Initial delay (turns):" -textVariable initial \
      -contextHelp "Enter the initial time delay value." -width 25
    APSLabeledEntry .final -parent $w \
      -label "Relative Final delay (turns):" -textVariable final \
      -contextHelp "Enter the final time delay value." -width 25
    APSRadioButtonFrame .mode -parent $w -orientation horizontal \
      -label "Timing PV: " -variable mode -buttonList {Fine Coarse} \
      -valueList {Fine Coarse} -contextHelp \
      "Choose the timing PV to use for scan. Coarse scan allows 6 ms of range."

    APSLabeledEntry .points -parent $w \
      -label "Number of points:" -textVariable points \
      -contextHelp "Enter the number of points." -width 25
    APSLabeledEntry .sample -parent $w \
      -label "Number of samples/point:" -textVariable samples \
      -contextHelp "Enter the number of samples." -width 25
    APSLabeledEntry .setWidth -parent $w \
      -label "Width of integrator (turns):" -textVariable width \
      -contextHelp "Enter the width of integrator." -width 25

    APSLabeledEntry .outputDir -parent $w \
      -label "Output directory:" -textVariable outputDir \
      -contextHelp "Enter a name for the output file directory." -width 45
    APSButton .daily -parent $w.outputDir -packOption "-side top" \
      -text "daily" -size small \
      -command {set outputDir [APSGoToDailyDirectory -subdirectory cerenkov]}
    APSLabeledEntry .outputFile -parent $w \
      -label "Output file:" -textVariable outputFile \
      -contextHelp "Enter a name for the output file ." -width 25
    
    return
}

proc plotScan {args} {
    global sectorList
    set outputFile timing01
    set outputDir .
    APSParseArguments {outputDir outputFile}
    # check file to see if the scan was fine or coarse
    set mode [exec sdds2stream $outputDir/$outputFile -para=Mode]
    switch $mode {
        Coarse {
            foreach sector $sectorList {
                if {$sector > 0 && $sector < 35 } {
                    set doubleSector [expr ($sector + 1) / 2 * 2 - 1]
                } elseif {$sector == 35 || $sector == 36} {
                    set doubleSector 36
                } elseif {$sector == 38 || $sector == 39} {
                    set doubleSector $sector
                } elseif {$sector == 0 || $sector == 40 } {
                     set doubleSector 40
                }
                lappend options "-col=S:bpm${doubleSector}:cerenkov:TrigD:P,S${sector}:cerenkovReadback0,SigmaS${sector}:cerenkovReadback0" "-grap=error,type=2" "-end"
                lappend options "-col=S:bpm${doubleSector}:cerenkov:TrigD:P,S${sector}:cerenkovReadback1,SigmaS${sector}:cerenkovReadback1" "-grap=error,type=2" "-end"
            }
        }
        Fine {
            foreach sector $sectorList {
                lappend options "-col=S${sector}:cerenkov:delay0,S${sector}:cerenkovReadback0,SigmaS${sector}:cerenkovReadback0" "-grap=error,type=2" "-end"
                lappend options "-col=S${sector}:cerenkov:delay1,S${sector}:cerenkovReadback1,SigmaS${sector}:cerenkovReadback1" "-grap=error,type=2" "-end"
            }
        }
    }
    foreach sector $sectorList {
        lappend options "-col=S${sector}:cerenkov:delay0,S${sector}:cerenkovReadback0,SigmaS${sector}:cerenkovReadback0" "-grap=error,type=2" "-end"
        lappend options "-col=S${sector}:cerenkov:delay1,S${sector}:cerenkovReadback1,SigmaS${sector}:cerenkovReadback1" "-grap=error,type=2" "-end"
    }
    if [catch {eval exec sddsplot -layout=1,2 $outputDir/$outputFile -axes=x -uns=y \
                 $options & \
             } results ] {
        APSSetVarAndUpdate status $results
        return
    }
}
proc runScan {args} {
    global sectorList
    set initial 0
    set final 351
    set points 20
    set samples 5
    set pause 0.5
    set outputFile ""
    set outputDir ""
    set width 3.68
    set mode Fine
    APSParseArguments {initial final points pause samples outputDir outputFile width mode}

    set inputDir /home/helios/oagData/sr/cerenkov/inputFiles
    # convert turns into time
    set initial [expr $initial * 3.682563]
    set final [expr $final * 3.682563]
    set width [expr $width * 3.682563]

    set tmpfile /tmp/[APSTmpString]
    switch $mode {
        Fine {
            if [catch {exec replace $inputDir/timingScanTemplate.exp \
                         $tmpfile.timingScan.exp \
                         -orig=<points>,<pause>,<initial>,<final>,<samples>,<inputDir> \
                         -repl=$points,$pause,$initial,$final,$samples,$outputDir \
                     } results ] {
                APSSetVarAndUpdate status $results
                return
            }
        }
        Coarse {
            if [catch {exec replace $inputDir/coarseTimingScanTemplate.exp \
                         $tmpfile.timingScan.exp \
                         -orig=<points>,<pause>,<initial>,<final>,<samples>,<inputDir> \
                         -repl=$points,$pause,$initial,$final,$samples,$outputDir \
                     } results ] {
                APSSetVarAndUpdate status $results
                return
            }
        }
    }

    set ExperimentDone 0
    set experimentIn $tmpfile.timingScan.exp
    set experimentOut $outputDir/$outputFile
    if [file exists $experimentOut] {
        APSSetVarAndUpdate status "Ouput file $experimentOut exists."
        return -code error "Ouput file $experimentOut exists."
    }
    if [catch {exec cavput -list=S -list=[join $sectorList ,] -list=:cerenkov:width -list=0,1 -list=AO=$width} result ] {
        APSSetVarAndUpdate status $results
        return
    }
    # set SCAN rate to 0.5 seconds (7th enumerated value)
    # set SCAN rate to 1 seconds (6th enumerated value)
    if [catch {exec cavput -list=S -list=[join $sectorList ,] -list=:cerenkovAdc -list=0,1 -list=AI.SCAN=7} result ] {
        APSSetVarAndUpdate status $results
        return
    }
    APSExecLog .expExec -name "Experiment log" \
      -cancelCallback "CleanUpExperiment -datafile $experimentOut" \
      -abortCallback "CleanUpExperiment -datafile $experimentOut" \
      -unixCommand "sddsexperiment $experimentIn $experimentOut -verbose" \
      -callback "CleanUpExperiment -datafile $experimentOut -mode $mode" \
      -width 80
    return
}

proc CleanUpExperiment {args} {
    APSParseArguments {datafile mode}
    global ExperimentDone
    
    exec sddsprocess $datafile \
      -print=para,Mode,$mode -noWarning 
    APSSetVarAndUpdate status "Experiment done."
    set ExperimentDone 1
    return
}

set points 21
set pause 0.5
set samples 10
set initial 0
set final 20
set width 1
set outputFile timing01
set outputDir .
set mode Fine
set sectorList [exec  sdds2stream -col=Sector /home/helios/oagData/sr/cerenkov/sectors.sdds]

MakeInputFrame .input -parent .userFrame
set status "Ready."

APSButton .run -parent .userFrame -text Run -command \
  { \
      APSDisableButton .userFrame.run.button 
      catch {runScan -initial $initial -final $final \
               -points $points -samples $samples \
               -width $width \
               -mode $mode \
               -outputDir $outputDir -outputFile $outputFile \
      } status
      update idletasks
      APSEnableButton .userFrame.run.button }

APSButton .plot -parent .userFrame -text Plot -command \
  { \
      APSDisableButton .userFrame.plot.button 
      catch {plotScan \
               -outputDir $outputDir -outputFile $outputFile \
      } status
      update idletasks
      APSEnableButton .userFrame.plot.button }
