#!/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.0 $ \$Author: shang $"


proc SetStatus {text} {
    global status
    set status "[exec date +%H:%M:%S]: $text"
    update
}

proc BringupADT {args} {
    global region

    exec adt -geometry +30+0 -f /home/helios/OAG/oagData/ADTFiles/booster/booster.bpm.pv-${region}.pv -z 3 -d &
}

proc SetStartEndBump {args} {
    global region StartBumpList EndBumpList 

    set index [scan $region region%ld]
    set StartBump [lindex $StartBumpList $index]
    set EndBump [lindex $EndBumpList $index]
    
    if [catch {exec cavput -list=B:CorrBumpStart=$StartBump,B:CorrBumpEnd=$EndBump -pend=30} result] {
        return -code error "Error setting start and end ramp pvs: $result"
    }
}

set IRampDir /home/helios/oagData/booster/ramps
proc StartMeasurement {args} {
    set archive 0
    APSParseArguments {archive}
    
    global region plane sector amplitude outputDir waitTime archiveDir IRampDir
    
    set adtFile /home/helios/OAG/oagData/ADTFiles/booster/booster.bpm.pv-${region}.pv 
    set lattice [file readlink $IRampDir/IRamp]
    set corr ${sector}$plane
    set rootname [clock format [clock seconds] -format %Y-%m%d-%H%M%S].$corr.$region
    cd $outputDir
    SetStatus "Setting start and end ramp time ..."
    if [catch {SetStartEndBump} result] {
        SetStatus "Error setting start and end bump: $result"
        return
    }
    SetStatus "Load reference ramp..."
    if [catch {exec ramploadnew /home/helios/oagData/booster/ramps/correctors/lattices/default/HVCorr.ramp } result] {
        SetStatus "Error loadig reference ramp..."
    }
    SetStatus "Waiting for orbit converging..."
    APSWaitWithUpdate -waitSeconds $waitTime
    SetStatus "Save orbit before starting corrector bump..."
    if ![file exist ${plane}-$region.mon] {
        if [catch {exec sddsprocess $adtFile "-match=par,ADTHeading=BOOSTER $plane *" ${plane}-$region.mon } result] {
            SetStatus "Error generating monitor file $plane $region: $result"
            return
        }
    }
    if [catch {exec sddscasr ${plane}-$region.mon -pipe=out -save \
                 | sddsprocess -pipe=in $rootname.orbit0 \
                 -scan=col,Orbit0,ValueString,%lf } result] {
        SetStatus "Error reading orbit0: $result"
        return
    }
    SetStatus "Do $corr bump with $amplitude amplitude..."
    if [catch {exec SetBoosterSingleBumpAmplitude -sector $sector -plane $plane -load 1 \
                 -outDir $outputDir } result] {
        SetStatus "Error creating bump for $corr : $result"
        return
    }
    exec mv $corr.ramp $rootname.$corr.ramp
    SetStatus "Waiting for orbit converging..."
    APSWaitWithUpdate -waitSeconds $waitTime
    SetStatus "Save orbit after bump..."
    if [catch {exec sddscasr ${plane}-$region.mon -pipe=out -save \
                 | sddsprocess -pipe -scan=col,Orbit1,ValueString,%lf \
                 | sddsxref -pipe $rootname.orbit0 -take=Orbit0 \
                 | sddsprocess -pipe=in "-define=col,Index,i_row 80.0 /,type=double"  \
                 "-redefine=col,Diff,Orbit1 Orbit0 -" $rootname.orbit } result] {
        SetStatus "Error processing orbit: $result"
        return
    }
    SetStatus "Restore reference ramp..."
    if [catch {exec ramploadnew /home/helios/oagData/booster/ramps/correctors/lattices/default/HVCorr.ramp } result] {
        SetStatus "Error loadig reference ramp..."
    }
    
    if [catch {exec sddsfft $rootname.orbit $rootname.orbit.fft -col=Index,Diff } result] {
        SetStatus "Error doing fft: $result"
        return
    }
    if [catch {exec sddspeakfind $rootname.orbit.fft -col=FFTDiff -pipe=out \
                 | sddsprocess -pipe -process=FFTDiff,max,IntegerTune,pos,functionof=f \
                 | sdds2stream -pipe -par=IntegerTune } integerTune] {
        SetStatus "Error processing tune: $integerTune"
        return
    }
    set integerTune [format %.0f $integerTune]
    SetStatus "$plane plane nearest integer tune = $integerTune"
    if [catch {exec sddsprocess $rootname.orbit.fft $rootname.proc "-print=par,TuneDesc,$plane plane nearest integer tune = $integerTune"  \
             "-define=col,IntegerTune,f" -print=par,Region,$region -define=par,BumpAplitude,$amplitude  \
             "-print=par,Lattice,$lattice"} result] {
        SetStatus "Error processing file: $result"
        return
    }
    if $archive {
        exec cp  $rootname.orbit $archiveDir/$rootname.orbit
        exec cp  $rootname.proc $archiveDir/$rootname.proc
    }
    SetStatus "done."
    
    exec sddsplot -col=IntegerTune,FFTDiff -topline=@TuneDesc $rootname.proc &
}

