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

APSApplication . -name BoosterCavityDetuningMeasurement -overview "This application provides GUI for acquistion data of booster cavity detuning for APS upgrade project."

set Status Ready
APSScrolledStatus .status -parent .userFrame -width 70 \
        -textVariable Status

proc SetStatus {text} {
    global Status
    set Status $text
    update
}

proc TurnOnRFBlanking {args} {
    global blankingDelay blankingWide
    if ![APSYesNoPopUp "Are you sure to turn on RF blanking?"] {
        SetStatus "Turning on RF blanking was canceled."
        return
    }
    
    SetStatus "1, Turning off RF blanking..."
    if [catch {exec cavput -list=BRF:K5:brf_blankingDly2.GATE=0 -pend=10} result] {
        return -code error "Error turning off rf blanking2: $result"
    }
    after 1000
    SetStatus "2, set delay and wide..."
    if [catch {exec cavput -list=BRF:K5:brf_blankingDly1.DLY=$blankingDelay,BRF:K5:brf_blankingDly2.WIDE=$blankingWide -pend=30} result] {
        return -code error "Error setting blanking delay and wide: $result"
    }
    SetStatus "3, turn on blanking..."
    if [catch {exec cavput -list=BRF:K5:brf_blankingDly2.GATE=1 -pend=10} result] {
        return -code error "Error turning on rf blanking3: $result"
    }
    SetStatus "done."
}

proc AcquireData {args} {
    global outputDir description rfSignal preTrigger postTrigger blankingStatus
    if {$blankingStatus=="Disabled"} {
        if ![APSYesNoPopUp "The blanking is disabled, are you sure to continue collecting data?"] {
            return
        }
    }
    
    SetStatus "Check A014 LLRF data acquisition system mux..."
    if [catch {exec cavget -list=SRF:S:RFmuxCtl_BI -printErrors -pend=10 } status] {
        return -code error "Error reading SRF:S:RFmuxCtl_BI: $status"
    }
    if {$status=="Local"} {
        APSInfoWindow .info -name "Warning" -infoMessage "A014 LLRF DAQ Mux is in Local control.\nYou must go to room A014 and switch to Remote. Data not collected."
        return
    }
    
    if [catch {APScaputTextToWaveform -pvName DAQ:SRRF:HISTORY:TCP:BurstDescriptionC -text $description } result] {
        return -code error "Error setting description field: $result"
    }
    if [catch {APScagetTextFromWaveform -pvName DAQ:SRRF:HISTORY:TCP:LastSavedFileNameM  } filename1] {
        return -code error "Error reading DAQ filename: $filename1"
    }
    SetStatus "before collecting data: DAQ file name=$filename1"
    SetStatus "Initialize DAQ..."

    if [catch {exec cavput "-list=DAQ:SRRF:DRV:AcquireOnEventCalc.INPA=DAQ:SRRF:DRV:AcquireOnEventC NPP NMS"
	exec cavput "-list=DAQ:SRRF:DRV:AcquireOnEventCalc.INPB=IOCRTFBDAQ:BoosterRfMuteUnixTsM CP NMS"
	exec cavput -list=DAQ:SRRF:HISTORY:TCP:PreTriggerTimeC=$preTrigger,DAQ:SRRF:HISTORY:TCP:PostTriggerTimeC=$postTrigger,DAQ:SRRF:HISTORY:TCP:SyncAcquireEnableC=1 -pend=30 } result] {
        return -code error "Error initializing DAQ: $result"
    }
    

    if [catch {exec cavget -list=DAQ:SRRF:HISTORY:TCP:DataCaptureM -printErrors -num -pend=10} collecting] {
        return -code error "Error checking acquisition status: $collecting."
    }
    if $collecting {
        SetStatus "other process is collecting data, waiting for it done."
        for {set i 0} {$i<30} {incr i} {
            if [catch {exec cavget -list=DAQ:SRRF:HISTORY:TCP:DataCaptureM -printErrors -num -pend=10} collecting] {
                return -code error "Error checking acquisition status: $collecting."
            }
            if !$collecting {
                break
            }
            APSWaitWithUpdate -waitSeconds 1
        }
        if $collecting {
            SetStatus "Time out while waiting for collecting status to become zero."
            return
        }
    }
    SetStatus "Collecting data..."
    if [catch {exec cavput -list=DAQ:SRRF:DRV:AcquireOnEventC=1 -pend=10} result] {
        return -code error "Error setting DAQ:SRRF:DRV:AcquireOnEventC: $result"
    }
    APSWaitWithUpdate -waitSeconds 3
    if [catch {exec cavget -list=DAQ:SRRF:HISTORY:TCP:DataCaptureM -printErrors -num -pend=10} collecting] {
        return -code error "Error checking acquisition status: $collecting."
    }
    SetStatus "Collecting data, waiting for it done..."
    while {1} {
        if [catch {exec cavget -list=DAQ:SRRF:HISTORY:TCP:DataCaptureM -printErrors -num -pend=10} collecting] {
            return -code error "Error checking acquisition status: $collecting."
        }
        if !$collecting {
            break
        }
    }
    
    if [catch {APScagetTextFromWaveform -pvName DAQ:SRRF:HISTORY:TCP:LastSavedFileNameM  } filename2] {
	return -code error "Error reading DAQ filename: $filename2"
    }
    SetStatus "After collecting data: filename=$filename2"
    if [string compare $filename1 $filename2]==0 {
        SetStatus "Error: data collecting failed (filename not changed). Please investigate"
        return
    }
    SetStatus "post-processing data $filename2..."
    if [catch {PostProcessData1 -filename $filename2 } result] {
        SetStatus "Error processing $filename2: $result"
        return
    }
    if {$rfSignal==5} {
        set desc "Booster RF Sum"
    } else {
        set desc "Booster Cavity $rfSignal"
    }
    SetStatus "restore initial settings..."
    catch {exec sddscasr -restore $outputDir/InitSCR.sdds } result
    if [catch {exec cavput -list=BRF:K5:brf_blankingDly2.GATE=0 -pend=10} result] {
        SetStatus "Error turning off blanking: $result"
    }
    SetStatus "data acquisition for $desc done."
}



