#!/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)]

set CVSRevisionAuthor "\$Revision: 1.44 $ \$Author: shang $"

set archiveDir /home/helios/oagData/sr/tuneArchive/FPGAdata

set env(EPICS_CA_MAX_ARRAY_BYTES) "3000000"

proc SetStatus {text} {
    global status fftLength
    set status $text
    update
}

set channel A
set archive 0
set source NASA
set topIndex -1
set enableNASA 1
proc MakeArchiveWidget {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    APSFrame $widget -parent $parent -label "Archive" \
      -contextHelp "Controls archiving and review of archived tune data."

    set w $parent$widget.frame

    global startDay startMonth startYear outputDir rootname fftLength clockShift adcDelay P0Select archiveDir archive
    global endDay endMonth endYear reprocess xySpan defaultSpan source topIndex enableNASA
    set reprocess 0
    # APSDateTimeAdjEntry .date0 -parent $w \
      # -dayVariable startDay -monthVariable startMonth -yearVariable startYear \
      #  -label "Start Y/M/D: "
    # APSDateTimeAdjEntry .date1 -parent $w \
      # -dayVariable endDay -monthVariable endMonth -yearVariable endYear \
     # -label "End   Y/M/D: "
    
    APSLabeledEntry .dir -parent $w -label "Output Directory:" -textVariable outputDir \
      -width 70
    APSButton .archive -parent $w.dir -packOption "-side right" -text "archive" -command "SetOutputDir -option archive" -size small
    APSButton .daily -parent $w.dir -packOption "-side right" -text "daily" -size small -command "SetOutputDir -option daily"
    APSLabeledEntry .filename -parent $w -label "Rootname:" -textVariable rootname \
      -width 70
    global comment 
    set comment "no comment"
    
    APSLabeledEntry .comment -parent $w -label "Comment:" -textVariable comment \
      -width 90

#    APSRadioButtonFrame .source -parent $w -label "Enable/Disable NASA:          " -buttonList {Enable Disable} \
#      -valueList {1 0} \
#      -variable enableNASA  -orientation horizontal
    
    APSFrameGrid .grid -parent $w -xList {x1 x2}
    APSRadioButtonFrame .channel -parent $w.grid.x1 -label "Select channel for measurement:" -buttonList {A(x) B(y) Both} -valueList {A B Both} \
      -variable channel  -orientation horizontal 
    global RingBucket
    APSLabeledEntry .bucket -parent $w.grid.x2 -label "    Select ring bucket number:" -textVariable RingBucket -width 20
    APSButton .add -parent $w.grid.x2.bucket -packOption "-side right" -text "->" -command "SelectBucket -add 1"
    APSButton .reduce -parent $w.grid.x2.bucket -packOption "-side right" -text "<-" -command "SelectBucket -add 0"
    bind $w.grid.x2.bucket.entry <Return> "SelectBucket -update 1"
    APSLabeledEntry .clockShiftA -parent $w.grid.x1 -label "clockShiftA:" \
      -textVariable clockShiftA -width 20
    APSLabeledEntry .clockShiftB -parent $w.grid.x2 -label "clockShiftB:" \
      -textVariable clockShiftB -width 20
    APSLabeledEntry .adcDelayA -parent $w.grid.x1 -label "adcDelayA:" \
      -textVariable adcDelayA -width 20
    APSLabeledEntry .adcDelayA -parent $w.grid.x2 -label "adcDelayB:" \
      -textVariable adcDelayB -width 20
    APSLabeledEntry .p0SelectA -parent $w.grid.x1 -label "P0PhaseA(0/180):" \
      -textVariable P0SelectA -width 20
    APSLabeledEntry .p0SelectB -parent $w.grid.x2 -label "P0PhaseB(0/180):" \
      -textVariable P0SelectB -width 20
    APSLabeledEntry .att -parent $w.grid.x1 -label "Attenuator A:" \
	-textVariable attenuatorA -width 20
    APSLabeledEntry .att -parent $w.grid.x2 -label "Attenuator B:" \
	-textVariable attenuatorB -width 20
    APSLabeledEntry .mix -parent $w.grid.x1 -label "Mixer delay A:" \
	-textVariable mixerDelayA -width 20
    APSLabeledEntry .mix -parent $w.grid.x2 -label "Mixer delay B:" \
	-textVariable mixerDelayB -width 20
####### removed scan clock phase here
    set widgetList [APSTabFrame .tab -parent $w -width 1000 -height 400 -labelList "NASA Chirper Turns" -frameIndexVariable topIndex \
                      -commandList {UpdateOutputDirBySource UpdateOutputDirBySource UpdateOutputDirBySource} ]
# -label "NASA/Chirper/Turns Parameters" -commandList
    set f1 [lindex $widgetList 0]
    set f2 [lindex $widgetList 1]
    set f3 [lindex $widgetList 2]
   
    global scanRangeBuckets adcAcqDelay scanStartBucket xStartA \
      xStopA zRangeA xStartB xStopB zRangeB xPowerLevel xPoints xCenterFreq \
      xTuneLow xTuneHigh yPowerLevel yPoints yCenterFreq yTuneLow yTuneHigh
### use 0/-6 for hybrids mode and -5/-12 for 24 singlets mode
    
    
    APSFrameGrid .grid -parent $f1 -xList {x1 x2}
    set w1 $f1.grid.x1
    set w2 $f1.grid.x2

    APSLabeledEntry .xStartA -parent $w1 -label "channel A xStart(0 to 0.1):" \
      -textVariable xStartA -width 20
    APSLabeledEntry .xStopA -parent $w1 -label "channel A xStopA(xStart to 0.5):" \
      -textVariable xStopA -width 20
    APSLabeledEntry .zRangeA -parent $w1 -label "channel A zRange (100 to 20000):" \
      -textVariable zRangeA -width 20
    APSLabeledEntry .power -parent $w1 -label "NASA channel A power level:" -width 20 \
      -textVariable xPowerLevel
    APSLabeledEntry .points -parent $w1 -label "NASA channel A set points:" -width 20 \
      -textVariable xPoints
    APSLabeledEntry .freq -parent $w1 -label "NASA channel A tune CF (0.1-0.4):" -width 20 \
      -textVariable xCenterFreq
    bind $w1.freq.entry <Return> "UpdateXYFreqFilter"
    APSLabeledEntryFrame .range -parent $w1 -label "x tune filter (low/high):" \
      -width 10 -variableList {xTuneLow xTuneHigh} -orientation horizontal 
    APSRadioButtonFrame .source -parent $w1 -packOption "-side top" -label "Enable/Disable NASA:          " -buttonList {Enable Disable} \
      -valueList {1 0} \
      -variable enableNASA  -orientation horizontal
    APSLabeledEntry .xStartB -parent $w2 -label "channel B xStart(0 to 0.1):" \
      -textVariable xStartB -width 20
    APSLabeledEntry .xStopB -parent $w2 -label "channel B xStop(xStart to 0.5):" \
      -textVariable xStopB -width 20
    APSLabeledEntry .zRangeB -parent $w2 -label "channel B zRange (100 to 20000):" \
      -textVariable zRangeB -width 20
     APSLabeledEntry .power -parent $w2 -label "NASA channel B power level:" -width 20 \
      -textVariable yPowerLevel
    APSLabeledEntry .points -parent $w2  -label "NASA channel B set points:" -width 20 \
      -textVariable yPoints
    APSLabeledEntry .freq -parent $w2 -label "NASA channel B tune CF (0.1-0.4):" -width 20 \
      -textVariable yCenterFreq
    bind $w2.freq.entry <Return> "UpdateXYFreqFilter"
    APSLabeledEntryFrame .range -parent $w2 -label "y tune filter (low/high):  " \
      -width 10 -variableList {yTuneLow yTuneHigh} -orientation horizontal 
    APSButton .scan -parent $w2 -packOption "-side top" -text "Scan Clock Phase" -command "scanClockPhase" -contextHelp \
      "set sample clock shifts."

    global chirperPlotOption
    set chiperPlotOption ""
    APSLabeledEntry .option -parent $f2 -label "Plot option:" -width 78 -textVariable chirperPlotOption

    global turnPause DACdrive DACdelay DACbucketOffset chirpDacStart  chirpDacInterval \
        chirpDacNumber chirpAcqStart chirpAcqInterval  chirpAcqNumber
    set turnPause 0
    set DACdrive Modulate
    set DACdelay 0
    set DACbucketOffset 206
    APSFrameGrid .grid -parent $f2 -xList {x1 x2}
    set w1 $f2.grid.x1
    set w2 $f2.grid.x2
    set chirpDacStart 0
    set chirpDacInterval 3
    set chirpDacNumber 432
    set chirpAcqStart 0
    set chirpAcqInterval 54
    set chirpAcqNumber 24
  
    APSLabel .label -parent $f2 -text "                Start           Interval          Number"
    APSLabeledEntryFrame .read1 -parent $f2 -label "DAC buckets:" \
      -variableList {chirpDacStart chirpDacInterval chirpDacNumber} -orientation horizontal -width 15
    APSButton .set1 -parent $f2.read1 -packOption "-side left" -text "clear and set" -command "SetChirpBuckets -dacAcq dac -clear 1"
    APSButton .set2 -parent $f2.read1 -packOption "-side left" -text "set only" -command "SetChirpBuckets -dacAcq dac -clear 0"
    APSLabeledEntryFrame .set1 -parent $f2 -label "Acq buckets:" \
      -orientation horizontal -width 15 -variableList {chirpAcqStart chirpAcqInterval chirpAcqNumber}
    APSButton .set2 -parent $f2.set1  -packOption "-side left" -text "clear and set" -command "SetChirpBuckets -dacAcq acq -clear 1"
    APSButton .set3 -parent $f2.set1  -packOption "-side left" -text "set only" -command "SetChirpBuckets -dacAcq acq -clear 0"
    APSLabeledEntry .pause -parent $w1 -label "Pause (usec):" -width 20 -textVariable turnPause 
  
    APSRadioButtonFrame .drive -parent $w2 -label "DAC drive:" -buttonList {Modulate Baseband} -valueList {Modulate Baseband} -variable DACdrive \
      -orientation horizontal
    
    
    
    global chirpStartA chirpStopA chirpStepA DACDelayA DACGainA halfClockDelayA DACDelayA DACOffsetA
    set chirpStartA 0.16
    set chirpStopA 0.20
    set chirpStepA 0.0001
    set DACOffsetA 206
    set DACDelayA 2
    set DACGainA 0.5
    set halfClockDelayA 0
   
    APSLabeledEntry .chirps -parent $w1 -label "Chirp startA:" -width 20 -textVariable chirpStartA
    APSLabeledEntry .chirpt -parent $w1 -label "Chirp stopA: " -width 20 -textVariable chirpStopA
    APSLabeledEntry .step -parent $w1   -label "Chirp stepA: " -width 20 -textVariable chirpStepA
    APSLabeledEntry .delay -parent $w1  -label "DAC DelayA:  " -width 20 -textVariable DACDelayA
    APSLabeledEntry .gain -parent $w1   -label "DAC gainA:   " -width 20 -textVariable DACGainA
    APSLabeledEntry .offset -parent $w1  -label "DAC OffsetA:  " -width 20 -textVariable DACOffsetA
    APSRadioButtonFrame .delay1 -parent $w1 -label "Half clock delayA:" -buttonList {0 1/2} -valueList {0 1} \
	-variable halfClockDelayA -orientation horizontal
    global chirpStartB chirpStopB chirpStepB DACDelayB DACGainB  halfClockDelayB DACOffsetB
    set chirpStartB 0.2
    set chirpStopB 0.26
    set chirpStepB 0.0001
    set DACOffsetB 206
    set DACDelayB 26
    set halfClockDelayB 0
    set DACGainB 0.4
 
    APSLabeledEntry .chirps -parent $w2 -label "Chirp startB:" -width 20 -textVariable chirpStartB
    APSLabeledEntry .chirpt -parent $w2 -label "Chirp stopB: " -width 20 -textVariable chirpStopB
    APSLabeledEntry .step -parent $w2   -label "Chirp stepB: " -width 20 -textVariable chirpStepB
    APSLabeledEntry .delay -parent $w2  -label "DAC DelayB:  " -width 20 -textVariable DACDelayB
    APSLabeledEntry .gain -parent $w2   -label "DAC gainB:   " -width 20 -textVariable DACGainB
    APSLabeledEntry .offset -parent $w2  -label "DAC offsetB:  " -width 20 -textVariable DACOffsetB
   
    APSRadioButtonFrame .delay1 -parent $w2 -label "Half clock delayB:" -buttonList {0 1/2} -valueList {0 1} \
	-variable halfClockDelayB -orientation horizontal

    APSButton .view -parent $f2 -text "Acquire Data" -command "saveData -archive 0"
    APSButton .plot -parent $f2 -text "Review Data" -command "ReviewChirperData"
    
    APSButton .scan -parent $f2  -text "Scan Clock Phase" -command "scanClockPhase" -contextHelp \
      "set sample clock shifts."

    APSFrame .ff2 -parent $f1 -packOption "-side top"
    $f1.ff2.frame configure -bd 0
    set w $f1.ff2.frame
    APSButton .view -parent $w -text "Acquire and View Only" -command "saveData -archive 0"
    APSButton .history -parent $w -text "Review Plots" -command \
        "ReviewPlots" -contextHelp \
        "Displays history of tune values between the dates given above."
    
    APSButton .archive -parent $w -text "Acquire and Archive" -command "saveData -archive 1" \
        -contextHelp \
        "Saves tune data to the archive area."
    
    
    APSFrame .ff1 -parent $f1 -packOption "-side top"
    $f1.ff1.frame configure -bd 0
    set w $f1.ff1.frame
  #  APSButton .disable -parent $w -text "Disable Drive" -command "DisableDrive" -contextHelp "disable the selected source."
    APSButton .review -parent $w -text "Review Achive Spectra" -command \
        "ReviewPlots -archive 1" -contextHelp \
        "Reviews archived tune data between the dates given above."
    APSButton .plot1 -parent $w -text "Reprocess Tune" -command "ReprocessTuneCurve"
    APSButton .launchScreen -parent $w -text "Launch MEDM screen" \
    -command "exec /home/helios/PAR/bin/srTune &"

    #turns waveform widget
    APSLabeledEntryFrame .set1 -parent $f3 -label "Acq buckets (start/interval/number):" \
      -orientation horizontal -width 15 -variableList {chirpAcqStart chirpAcqInterval chirpAcqNumber}
    APSButton .set2 -parent $f3.set1  -packOption "-side left" -text "clear and set" -command "SetChirpBuckets -dacAcq acq -clear 1"
    APSButton .set3 -parent $f3.set1  -packOption "-side left" -text "set only" -command "SetChirpBuckets -dacAcq acq -clear 0"
    APSButton .view -parent $f3 -text "Acquire Data" -command "SaveTurnsData"
    APSButton .plot -parent $f3 -text "Review Data" -command "ReviewTurnsData"
    APSButton .scan -parent $f3 -text "Scan Clock Phase" -command "scanClockPhase" -contextHelp \
      "set sample clock shifts."

}