proc PlotFile {args} {
    set archive 0
    APSParseArguments {archive}
    global outputDir archiveDir

    if $archive {
        set dir $archiveDir
    } else {
        set dir $outputDir
    }
    set files [glob -nocomplain $dir/*.proc] 

    if ![llength $files] {
        SetStatus "No proc files found in $dir."
        return
    }
    
    set filename [APSFileSelectDialog [APSUniqueName .] -width 100 -listDir $dir -reverseSort 1 -listFilter *.proc]
    if ![string length $filename] {
        return
    }
    exec sddsplot -col=IntegerTune,FFTDiff -topline=@TuneDesc  $filename &

}


set StartBumpList {0    34.0 56.5 79.0 101.5 124.0 146.5 169.0 191  214.0}
set EndBumpList   {29.0 51.5 74   96.5 119   141.5 164.0 186   209  240.0}
set archiveDir /home/helios/oagData/booster/tuneArchive/integerTune

APSApplication . -name MeasureBoosterIntegerTune -version $CVSRevisionAuthor \
  -overview {Helps with booster tune measurement setup and data collection.}

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
  -width 60 -height 6
update
set plane H
APSRadioButtonFrame .plane -parent .userFrame -label "Plane:      "  -buttonList {H V} -valueList {H V} -variable plane -orientation horizontal

set waitTime 10
set sector B1C0
set itemList {B1C0 B1C1 B1C2 B1C3 B1C4 B1C5 B1C6 B1C7 B1C8 B1C9 \
                B2C0 B2C1 B2C2 B2C3 B2C4 B2C5 B2C6 B2C7 B2C8 B2C9 \
                B3C0 B3C1 B3C2 B3C3 B3C4 B3C5 B3C6 B3C7 B3C8 B3C9 \
                B4C0 B4C1 B4C2 B4C3 B4C4 B4C5 B4C6 B4C7 B4C8 B4C9 }
APSRadioButtonFrame .sector -parent .userFrame -label "Sector:     " -buttonList $itemList -valueList $itemList -variable sector \
  -orientation horizontal -limitPerRow 10
set region region0
set regionList {region0 region1 region2 region3 region4 region5 region6 region7 region8 region9}
APSRadioButtonFrame .region -parent .userFrame -label "Ramp region:" -buttonList $regionList -valueList $regionList \
  -variable region -orientation horizontal -limitPerRow 5

APSFrameGrid .grid -parent .userFrame -xList {x1 x2}

set amplitude 1.0
APSLabeledEntry .amp -parent .userFrame.grid.x1 -label "Bump amplitude (-1.5 to 1.5):" -width 25 -textVariable amplitude
APSLabeledEntry .wait -parent .userFrame.grid.x2 -label "Wait time after ramp loading (seconds):" -width 25 -textVariable waitTime

set outputDir [APSGoToDailyDirectory -subdirectory booIntegerTune]
APSLabeledEntry .dir -parent .userFrame -label "Output directory:       " -textVariable outputDir \
  -width 100

APSButton .adt -parent .userFrame -text "Start ADT" -command "BringupADT"
APSButton .start -parent .userFrame -text "Measure Only" -command "StartMeasurement -archive 0"
APSButton .start1 -parent .userFrame -text "Measure and Archive" -command "StartMeasurement -archive 1"
APSButton .plot -parent .userFrame -text "Plot" -command "PlotFile"
APSButton .plot1 -parent .userFrame -text "Plot Archive" -command "PlotFile -archive 1"