proc PostProcessData1 {args} {
    set filename ""
    APSParseArguments {filename}
    global outputDir Time_start Time_length
    
    if ![file exist $filename] {
        return -code error "$filename does not exit!"
    }
    set rootname $outputDir/[file root [file tail $filename]]

    set data_phase ADC4:SRMuxSig:Phase
    set data_amp ADC4:SRMuxSig:Amplitude
    
    set cols [exec sddsquery -col $filename]
    if [lsearch -exact $cols $data_amp]<0 {
        set data_amp ADC4:SRMuxSig:Mag
        if [lsearch -exact $cols $data_amp]<0 {
            return -code error "Measurement data must have ADC4:SRMuxSig:Mag or ADC4:SRMuxSig:Amplitude column!"
        }
    }

    set Time_stop  [expr {$Time_start*1.0e-6 + $Time_length*1.0e-6}]
    set threshold 180
    set modulo 360
    
    set Cavity [exec sdds2stream -param=BoosterRfMuxSourceM $filename]
    SetStatus "Cavity = $Cavity"
    # unwrap the phase signal
    if [catch {exec sddsunwrap $filename -pipe=out -col=$data_phase -threshold=$threshold -modulo=$modulo \
                 | sddsprocess -pipe=in \
                 $rootname.proc \
                 "-define=col,TimeFromMute,Time BoosterRfMuteUnixTimeM -" } result] {
	return -code error "PostProcessDataA: $result"
    }
    
    # Get maximum of waveform and save it in WaveformMax
    set WaveformMax [exec sddsprocess -pipe=out  $rootname.proc \
                       -process=$data_amp,maximum,WaveformMax \
                       | sdds2stream -pipe=in -param=WaveformMax]
    
    #puts $WaveformMax
    # Save all values which have 90% of the maximum value (should contain all peaks)
    # Then break into different pages. Each page should consist of one peak -> The falling slope is expected to start at the last value (which is 90% of the maximum)
    
     set peakTimes [ exec sddsprocess -pipe=out $rootname.proc \
                       -filter=col,$data_amp,[expr $WaveformMax * 0.9],$WaveformMax \
                       | sddsbreak -pipe -gapin=RelativeTime,amount=0.25 \
                       | sddsprocess -pipe -process=RelativeTime,last,WaveformMaxPos \
                       | sdds2stream -pipe=in -param=WaveformMaxPos ]
    
    # First version looked for the maximum. However, script is more robust taking the last datapoint.
    #	 | sddsprocess -pipe -process=$data_amp,max,WaveformMaxPos,position,functionOf=RelativeTime \
      
    # Loop through peaks
    set page 1
    foreach peakTime $peakTimes {
        set TimeStart [expr $peakTime + $Time_start*1.0e-6]
        set TimeStop  [expr $peakTime + $Time_start*1.0e-6 + $Time_length*1.0e-6]
        # Filter the data after the peak into a new file. Redefine RelativeTime to start at zero on each page. Neccessary for expfit
        exec sddsprocess $rootname.proc -filter=col,RelativeTime,$TimeStart,$TimeStop  $rootname.proc.page$page \
          "-redefine=col,RelativeTime,RelativeTime 0 &RelativeTime \[ -" \
          "-redefine=col,Unwrap$data_phase,Unwrap$data_phase 0 &Unwrap$data_phase \[ -" \
          "-reprint=par,DataFile,$filename" 
        incr page
    }
    # Combine the different output files into different pages of a single sdds file. 
    if [catch { eval exec sddscombine -overWrite [glob $rootname.proc.page*] $rootname.proc.filter } result] {
	return -code error "PostProcessData1: $result"
    }
    
    # delete temporary files
    eval file delete [glob $rootname.proc.page*]
    
    #calculate deltaF (slope of the phase signal equals frequency offset)
    if [catch {exec sddspfit $rootname.proc.filter -pipe=out \
                 -col=RelativeTime,Unwrap$data_phase -terms=2 | sddsprocess -pipe \
                 "-redefine=param,DeltaF,Slope -360 / 1e3 /,units=kHz" \
                 | tee $rootname.proc.phase \
                 | sdds2stream -pipe -par=DeltaF } DeltaF] {
        return -code error "PostProcessData2: $DeltaF"
    }
    
    SetStatus "DeltaF = $DeltaF kHz"
    set cols [exec sddsquery -col $rootname.proc.filter]
    if [lsearch -exact $cols $data_amp]<0 {
        return -code error "Measurement data must have ADC4:SRMuxSig:Mag or ADC4:SRMuxSig:Power column!"
    }
    #calculate QL (time constant of amplitude decay leads to Q-factor)
    if [catch {exec sddsexpfit $rootname.proc.filter -pipe=out \
	         -col=RelativeTime,$data_amp -clue=decays -fullOutput | sddsprocess -pipe \
                 "-redefine=param,QL,-352e6 pi * expfitRate /" \
                 | tee $rootname.proc.amp \
                 | sdds2stream -pipe -par=QL } QL] {
        return -code error "PostProcessData3: $QL"
    }
    SetStatus "QL = $QL"
    
    #plot Data
    if [catch {exec sddsprocess -nowarnings $rootname.proc \
                 "-redefine=par,QL,$QL" \
                 "-redefine=par,DeltaF,$DeltaF,units=kHz" \
                 "-reprint=par,DataFile,$filename" } result] {
        return -code error "PostProcessData4: error processing output file: $result"
    }
    
    PlotData1 -filename [file tail $rootname.proc]
}