proc DisableDrive {args} {
    global source
    
    if [catch {SetupNASATuneDrive -plane both } result] {
        return -code error "Error in disabling NASA: $result"
    }
    
    if [catch {exec cavput -list=S:tune:chirp:dacGainA=0,S:tune:chirp:dacGainB=0 } result] {
        return -code error "unable to disable chirper: $result"
    }
}
proc ReprocessTuneCurve {args} {
    
    global outputDir archiveDir fftLength xTuneLow xTuneHigh yTuneLow yTuneHigh reprocess fileSelection1
   
    set oldDir [pwd]
    cd $outputDir
    set fileList [lsort -unique -decreas [regsub -all {\.tune} [glob -nocomplain *] ""]]
    if ![llength $fileList] {
        SetStatus "No files found in $outputDir."
        return
    }
    cd $oldDir
    set fileSelection1 ""
    SetStatus "Selecting file..."
    APSScrolledListWindow .process -name "Select a file" \
      -label "Select a file" \
      -itemList $fileList -selectionVar fileSelection1
    tkwait variable fileSelection1
    if ![string length $fileSelection1] {
        SetStatus "No file chosen"
        return
    }
    
    if [catch {CalculateTune -filename $outputDir/$fileSelection1 -plot 1 } tune] {
        return -code error "$tune"
    }
    tkwait variable fileSelection1
    if [catch {CalculateTune -filename $outputDir/$fileSelection1 -plot 1 } tune] {
        return -code error "$tune"
    }
}

proc SelectBucket {args} {
    set add 0
    set update 0
    APSParseArguments {add update}
    global  BucketOffset adcDelayA adcDelayB RingBucket
    if $update {
        set adcDelayA [expr $BucketOffset + $RingBucket]
        set adcDelayB $adcDelayA
    } else {
        if $add {
            set RingBucket [expr $RingBucket+3]
            set adcDelayA [expr $adcDelayA+3]
            set adcDelayB [expr $adcDelayB+3]
        } else {
            set RingBucket [expr $RingBucket - 3]
            set adcDelayA [expr $adcDelayA - 3]
            set adcDelayB [expr $adcDelayB -3]
        }
        if $RingBucket>=0 {
            set RingBucket [expr $RingBucket%1296]
        } else {
            set RingBucket [expr $RingBucket + 1296]
        }
    }
}

proc scanClockPhase {args} {
    global clockShiftA adcDelayA P0SelectA clockShiftB adcDelayB BucketOffset SRBucket
    global P0SelectB diagresponse adcAcqDelay scanStartBucket scanRangeBuckets  
    set att_x [lindex [exec caget C0:P0FB:SumAttSet.A] 1]
    set att_y [lindex [exec caget C1:P0FB:SumAttSet.A] 1]
#### set fixed att value for timing scan
    exec caput C0:P0FB:SumAttSet.A [expr $att_x + 0] 
    exec caput C1:P0FB:SumAttSet.A [expr $att_y + 0] 
    set diagresponse 0
    SetStatus "Scan clock phase, please waiting ..."
    exec caput S:tune:scanPllFirstBucket $scanStartBucket 
    exec caput S:tune:scanPllBucketCount $scanRangeBuckets 
    foreach channel { "A" "B" } index {0 1} {  
        #    puts "$channel $index"
        exec caput S:tune:scanPllAdcSelect $index 
        after 1000
        exec caput S:tune:ClockScanStartBO 1
        after 10000
        set P0Select${channel} [exec caget -t S:tune:pinger:P0select]
        set adcDelay${channel} [exec caget -t S:tune:pinger:acqDelay]
        set clockShift${channel} [exec caget -t S:tune:adcClockShift]
    }
    set BucketOffset adcDelayA
    set SRBucket 0
#### restore attenuator values.
    exec caput C0:P0FB:SumAttSet.A $att_x
    exec caput C1:P0FB:SumAttSet.A $att_y
    SetStatus "done."
    update
}