proc PostProcessData {args} {
    set filename ""
    APSParseArguments {filename}
    global outputDir Time_start Time_length
   
    if ![file exist $filename] {
        return -code error "$filename does not exit!"
    }
    set rootname $outputDir/[file root [file tail $filename]]
    
    set Time_stop  [expr $Time_start*1.0e-6 + $Time_length*1.0e-6]
    set data_phase ADC4:SRMuxSig:Phase
    set data_amp ADC4:SRMuxSig:Amplitude
    set threshold 180
    set modulo 360

    set cols [exec sddsquery -col $filename]
    if [lsearch -exact $cols $data_amp]<0 {
        set data_amp ADC4:SRMuxSig:Mag
        if [lsearch -exact $cols $data_amp]<0 {
            return -code error "Measurement data must have ADC4:SRMuxSig:Amplitude or ADC4:SRMuxSig:Power column!"
        }
    }
    set Cavity [exec sdds2stream -param=BoosterRfMuxSourceM $filename]
    SetStatus "Cavity = $Cavity"
    #fileter the data
    if [catch {exec sddsunwrap $filename -pipe=out -col=$data_phase -threshold=$threshold -modulo=$modulo \
		   | sddsprocess -pipe=in \
		   $rootname.proc \
		   "-define=col,TimeFromMute,Time BoosterRfMuteUnixTimeM -" } result] {
	return -code error "PostProcessDataA: $result"
    }
    if [catch {exec sddsprocess $rootname.proc $rootname.proc.filter \
		   -filter=col,TimeFromMute,$Time_start*1.0e-6,$Time_stop \
		   "-redefine=col,RelativeTime,RelativeTime 0 &RelativeTime \[ -" } result] {
        return -code error "PostProcessData1: $result"
    }
    #calculate deltaF
    if [catch {exec sddspfit $rootname.proc.filter -pipe=out \
                 -col=RelativeTime,Unwrap$data_phase -terms=2 \
                 | sddsprocess -pipe \
                 "-redefine=param,DeltaF,Slope -360 / 1e3 /,units=kHz" \
                 | tee $rootname.proc.phase \
                 | sdds2stream -pipe -par=DeltaF } DeltaF] {
        return -code error "PostProcessData2: $DeltaF"
    }
    SetStatus "DeltaF = $DeltaF kHz"
    set cols [exec sddsquery -col $rootname.proc.filter]
    if [lsearch -exact $cols $data_amp]<0 {
        set data_amp ADC4:SRMuxSig:Mag
        if [lsearch -exact $cols $data_amp]<0 {
            return -code error "Measurement data must have ADC4:SRMuxSig:Amplitude or ADC4:SRMuxSig:Mag column!"
        }
    }
    #calculate QL
    if [catch {exec sddsexpfit $rootname.proc.filter -pipe=out -col=RelativeTime,$data_amp -clue=decays -fullOutput \
                 | sddsprocess -pipe \
                 "-redefine=param,QL,-352e6 pi * expfitRate /" \
                 | tee $rootname.proc.amp \
                 | sdds2stream -pipe -par=QL } QL] {
        return -code error "PostProcessData3: $QL"
    }
    SetStatus "QL = $QL"
    #plot Data
    if [catch {exec sddsprocess -nowarnings $rootname.proc \
                 "-redefine=par,QL,$QL" \
                 "-redefine=par,DeltaF,$DeltaF,units=kHz" \
                 "-reprint=par,DataFile,$filename" } result] {
        return -code error "PostProcessData4: error processing output file: $result"
    }
    
    PlotData1 -filename [file tail $rootname.proc]
}