proc Measure {args} {
#    global adcAcqDelay 
    set outputFile ""
    set commandline 0
    set channel ""
    set source ""
    set maxWaitMs [expr int(1024 * 15.07328) + 3000] 
    APSParseArguments {outputFile commandline channel source}
    
    global clockShiftA adcDelayA P0SelectA clockShiftB adcDelayB P0SelectB enableNASA chirpAcqStart chirpAcqInterval  chirpAcqNumber
    global chirpDacStart chirpDacInterval  chirpDacNumber
    global chirpStartA chirpStopA  chirpStepA chirpStartB chirpStopB  chirpStepB chirperPlotOption
    global attenuatorA attenuatorB mixerDelayA mixerDelayB
    
    if !$commandline {
	SetStatus "1. set clockShift (Stune:pinger:clockShift)"
        if {$channel=="A"} {
	    if [catch { exec /home/helios/PAR/bin/setSRClockShift \
			    $clockShiftA $adcDelayA  $P0SelectA } result] {
		return -code error $result
            }
        }
	if {$channel=="B"} {
	    if [catch { exec /home/helios/PAR/bin/setSRClockShift \
			    $clockShiftB $adcDelayB $P0SelectB } result] {
		return -code error $result
	    }
	}
   }
    if !$commandline {
        SetStatus "2. disable both pingers on tuneAcquisition.adl (S:tune:pinger:Yenable)"
    }
    switch $channel {
        A {
            set plane x
            set index 0
            set waveformPV S:tune:fftAvg:gtr:waveform0
        } 
        B {
            set plane y
            set index 1
            set waveformPV S:tune:fftAvg:gtr:waveform1
        }
    }
    switch $source {
        NASA {
            if $enableNASA {
                if [catch {SetupNASATuneDrive -plane $plane } result] {
                    return -code error "Error in setup NASA: $result"
                }
            } else {
                DisableDrive 
            }
        }
        Chirper {
            if [catch {SetupChirperDrive -channel $channel } result] {
                return -code error "Error in setup chirper: $result"
            }
            set waveformPV S:tune:chirp:gtr:waveform0
        }
    }
   
    if {$source=="NASA"} {
         if [catch {exec cavput -list=S:tune:fftAvg:gtr:arm=0} result] {
             return -code error $result
         }
        after 500
        if !$commandline {
            SetStatus "4. set auto restart to no on tunePlots.adl (S:tune:fftAvg:gtr:autoRestart) "
        if [catch {exec cavput -list=S:tune:fftAvg:gtr:autoRestart=0} result] {
            return -code error $result
        }
        }
        after 500
        if !$commandline {
            SetStatus "5. disarm and arm the acquisition the FftWaterfallPlots.adl (S:tune:fftAvg:gtr:arm)"
        
        if [catch {exec cavput -list=S:tune:fftAvg:gtr:arm=1} result] {
            return -code error $result
        }
        after 3000
	}
    } else {
        SetStatus "2. Arm chirp. "
        if [catch {exec cavput -list=S:tune:chirp:gtr:arm=1 -pend=10} result] {
            return -code error "SetupChirperDrive3: unable to arm chirper: $result"
        }
	set points [expr int ( ([set chirpStop$channel] - [set chirpStart$channel] )/[set chirpStep$channel])] 
        set waitMs [expr int($points * 15.07328)+3000]
	if { $waitMs > $maxWaitMs } {
		set waitMs $maxWaitMs 
	}
        set waitSeconds [expr $waitMs / 1000 ]
	SetStatus "6. Wait $waitSeconds seconds for FPGA to finish"
	after $waitMs

#        after [expr int($points * 15.07328)+3000]
#	if [catch {exec cavget -list=S:tune:chirpWaveformsNORD -printErrors} points] {
#	    return -code error $points
#	}
    }
    if !$commandline {
        SetStatus "7. take data..."
    }
    global env xDim yDim fftLength 
    set env(EPICS_CA_MAX_ARRAY_BYTES) 3000000
    set tuneInterval [expr 1.0 / 2048.0]
   set scalars /home/helios/oagData/sr/tuneArchive/inputFiles/tuneScalars.mon 
#    set scalars /home/helios/PAR/SRTune/inputFiles/tuneScalars.mon 
    set timeStr [clock format [clock seconds] -format %Y-%j-%m%d:%H%M%S].$plane
   
    if [catch {exec sddswmonitor -erase -pvnames=$waveformPV  \
                 -xparameter=name=x,dimension=$xDim,interval=1,minimum=0 \
                 -yparameter=name=y,dimension=$yDim,interval=$tuneInterval,minimum=0 \
                 -scalars=$scalars \
                 $outputFile } result] {
        return -code error $result
    }
    if {$source=="NASA"} {
        if [catch {SetupNASATuneDrive -plane x/y } result] {
            return -code error $result
        }
        if !$commandline {
            set plot 1
        } else {
            set plot 0
        }
        if [catch {ProcessData -filename $outputFile -plot $plot -channel $channel -source $source} result] {
            return -code error $result
        }
    } else {
	if [catch {exec cavget -list=S:tune:chirpWaveformsNORD -printErrors} len] {
	    return -code error "Process chirper data1: $len"
	}
        if [catch {GetChirpAcqBuckets -start $chirpAcqStart -number $chirpAcqNumber -interval $chirpAcqInterval} bucketList] {
            return -code error "Process chirper data2: $bucketList "
        }
        set tmpFile /tmp/[APSTmpString]
        if [catch {exec sddsmakedataset -col=BucketNumber,type=long -data=[join $bucketList ,]  $tmpFile } result] {
            return -code error "Process chirper data3: $result"
        }
        set rows [exec sdds2stream -rows=bar $tmpFile]
        set pointsA [expr $len/$rows]
        if [catch {exec cavget -list=S-DCCT:CurrentM -printErrors } srCurrent] {
            return -code error "Process chirper data4: srCurrent"
        }
       # puts $tmpFile
       # puts "$rows $len $points"
        if {$srCurrent>15} {
            #read the bunch current only when there is stored beam
            if [catch {exec sddswget -pv=BNCHI:BunchCurrentWF $tmpFile.1} result] {
                return -code error "Unable to reand the bunch current waveform."
            }
            if [catch {exec sddsprocess $tmpFile.1  -pipe=out\
                         "-process=Waveform,max,Max" \
                         "-define=col,NormInt,Waveform Max /" \
                         | sddsprocess -pipe=in \
                         "-test=col,NormInt 0.5 >" $tmpFile.2 } result] {
                return -code error "Unable to find out the bucket current: $result"
            }
            if [catch {exec sddsxref $tmpFile $tmpFile.2 -equate=BucketNumber=Index -nowarnings \
                         -fillIn -rename=col,Waveform=BunchCurrent -pipe=out \
                         | sddsexpand -pipe=in $tmpFile.3 } result] {
                return -code error "Process chirper data5: result"
            }
        } else {
            if [catch {exec sddsprocess $tmpFile "-redefine=col,BunchCurrent,0" -pipe=out \
                         | sddsexpand -pipe=in $tmpFile.3 } result] {
                return -code error "Process chirper data6: result"
            }
        }
        if [catch {exec sddsprocess $outputFile -filter=col,Index,0,[expr $len-1] -pipe=out  \
                     -define=par,AcqBucketStart,$chirpAcqStart,type=long \
                     -define=par,AcqBucketInterval,$chirpAcqInterval,type=long \
                     -define=par,AcqBucketNumber,$chirpAcqNumber,type=long \
                     -define=par,DACBucketStart,$chirpDacStart,type=long \
                     -define=par,DACBucketInterval,$chirpDacInterval,type=long \
                     -define=par,DACBucketNumber,$chirpDacNumber,type=long \
                     | sddsbreak -pipe -rowlimit=$pointsA \
                     | sddsprocess -pipe -redefine=col,Index,i_row  \
		     | sddsprocess -filter=col,Index,0,$points -pipe \
		     | sddsprocess -pipe \
		     "-redefine=col,tune,Index [set chirpStep$channel] * [set chirpStart$channel] +" \
		     | sddsprocess \
		     -process=S:tune:chirp:gtr:waveform0,spread,wfSpread -pipe \
                     | sddsxref -pipe=in $tmpFile.3 $outputFile.1 -transfer=par,BucketNumber,BunchCurrent -leave=* -nowarnings } result] {
            return -code error "Process chirper data7: $result $len $points $tmpFile.3 $outputFile"
        }
	exec mv $outputFile.1 $outputFile
        if {0} {
        set yInc [expr 0.2 * [exec sddscollapse $outputFile -pipe=out \
                                | sddsprocess -process=wfSpread,maximum,wfSpreadMax -pipe \
                                | sdds2stream -para=wfSpreadMax -pipe=in ] ] 
        }
       eval  exec sddsplot -col=tune,S:tune:chirp:gtr:waveform0 $outputFile  \
          -split=pages $chirperPlotOption -grap=li,vary \
          -leg=para=BucketNumber & 
    }
    if !$commandline {
        SetStatus "done."
    }
    return $timeStr
}

proc GetChirpAcqBuckets {args} {
    if [catch {exec cavget -list=S:tune:chirpAcqControl -range=begin=0,end=416,interval=16 -list=.B \
                 -list=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F -printErrors -pend=30 -label } valList] {
        return -code error $valList
    }
    array set data $valList
    set bucketList ""
    foreach name [array name data] {
        set nt [string index $name end]
        set num [scan $name S:tune:chirpAcqControl%ld]
        set nt [expr 0x$nt]
        set bucket [expr ($num+$nt)*3 ]
        if $data($name) {
            lappend bucketList $bucket
        }
    }
    set bucketList [lsort -integer $bucketList]
    return $bucketList
}

proc CalculateTune {args} {
    set filename ""
    set plot 0
    APSParseArguments {filename plot}
    
    global xTuneLow xTuneHigh yTuneLow yTuneHigh xCenterFreq yCenterFreq 
    global xStartA xStartB xStopA xStopB 
    global srRevFreq
    SetStatus "Calculating tune..."

    if [catch {exec sdds2stream -par=channel $filename} channel] {
        set channel A
    } 
    if [catch {exec sdds2stream -par=SR:TUNE:NASA:centerFreqAI $filename} centerFreqHz] {
    return -code error "centerFreqHz parameter not found"
    } 
    switch $channel {
        A {
            set low $xTuneLow
            set high $xTuneHigh
            set plane x
	    set xStart $xStartA
	    set xStop $xStopA
        }
        B {
            set low $yTuneLow
            set high $yTuneHigh
            set plane y
	    set xStart $xStartB
	    set xStop $xStopB
        }
    }
    if [catch { set centerFreqTune [expr fmod ($centerFreqHz / $srRevFreq, 1)]} result ] {
    return -code error "$result centerFreqTune: $centerFreqTune"
    }
    if { $centerFreqTune > 0.5 } {
	set centerFreqTune [expr 1.0 - $centerFreqTune]
    }
    if [catch {exec sddsprocess $filename \
		   "-redefine=col,tune,Index 1024 mod 2048 /" -pipe=out \
		   | sddssort -col=tune -pipe \
		   | sddsbreak -change=tune -pipe \
		   | sddsprocess -process=SrTune,max,SrTune \
		   -process=tune,first,tune -pipe \
		   | sddscollapse  -pipe \
		   | sddsprocess -filter=col,SrTune,100,1e9 -pipe \
		   | sddssmooth -col=SrTune -pipe \
		   | sddsxref -pipe=in $filename -leave=* -transfer=par,* $filename.tune } result] {
	return -code error "Error in processing tune: $result"
    }
    if [catch {exec sddsprocess $filename.tune -pipe=out \
                 -process=SrTune,max,tune,functionOf=tune,position,lowerLimit=$low,upperLimit=$high \
                 | sdds2stream -pipe -par=tune} tune] {
        return -code error $tune
    }
    if [catch {exec sddsprocess $filename $filename.1 -redefine=par,nu,$tune} result] {
        return -code error $result
    }
    if [catch {exec sddsprocess $filename.tune $filename.tune.1 -redefine=par,nu,$tune} result] {
        return -code error $result
    }
    exec mv $filename.1 $filename
    exec mv $filename.tune.1 $filename.tune
    if $plot {
        exec sddsplot -col=tune,SrTune -graph=line $filename.tune \
	"-title=$filename" "-topline=$plane tune\\=[format %.4f $tune]" \
	-filter=col,tune,$low,$high &
    }
    SetStatus "calculating tune done."
    return $tune
}

proc SaveTurnsData {args} {
    global channel source outputDir rootname

    switch $channel {
        A {
            set planeList x
            set channelList A
        }
        B {
            set planeList y
            set channelList B
        }
        Both {
            set planeList {x y}
            set channelList {A B}
        }
    }
    foreach chan $channelList plane $planeList {
        set filename ${rootname}.turn.${plane}-0000
        set newfilename [APSNextGenerationedName -name $filename -separator "-" -directory $outputDir -newFile 1] 
        if  [catch  {TakeTurnsData -plane $plane -channel $channel -filename $outputDir/$newfilename } result] {
            return -code error $result
        }
    }
    SetStatus "done."
}

proc TakeTurnsData {args} {
    set plane ""
    set channel ""
    set filename ""
    global chirpAcqStart chirpAcqNumber chirpAcqInterval
    APSParseArguments {plane channel filename}
    
    switch $channel {
        A {
            set plane x
            set index 0
            set waveformPV S:tune:turn:gtr:waveform0
        } 
        B {
            set plane y
            set index 1
            set waveformPV S:tune:turn:gtr:waveform1
        }
    }
 #   SetStatus "1, setup tune drive..."
  #  if [catch {SetupNASATuneDrive -plane $plane } result] {
  #      return -code error "Error1 in setup NASA: $result"
  #  }
    if [catch {exec cavput -list=S:tune:turn:gtr:arm=1} result] {
        return -code error "Error2 in arm turn trigger: $result"
    }
    #if [catch {exec cavput -list=S:tune:turn:gtr:softTrigger=1 } result] {
    #    return -code error "Error2 in triggering turns waveform: $result"
    #}
    SetStatus "2, taking data ..."
    set scalars /home/helios/oagData/sr/tuneArchive/inputFiles/tuneScalars.mon 
    if [catch {exec sddswmonitor -erase -pvnames=$waveformPV  \
                 -scalars=$scalars $filename } result] {
        return -code error "Error3 in taking turn data: $result"
    }
    #process data
    if [catch {exec cavget -list=S:tune:chirpWaveformsNORD -printErrors} len] {
        return -code error "Process turns data1: $len"
    }
    if [catch {GetChirpAcqBuckets -start $chirpAcqStart -number $chirpAcqNumber -interval $chirpAcqInterval} bucketList] {
        return -code error "Process turns data2: $bucketList "
    }
    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddsmakedataset -col=BucketNumber,type=long -data=[join $bucketList ,]  $tmpFile } result] {
        return -code error "Process turns data3: $result"
    }
    set rows [exec sdds2stream -rows=bar $tmpFile]
    if [catch {exec cavget -list=S-DCCT:CurrentM -printErrors } srCurrent] {
        return -code error "Process turns data4: srCurrent"
    }
    if {$srCurrent>15} {
        #read the bunch current only when there is stored beam
        if [catch {exec sddswget -pv=BNCHI:BunchCurrentWF $tmpFile.1} result] {
            return -code error "Unable to reand the bunch current waveform."
        }
        if [catch {exec sddsprocess $tmpFile.1  -pipe=out\
                     "-process=Waveform,max,Max" \
                     "-define=col,NormInt,Waveform Max /" \
                     | sddsprocess -pipe=in \
                     "-test=col,NormInt 0.5 >" $tmpFile.2 } result] {
            return -code error "Unable to find out the bucket current: $result"
        }
        if [catch {exec sddsxref $tmpFile $tmpFile.2 -pipe=out -equate=BucketNumber=Index -nowarnings \
                     -fillIn -rename=col,Waveform=BunchCurrent \
                     | sddsexpand -pipe=in $tmpFile.3 } result] {
            return -code error "Process turns data5: $result"
        }
        
    } else {
        if [catch {exec sddsprocess $tmpFile -pipe=out -define=col,BunchCurrent,0 \
                 | sddsexpand -pipe=in $tmpFile.3 } result] {
            return -code error "Process turns data6: $result"
        }
    }
    set total_rows [exec sdds2stream -rows=bar $filename]
    set bucketCounts [llength $bucketList]
    set nrows [expr int ($total_rows/$chirpAcqNumber )]
    if  [catch {exec sddsprocess $filename -pipe=out "-redefine=col,IndexM,Index $rows mod" \
                  | sddssort -pipe=in,out -col=IndexM \
                  | sddsbreak -change=IndexM -pipe \
                  | sddsprocess -pipe "-redefine=col,Index,i_row" \
                  | sddsprocess -pipe -filter=col,Index,0,$nrows \
                  -process=$waveformPV,spread,wfSpread  \
                  | sddsxref -pipe=in $tmpFile.3 -leave=* -transfer=par,BucketNumber,BunchCurrent $filename.break } result] {
        return -code error "Process turns data7: $result"
    }
    file rename -force $filename.break $filename
    
}