proc SelectFile {args} {
    global outputDir FileSelection
    cd $outputDir
    set data_phase ADC4:SRMuxSig:Phase
    set data_amp ADC4:SRMuxSig:Amplitude
    #puts [pwd]
    set files [glob -nocomplain *.proc]
    if ![llength $files] {
        SetStatus "No *.proc files found at $outputDir."
        return
    }
    set files [lsort -decreasing $files]
    
    set FileSelection ""
    APSScrolledListWindow .process -name "Booster Cavity Meas" \
	-label "Select a data file" -acceptButton 0 \
	-itemList $files -selectionVar FileSelection
    tkwait variable FileSelection
    if ![string length $FileSelection] {
	return -code error "No file chosen"
    }
    return $FileSelection
}

proc ReprocessData {args} {
    if [catch {SelectFile} files] {
	return -code error "$files"
    }
    foreach file $files {
        set filename [exec sdds2stream -par=DataFile $file]
        SetStatus "reprocessing data $filename ..."
        if [catch {PostProcessData1 -filename $filename } result] {
            return -code error "Error in re-processing data: $result"
        }
    }
    SetStatus "done."
}

proc PlotData {args} {
    global outputDir FileSelection
    cd $outputDir
    if [catch {SelectFile} files] {
	SetStatus "$file"
	return
    }
    foreach file $files {
        PlotData1 -filename $file
    }
}

proc ChangeMux {args} {
    set rf ""
    APSParseArguments {rf}
    
    SetStatus "Switching mux..."
    if [catch {exec cavput -list=SRF:S:srcSelReqMO=$rf  -pend=10} result] {
        return -code error "Error switching mux SRF:S:srcSelReqMO: $result"
    }
    if [catch {exec cawait -waitFor=SRF:S:srcMuxChangingBI,equalTo=0 -timeLimit=20 } result] {
        return -code error "Error switching mux: $result"
    }
    SetStatus "Check signal status ..."
    if [catch {exec cavget -list=SRF:S:RFmux${rf}BI -pend=10 -printErrors -num } muxStatus] {
        return -code error "Error reading SRF:S:RFmux${rf}BI status: $muxStatus"
    }
    if {!$muxStatus} {
        return -code error "RF Mux did not respond properly. Please investigate."
    }
    SetStatus "done."
}


proc PlotData1 {args} {
    set filename ""
    APSParseArguments {filename}
    global outputDir data_phase data_amp
#    set data_phase ADC4:SRMuxSig:Phase
#    set data_amp ADC4:SRMuxSig:Mag
    
    set data_phase ADC4:SRMuxSig:Phase
    set data_amp ADC4:SRMuxSig:Amplitude
    
    set rootname $outputDir/[file root $filename]

    if {![file exist $rootname.proc.amp] \
	    || ![file exist $rootname.proc.phase]} {
	return -code error "Postprocess is not done for $rootname, plot is cancelled."
    }
    set cols [exec sddsquery -col $rootname.proc]
    if [lsearch -exact $cols $data_amp]<0 {
        set data_amp ADC4:SRMuxSig:Mag
        if [lsearch -exact $cols $data_amp]<0 {
            return -code error "Measurement data must have ADC4:SRMuxSig:Amplitude or ADC4:SRMuxSig:Power column!"
        }
    }
    
    set QL [exec sdds2stream -par=QL $rootname.proc]
    set DeltaF [exec sdds2stream -par=DeltaF $rootname.proc]
    set cols [exec sddsquery -col $rootname.proc]
    if [lsearch -exact $cols $data_amp]<0 {
        return -code error "Measurement data must have ADC4:SRMuxSig:Mag column"
    }
#    SetStatus "DeltaF = $DeltaF kHz    QL = $QL"
    SetStatus "Plotting $filename..."

    exec sddsplot -labelSize=0.026 -pspace=0.2,0.92,0.17,0.85 -lspace=0.65,0.85,-0.1,0.9 -layout=2,1 -groupby=page -sep=2,req -split=page \
      -topTitle "-xLabel=Time \[\$gm\$rsec\],scale=0.8,offset=0.02" \
      -factor=xMult=1e6 -tickSettings=xScaleChar=1 \
      -col=RelativeTime,$data_amp  \
      -legend=spec=Data -title=Amplitude,scale=0.95 "-yLabel=\[arb\],scale=1.1" -graphic=symb,type=0,subtype=0,connect=subtype,scale=3 \
      -string=@BoosterRfMuxSourceM,p=0.725,q=1.12,scale=3.8 $rootname.proc.filter \
      -col=RelativeTime,${data_amp}Fit \
      -legend=spec=Fit -graphic=symb,type=2,subtype=1,connect=subtype,scale=2 \
      "-string=@QL,p=0.3,q=0.6,scale=2.5,edit=e4b4ka5fDyai/QL=/"  $rootname.proc.amp \
      -col=RelativeTime,Unwrap$data_phase \
      -topTitle -title=Phase,scale=0.7 \
      "-yLabel=\[deg\],scale=1.4,offset=-0.01" \
      -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 \
      -factor=yMult=-1,xMult=1e6 -legend=spec=Data $rootname.proc.filter \
      -col=RelativeTime,Unwrap${data_phase}Fit \
      -factor=yMult=-1,xMult=1e6 -legend=spec=Fit \
      "-string=DeltaF \[kHz\],p=0.1,q=0.17,scale=2.7" \
      "-string=@DeltaF,p=0.1,q=0.1,scale=2.5,edit=e4b4ka5fDy" $rootname.proc.phase \
      -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 &

    exec sddsplot -pspace=0.2,0.9,0.17,0.9 -labelSize=0.025 -title=@BoosterRfMuxSourceM,scale=1.75,offset=0.01 \
      -topTitle "-xLabel=Time sec,offset=0.01,scale=0.8" \
      -col=RelativeTime,$data_amp "-yLabel=Amp. arb,offset=0.05,scale=0.85" $rootname.proc \
      -col=RelativeTime,Unwrap$data_phase -newPanel -factor=yMult=-1 "-yLabel=Phase deg,offset=0.05,scale=0.85" $rootname.proc &
    return
}