proc ReviewTurnsData {args} {
    global outputDir turnFileSelection
    
    cd $outputDir
    set fileList [lsort -unique -decreas [regsub -all {\.turn} [glob -nocomplain *] "\.turn"]]
    if ![llength $fileList] {
        SetStatus "No turns file found."
        return
    }
    set turnFileSelection ""
    APSScrolledListWindow .process1 -name "Select a file" \
      -label "Select a file" \
      -itemList $fileList -selectionVar turnFileSelection
    tkwait variable turnFileSelection
    if ![string length $turnFileSelection] {
        SetStatus "No file chosen"
        return
    }
    PlotTurnFile -filename $outputDir/$turnFileSelection 
    tkwait variable turnFileSelection
    PlotTurnFile -filename $outputDir/$turnFileSelection
}

proc PlotTurnFile {args} {
    set filename ""
    APSParseArguments {filename}
    if [regexp {.x} $filename] {
        set waveformPV S:tune:turn:gtr:waveform0
    } else {
        set waveformPV S:tune:turn:gtr:waveform1

    }
    set yInc [expr 0.2 * [exec sddscollapse $filename -pipe=out \
                            | sddsprocess -process=wfSpread,maximum,wfSpreadMax -pipe \
                            | sdds2stream -para=wfSpreadMax -pipe=in ] ] 
    exec sddsplot -col=Index,$waveformPV $filename  \
      -split=pages -stagger=yIncrement=$yInc -grap=li,vary \
      -leg=para=BucketNumber & 
}

proc saveData {args} {
    set archive 0
    APSParseArguments {archive}
    
    global archiveDir outputDir rootname fftLength channel source
    
    switch $channel {
        A {
            set planeList x
            set channelList A
        }
        B {
            set planeList y
            set channelList B
        }
        Both {
            set planeList {x y}
            set channelList {A B}
        }
    }
    foreach chan $channelList plane $planeList {
        set filename ${rootname}.${plane}-0000
        set newfilename [APSNextGenerationedName -name $filename -separator "-" -directory $outputDir -newFile 1] 
        
        if [catch {Measure -outputFile $outputDir/$newfilename -channel $chan -source $source} timeStr] {
            return -code error $timeStr
        }
        if $archive {
            if [APSYesNoPopUp "Would you like to archive this data?"] {
                exec cp $outputDir/$filename $archiveDir/$timeStr
                exec cp $outputDir/$filename.tune $archiveDir/$timeStr.tune
            }
        }
    }
}

proc PlotFile {args} {
    set filename ""
    APSParseArguments {filename}
    global xTuneLow xTuneHigh yTuneLow yTuneHigh xCenterFreq yCenterFreq 
    global adcAcqDelay xStartA xStopA zRangeA xStartB xStopB zRangeB
    SetStatus "plotting..."
    if [catch {exec sdds2stream -par=channel $filename} channel] {
        set channel A
    }
    if [catch {exec sdds2stream -par=nu $filename} tune] {
        set description [exec sdds2stream -par=Description $filename]
    } else {
        set description "tune = [format %.4f $tune]"
    }
    
    switch $channel {
        A {
            set plane x
	    set low $xTuneLow
	    set high $xTuneHigh
            if {$zRangeA==0} {
                exec sddscontour $filename  -quantity=SrTune -swapxy \
                  -shade=100\
                  -topline=file -date \
                  "-title=$description" \
                  "-yLabel=${plane} tune" -xLabel=Traces \
                  -scales=$xStartA,$xStopA,0,0  &
            } else {
                exec sddscontour $filename  -quantity=SrTune -swapxy \
                  -shade=100,0,$zRangeA \
                  -topline=file -date \
                  "-title=$description" \
                  "-yLabel=${plane} tune" -xLabel=Traces \
                  -scales=$xStartA,$xStopA,0,0 &
            }
        }
        B {
            set plane y
	    set low $yTuneLow
	    set high $yTuneHigh
            if {$zRangeB==0} {
                exec sddscontour $filename  -quantity=SrTune -swapxy \
                  -shade=100\
                  -topline=file -date \
                  "-title=$description" \
                  -yLabel=${plane}\ tune -xLabel=Traces  \
                  -scales=$xStartB,$xStopB,0,0  &
            } else {
                exec sddscontour $filename  -quantity=SrTune -swapxy \
                  -shade=100,0,$zRangeB \
                  -topline=file -date \
                  "-title=$description" \
                  -yLabel=${plane}\ tune -xLabel=Traces \
                  -scales=$xStartB,$xStopB,0,0 &
            }
        }
    }
    if [file exist $filename.tune] {
        set tune [exec sdds2stream -par=nu $filename.tune]
        exec sddsplot -col=tune,SrTune -graph=line $filename.tune \
	"-title=$filename" "-topline=$plane tune\\=[format %.4f $tune]" \
	-scales=$low,$high,0,0 &
    }
}

proc UpdateXYFreqFilter {args} {
    global xCenterFreq yCenterFreq xTuneLow xTuneHigh yTuneLow yTuneHigh
    set xTuneLow [format %.2f [expr $xCenterFreq - 0.05]]
    set xTuneHigh [format %.2f [expr $xCenterFreq + 0.05]]
    set yTuneLow [format %.2f [expr $yCenterFreq - 0.05]]
    set yTuneHigh [format %.2f [expr $yCenterFreq + 0.05]]
}

proc ReviewChirperData {args} {
    global outputDir chirperFileSelection chirperPlotOption

    cd $outputDir
    set fileList [lsort -unique -decreas [regsub -all {\.tune} [glob -nocomplain *] ""]]
    if ![llength $fileList] {
        SetStatus "No files found in $outputDir."
        return
    }
    set chirperFileSelection ""
    APSScrolledListWindow .process1 -name "Select a file" \
      -label "Select a file" \
      -itemList $fileList -selectionVar chirperFileSelection
    tkwait variable chirperFileSelection
    if ![string length $chirperFileSelection] {
        SetStatus "No file chosen"
        return
    }
    PlotChirperFile -filename $outputDir/$chirperFileSelection -extraOption $chirperPlotOption
    tkwait variable chirperFileSelection
    PlotChirperFile -filename $outputDir/$chirperFileSelection -extraOption $chirperPlotOption
}

proc PlotChirperFile {args} {
    set filename ""
    set extraOption ""
    APSParseArguments {filename extraOption}
    

   eval  exec sddsplot -col=tune,S:tune:chirp:gtr:waveform0 $filename  \
      -split=pages  -grap=li,vary $extraOption \
      -leg=para=BucketNumber & 
}
proc ReviewPlots {args} {
    set archive 0
    APSParseArguments {archive}
    
    
    global outputDir archiveDir fftLength channel fileSelection
    set oldDir [pwd]
    
    if $archive {
        set dir $archiveDir
    } else {
        set dir $outputDir
    }
    cd $dir
    set fileList [lsort -unique -decreas [regsub -all {\.tune} [glob -nocomplain *] ""]]
    if ![llength $fileList] {
        SetStatus "No files found in $dir."
        return
    }
    SetStatus "listing files..."
    set fileSelection ""
    APSScrolledListWindow .process1 -name "Select a file" \
      -label "Select a file" \
      -itemList $fileList -selectionVar fileSelection
    tkwait variable fileSelection
    if ![string length $fileSelection] {
        SetStatus "No file chosen"
        return
    }
    PlotFile -filename $dir/$fileSelection
    tkwait variable fileSelection
    PlotFile -filename $dir/$fileSelection
}