proc PlotData1a {args} {
    set filename ""
    APSParseArguments {filename}
    global outputDir
    set data_phase ADC4:SRMuxSig:Phase
    set data_amp ADC4:SRMuxSig:Amplitude
    
    
    set rootname $outputDir/[file root $filename]

    if {![file exist $rootname.proc.amp] \
	    || ![file exist $rootname.proc.phase]} {
	return -code error "Postprocess is not done for $rootname, plot is cancelled."
    }
    set QL [exec sdds2stream -par=QL $rootname.proc]
    set DeltaF [exec sdds2stream -par=DeltaF $rootname.proc]
     set cols [exec sddsquery -col $rootname.proc]
    if [lsearch -exact $cols $data_amp]<0 {
        set data_amp ADC4:SRMuxSig:Mag
        if [lsearch -exact $cols $data_amp]<0 {
            return -code error "Measurement data must have ADC4:SRMuxSig:Amplitude or ADC4:SRMuxSig:Power column!"
        }
    }
    SetStatus "DeltaF = $DeltaF kHz    QL = $QL"
    SetStatus "Plotting $filename..."
    exec sddsplot -labelSize=0.026 -pspace=0.2,0.92,0.17,0.85 -lspace=0.65,0.85,-0.1,0.9 -layout=2,1 \
      -topTitle "-xLabel=Time \[\$gm\$rsec\],scale=0.8,offset=0.02" \
      -factor=xMult=1e6 -tickSettings=xScaleChar=1 -col=RelativeTime,$data_amp -legend=spec=Data \
      -title=Amplitude,scale=0.95 "-yLabel=\[arb\],scale=1.1" -graphic=symb,type=0,subtype=0,connect=subtype,scale=3 \
      -string=@BoosterRfMuxSourceM,p=0.725,q=1.12,scale=3.8 $rootname.proc.filter \
      -col=RelativeTime,${data_amp}Fit -legend=spec=Fit -graphic=symb,type=2,subtype=1,connect=subtype,scale=2 \
      "-string=@QL,p=0.3,q=0.6,scale=2.5,edit=e4b4ka5fDyai/QL=/"  $rootname.proc.amp \
      -col=RelativeTime,$data_phase -new -topTitle -title=Phase,scale=0.7 \
      "-yLabel=\[deg\],scale=1.4,offset=-0.01" \
      -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 \
      -factor=yMult=-1,xMult=1e6 -legend=spec=Data $rootname.proc.filter \
      -col=RelativeTime,Unwrap${data_phase}Fit -factor=yMult=-1,xMult=1e6 -legend=spec=Fit \
      "-string=DeltaF \[kHz\],p=0.1,q=0.17,scale=2.7" \
      "-string=@DeltaF,p=0.1,q=0.1,scale=2.5,edit=e4b4ka5fDy" $rootname.proc.phase \
      -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 &

    #exec sddsplot -labelSize=0.026 -pspace=0.2,0.92,0.17,0.85 -lspace=0.65,0.85,-0.1,0.9 -layout=2,1 \
    #  -topTitle "-xLabel=Time \[\$gm\$rsec\],scale=0.8,offset=0.02" \
    #  -factor=xMult=1e6 -tickSettings=xScaleChar=1 -col=RelativeTime,$data_amp -legend=spec=Data \
    #  -title=Amplitude,scale=0.95 "-yLabel=\[arb\],scale=0.8" -graphic=symb,type=0,subtype=0,connect=subtype,scale=3 \
    #  -string=@BoosterRfMuxSourceM,p=0.725,q=1.12,scale=3.8 $rootname.proc.filter \
    #  -col=RelativeTime,${data_amp}Fit -legend=spec=Fit -graphic=symb,type=2,subtype=1,connect=subtype,scale=2 \
    #  "-string=@QL,p=0.3,q=0.6,scale=2.5,edit=e4b4ka5fDyai/QL=/"  $rootname.proc.amp \
    #  -col=RelativeTime,$data_phase -new -topTitle -title=Phase,scale=0.7 \
    #  "-yLabel=deg,scale=1.4,offset=-0.01" \
    #  -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 \
    #  -factor=yMult=-1,xMult=1e6 -legend=spec=Data $rootname.proc.filter \
    #  -col=RelativeTime,Unwrap${data_phase}Fit -factor=yMult=-1,xMult=1e6 -legend=spec=Fit \
    #  "-string=DeltaF \[kHz\],p=0.1,q=0.17,scale=2.7" \
    #  "-string=@DeltaF,p=0.1,q=0.1,scale=2.5,edit=e4b4ka5fDy" $rootname.proc.phase \
    #  -graphic=symb,vary=type,vary=subtype,connect=subtype,scale=3 &

    exec sddsplot -pspace=0.2,0.9,0.17,0.9 -labelSize=0.025 -title=@BoosterRfMuxSourceM,scale=1.75,offset=0.01 \
      -topTitle "-xLabel=Time sec,offset=0.01,scale=0.8" \
      -col=TimeFromMute,$data_amp "-yLabel=Amp. arb,offset=0.05,scale=0.85" $rootname.proc \
      -col=TimeFromMute,Unwrap$data_phase -newPanel -factor=yMult=-1 "-yLabel=Phase deg,offset=0.05,scale=0.85" $rootname.proc &

    return
    
}

set Time_start 0
#set Time_length 0.0006

set Time_length 75

set outputDir [APSGoToDailyDirectory -subdirectory boosterCavityDetuning]

set description "testing"
APSLabeledEntry .dir -parent .userFrame -label "Output directory:" -textVariable outputDir -width 75 -fileSelectDirectory 1 -fileSelectButton 1 -buttonsOnLeft 1
APSLabeledEntry .desc -parent .userFrame -label "Comments:" -textVariable description -width 75
set blankingDelay 261.5
set blankingWide 15
APSFrameGrid .grid -parent .userFrame -xList {x1 x2}
set w1 .userFrame.grid.x1
set w2 .userFrame.grid.x2
APSLabeledEntry .delay -parent $w1 -textVariable blankingDelay -label "Blanking delay (msec):" -width 25
APSLabeledEntry .delay -parent $w2 -textVariable blankingWide -label "Blanking width (msec):" -width 25
set preTrigger 0.5
set postTrigger 0.5
APSLabeledEntry .pretrig -parent $w1 -textVariable preTrigger -label "Pre-trigger (sec):" -width 25
APSLabeledEntry .posttrig -parent $w2 -textVariable postTrigger -label "Post-trigger(sec):" -width 25
APSLabeledEntry .tstart -parent $w1 -textVariable Time_start -label "Time offset to start fit (usec):" -width 25
APSLabeledEntry .tlen -parent $w2 -textVariable Time_length -label "Time length of fit (usec):" -width 25