proc ProcessData {args} {
    global xDim xDimMax yDim totalTimeMs fftLength comment
    global adcAcqDelay xStartA xStopA zRangeA  xStartB xStopB zRangeB
    ### added to check and apply the acquisition length PV
    set fftLength [exec caget S:tune:pinger:FFTsampleCount -t]
   
    set filename ""
    set plot 1
    set channel ""
    set source ""
    APSParseArguments {filename plot channel source}
    #### limit to 113 traces. 
  
    set cutoff [expr $xDim * $yDim - 1]
    set option ""
    set fftFormatLog [exec sdds2stream -para=S:tune:crosspointControl.B3 $filename] 
    global xTuneLow xTuneHigh yTuneLow yTuneHigh
    
    switch $channel {
        A {
            set index 0
            set low $xTuneLow
            set high $xTuneHigh
            set plane x
        }
        B {
            set index 1
            set low $yTuneLow
            set high $yTuneHigh
            set plane y
        }
    }
    
    if {$fftFormatLog == 0 } { 
        if [catch {eval exec sddsprocess $filename -pipe=out -filter=col,Index,0,$cutoff \
                     | sddsprocess -pipe=in $filename.1 -nowarnings \
                     \"-redefine=col,SrTune,S:tune:fftAvg:gtr:waveform$index \" \
                     \"-reprint=par,Description,[APSMakeSafeQualifierString $comment]\" \
                     "-reprint=par,channel,$channel" \
                     "-reprint=par,source,$source" \
                     -redefine=para,xDimension,$xDim,type=long \
                     -redefine=para,yDimension,$yDim,type=long } result] {
            return -code error $result
        }
    } else {
        if [catch {eval exec sddsprocess $filename -pipe=out -filter=col,Index,0,$cutoff \
                     | sddsprocess -pipe=in $filename.1 -nowarnings \
                     \"-redefine=col,SrTune,2 S:tune:fftAvg:gtr:waveform$index 1024.0 / pow \" \
                     \"-reprint=par,Description,[APSMakeSafeQualifierString $comment]\" \
                     "-reprint=par,channel,$channel" \
                     "-reprint=par,source,$source" \
                     -redefine=para,xDimension,$xDim,type=long \
                     -redefine=para,yDimension,$yDim,type=long } result] {
            return -code error $result
        }   
    }
    exec mv $filename.1 $filename
    if [catch {CalculateTune -filename $filename } tune] {
        return -code error "Error in computing tune: $tune"
    }
    
    if $plot {
        PlotFile  -filename $filename
    }
}

set centerFreq 357317200
if [catch {exec cavget -list=SR:TUNE:NASA:freqSpanAO -printErrors} origSpan] {
    return -code error $origSpan
}

proc SetupChirperDrive {args} {
    set channel A
    APSParseArguments {channel}
    global chirpStart$channel chirpStop$channel chirpStep$channel DACDelay$channel DACGain$channel
    global turnPause DACdrive DACdelay DACbucketOffset halfClockDelay$channel halfClockDelay$channel DACOffset$channel
    
    
    if [catch {exec cavput -list=S:tune:chirp:pause=$turnPause,S:tune:chirp:baseband=$DACdrive,S:tune:chirp:dacDelay=[set halfClockDelay$channel],S:tune:chirp:dacBucketOffset=[set DACOffset$channel] -pend=20 } result] {
        return -code error "SetupChirperDrive - unable to set chirp parameters: $result"
    }
     #disable NASA
    if [catch {exec cavput -list=SR:TUNE:NASA:rfPowerBO=0,SR:TUNE:NASA:sweepSelectMBBO=0 } result] {
        return -code error "SetupChirperDrive - unable disable NASA: $result"
    }
    if [catch {exec cavput -list=S:tune:chirp:adcSelectSeq${channel}. \
                 -list=DO1=[set chirpStart$channel],DO2=[set chirpStop$channel],DO3=[set  chirpStep$channel],DO4=[set DACDelay$channel] } result] {
        return -code error "SetupChirperDrive1: $result"
    }
    if [catch {exec cavput -list=S:tune:chirp:dacGain${channel}=[set DACGain$channel]}  result] {
        return -code error "SetupChirperDrive2: $result"
    }
    switch $channel {
	A {
	    set togger B
	}
	B {
	    set togger A
	}
    }
    #toggle the ADC selection to make the Acq parameters become the same the selected channel
    if [catch {exec cavput -list=S:tune:chirp:adcSelect=$togger} result] {
	return -code error $result
    }
    if [catch {exec cavput -list=S:tune:chirp:adcSelect=$channel} result] {
	return -code error $result
    }
}
proc SetupNASATuneDrive {args} {
    set plane x
    APSParseArguments {plane}
    global centerFreq  xPowerLevel xPoints xCenterFreq  yPowerLevel yPoints yCenterFreq \
    defaultSpan xySpan origSpan srRevFreq centerFreqA0
   
    if {$plane=="x" || $plane=="y"} {
        #disable the chirper
        if [catch {exec cavput -list=S:tune:chirp:dacGainA=0,S:tune:chirp:dacGainB=0 -pend=30} result] {
            return -code error "SetupNASATuneDrive: unable to disable chirper."
        }
    }
    
    switch $plane {
        x {
            set pointsVal [expr int ( log (($xPoints  )/50)/ log (2.0)) ]
            if [catch {exec caput SR:TUNE:HP_1366A_C0P1_MBBO  1
		exec caput SR:TUNE:Mux4Sw0BO 0
		exec caput SR:TUNE:HP_1366A_C0P0_MBBO 1
		exec caput SR:TUNE:HP_1366A_C0P1_MBBO 1
		exec caput SR:TUNE:HP_1366A_C2P0_MBBO 1
		exec caput SR:TUNE:NASA:centerFreqAO [expr (1390 - $xCenterFreq) * $srRevFreq] 
		exec caput SR:TUNE:NASA:freqSpanAO $xySpan
                exec caput SR:TUNE:NASA:sweepSelectMBBO  1
                exec caput SR:TUNE:NASA:ifBwMO 2 
                exec caput SR:TUNE:NA:setNumPointsMO $pointsVal
		### setting sweep time zero forces updating of sweep time from points and ifBW
                exec caput SR:TUNE:NASA:sweepTimeAO 0
                exec caput SR:TUNE:NASA:rfPowerAO $xPowerLevel
		after 2000
                exec caput SR:TUNE:NASA:trigModeBO 1
                exec caput SR:TUNE:NASA:rfPowerBO 1  # turn on power
		exec caput SR:TUNE:Mux4Sw2BO 1 #turn on nasa drive
	    } result] {
                return -code error "unable to setup NASA for x plane: $result"
            }
        }
        y {
            set pointsVal [expr int ( log (($yPoints  )/50)/ log (2.0)) ]
            if [catch {exec caput SR:TUNE:HP_1366A_C0P1_MBBO 2
	    	exec caput SR:TUNE:Mux4Sw2BO 1
		exec caput SR:TUNE:HP_1366A_C0P0_MBBO 1
		exec caput SR:TUNE:HP_1366A_C0P1_MBBO 2
		exec caput SR:TUNE:HP_1366A_C2P0_MBBO 4
                exec caput SR:TUNE:NASA:centerFreqAO [expr (1390 - $yCenterFreq) * $srRevFreq] 
                exec caput SR:TUNE:NASA:freqSpanAO $xySpan
                exec caput SR:TUNE:NASA:sweepSelectMBBO  1
                exec caput SR:TUNE:NASA:ifBwMO 2 
                exec caput SR:TUNE:NA:setNumPointsMO $pointsVal
                exec caput SR:TUNE:NASA:sweepTimeAO 0 
                exec caput SR:TUNE:NASA:rfPowerAO $yPowerLevel
		after 2000
                exec caput SR:TUNE:NASA:trigModeBO 1
                exec caput SR:TUNE:NASA:rfPowerBO 1  # turn on power
		exec caput SR:TUNE:Mux4Sw2BO 1 #turn on nasa drive
		} result] {
                return -code error "unable to setup NASA for y plane: $result"
            }
        }
        default {
	    if [catch {exec cavput -list=SR:TUNE:HP_1366A_C0P1_MBBO=0,SR:TUNE:NASA:freqSpanAO=$origSpan,SR:TUNE:NASA:trigModeBO=0,SR:TUNE:NASA:rfPowerAO=13,SR:TUNE:NA:setNumPointsMO=3,SR:TUNE:NASA:ifBwMO=2,SR:TUNE:NASA:sweepTimeAO=0,SR:TUNE:Mux4Sw2BO=0 -pend=30 
	    } result] {
                return -code error "unable to setup NASA for x/y plane: $result"
            }
	    after 1000
	    if [catch {exec cavput -list=SR:TUNE:NASA:sweepSelectMBBO=0,SR:TUNE:NASA:rfPowerBO=0 -pend=30} result] {
		return -code error "unable to setup NASA for x/y plane2: $result"
	    }
        }
    }
}

proc SetChirpBuckets {args} {
    set dacAcq acq
    set clear 0
    APSParseArguments {dacAcq clear}
    global chirpAcqStart chirpAcqInterval chirpAcqNumber
    global chirpDacStart chirpDacInterval chirpDacNumber
    SetStatus "Set chirp $dacAcq buckets..."
    switch $dacAcq {
        dac {
            set start $chirpDacStart
            set interval $chirpDacInterval
            set number $chirpDacNumber
            set pvPrefix S:tune:chirpDacEnable
        }
        acq {
            set start $chirpAcqStart
            set interval $chirpAcqInterval
            set number $chirpAcqNumber
            set pvPrefix S:tune:chirpAcqControl
        }
    }
    if {[expr $start % 3]!=0} {
        return -code error "The $dacAcq bucket start has to be multiplier of 3!"
    }
    if {[expr $interval % 3]!=0} {
        return -code error "The $dacAcq bucket interval has to be multiplier of 3!"
    }
    if {[expr $number * $interval]>1296 } {
    	return -code error "Bucket train length longer than 1296!"
    }
    if $clear {
        if [catch {exec cavput -list=${pvPrefix} -range=begin=0,end=416,interval=16 -list=.B \
                     -list=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F -list==0 -pend=10 } result] {
            return -code error "Unable to clear chirp $dacAcq buckets."
        }
    }
    
    for {set i 0} {$i<$number} {incr i} {
        set bucket [expr $start + $i * $interval]
        if {$bucket>=1296} {
            set bucket [expr $bucket - 1296]
        }
        set bucket3 [expr $bucket / 3]
        set bk [expr ( ${bucket3}/16) *16]
        set m [string toupper [format %x [expr $bucket3%16]]]
        set pv ${pvPrefix}${bk}.B$m
        lappend setList $pv=1
    }
    if [string length $setList] {
        if [catch {exec cavput -list=[join $setList ,] -pend=30} result] {
            return -code error "Error in setting chirp $dacAcq buckets: $start $number $interval: $result"
        }
    } else {
        return -code error "No buckets is being set because of the wrong input of $dacAcq start/interval/number."
    }
    SetStatus "Done"
}

proc UpdateOutputDirBySource {args} {
    global source archive outputDir topIndex
    if {$source=="Disable"} {
        return
    }
    switch $topIndex {
        0 {
            set source NASA
        }
        1 {
            set source Chirper
        }
        2 {
            set source Turns
        }
    }
    if $archive {
        set outputDir /home/helios/oagData/sr/tuneArchive/FPGAdata/$source
    } else {
        set outputDir [APSGoToDailyDirectory -subdirectory SRTuneFPGA-$source]
    }
}

proc SetOutputDir {args} {
    set option ""
    APSParseArguments {option}
    global source outputDir archive 
    
    if {$source=="Disable"} {
        return
    }
    switch $option {
        daily {
            set archive 0
            set outputDir [APSGoToDailyDirectory -subdirectory SRTuneFPGA-$source]
        }
        archive {
            set archive 1
            set outputDir /home/helios/oagData/sr/tuneArchive/FPGAdata/$source
        }
    }
}
set outputDir [APSGoToDailyDirectory -subdirectory SRTuneFPGA-NASA]

set rootname SrTune
set outputFile ""
set args $argv 
set channel A
APSParseArguments {outputFile channel}

set xDim 128 
set yDim 1024 
set xDimMax 128
set comment "no comment"
### revolution period
if [catch {exec cavget -list=A014-IETS:BTC:SRSetFreqM -pend=30 -printErrors} rfFreq] {
    puts stderr "Error in reading SR rf frequency (A014-IETS:BTC:SRSetFreqM): $rfFreq"
    exit 1
}
set P0Period [expr 1.0e3 / $rfFreq * 1296.0 ]
set srRevFreq [expr $rfFreq / 1296.0 ]
###  set up pinger pattern
exec /home/helios/PAR/SRTune/setPingerPattern 9.5 1075 SR

#[expr 1.0e3 / 351.95e6 * 1296.0]
### total valid data time in ms for the booster
set fftLength [exec caget S:tune:pinger:FFTsampleCount -t]
set configFile /home/helios/oagData/sr/tuneArchive/inputFiles/tuneconfig.sdds

set varList [exec sdds2stream -col=VariableName $configFile]
set valList [exec sdds2stream -col=DefaultValue $configFile]
foreach var $varList val $valList {
    set $var $val
}

UpdateXYFreqFilter
set SRBucket 0
set RingBucket 0
set BucketOffset $adcDelayA

if ![string length $outputFile] {
    APSApplication . -name SR-Tunes-FPGA -version $CVSRevisionAuthor \
        -overview {Helps with booster tune measurement setup and data collection.}
    
    set status Working...
    APSScrolledStatus .status -parent .userFrame -textVariable status \
        -width 60 -height 2
    update
    
    MakeArchiveWidget .data -parent .userFrame
} else {
    wm withdraw .
    if [catch {Measure -outputFile $outputFile -commandline 1 -channel $channel} result] {
        puts stderr $result
        exit 1
    } else {
        exit 0
    }
}