set rfSignal 1
APSRadioButtonFrame .rf -parent .userFrame -variable rfSignal -label "Choose RF signal to collect"\
  -buttonList {"Booster Cavity 1" "Booster Cavity 2" "Booster Cavity 3" "Booster Cavity 4" "Booster RF Sum"} \
    -valueList {1 2 3 4 5} -commandList {"ChangeMux -rf 1" "ChangeMux -rf 2" "ChangeMux -rf 3" "ChangeMux -rf 4" "ChangeMux -rf 5"}

if [pv linkw blankingStatus BRF:K5:brf_blankingDly2.GATE] {
    puts stderr "Error connecting BRF:K5:brf_blankingDly2.GATE: $errorCode"
    exit 1
}
if [pv umon blankingStatus] {
    puts stderr "Error monitoring blanking status pv: $errorCode"
    exit 1
}
pv getw blankingStatus
APSFrameGrid .f2 -parent .userFrame -xList {x1 x2 x3}
APSLabeledOutput .blankingStatus -parent .userFrame.f2.x1 -label "Blanking status"  \
    -textVariable blankingStatus -width 15

#APSLabeledEntry .length -parent .userFrame.f2.x2 -textVariable Time_length -label "Data length (usec):" -width 15

APSButton .blanking -parent .userFrame -text "Turn on RF Blanking" -command "TurnOnRFBlanking"
APSButton .off -parent .userFrame -text "Turn off RF Blanking" -command "exec cavput -list=BRF:K5:brf_blankingDly2.GATE=0 -pend=10"
APSButton .acquire -parent .userFrame -text "Acquire Data" -command "AcquireData"
APSButton .process -parent .userFrame -text "Reprocess Data" -command "ReprocessData"
APSButton .plot -parent .userFrame -text "Plot Data" -command "PlotData"

#setup daq IOC variable environment
#set env(EPICS_CA_ADDR_LIST) "ctlsdaqsrv1 iocrtfbdaq ctlsdaqdev2 ctlsdaqdev6  ctlsdaqdev1.aps4.anl.gov CTLAPPS8-VM"
set env(EPICS_CA_ADDR_LIST) ctlsdaqdev6
set env(EPICS_CA_MAX_ARRAY_BYTES) 2500000

#setup daq IOC variable environment
#if [regexp "csh" $env(SHELL)] {
#    exec /bin/csh /net/helios/ctlsdaq1/prod/setup.csh 
#} elseif [regexp "bash" $env(SHELL)] {
#    exec /bin/sh /net/helios/ctlsdaq1/prod/setup.sh 
#}

if [catch {exec cavget -list=DAQ:SRRF:HISTORY:TCP:PreTriggerTimeC -printErrors -pend=10} result] {
    APSInfoWindow .info -infoMessage "Error reading DAQ:SRRF:HISTORY:TCP:PreTriggerTimeC: $result \n check if the IOC is correctly connected." -modal 1
}
if [catch {exec sddscasr -save /home/helios/oagData/SCR/requestFiles/BoosterCavity.req $outputDir/InitSCR.sdds } result] {
    puts stderr "Error saving initial condition: $result,  check if the IOC is correctly setup"
    exit 1
}
exec medm -x -attach  -dg +3000+100  /usr/local/iocapps/adlsys/rf/miscApp/rfSourceMux.adl &
exec medm -x -attach -dg +4000+100  /usr/local/iocapps/adlsys/rf/vmeApp/BlankingDelay.adl &
update
APSInfoWindow .info -name "Warning" -infoMessage "This application is for development ONLY.\nContact Tim Berenc and Ned Arnold before using.\nThis program uses RF blanking in the Booster. Be careful." -modal 1

#set outputDir /home/helios/BERENC/daily/1610/17/2/boosterCavityDetuning
