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

APSApplication  . -name BoosterTestRamps
set status "Autocorrection should be running on this workstation because the intermediate\nramp files will be in the /tmp directory of this workstation only.\n\nReady..."

APSScrolledStatus .status -parent .userFrame -textVariable status -height 15 -width 50 -packOption {-side top -fill x}

set referenceRamp /home/helios/oagData/booster/ramps/IRamp/current-IRamp/IRef
set type [file type $referenceRamp]
while {$type == "link"} {
    set referenceRamp [file readlink $referenceRamp]
    if {![file exists $referenceRamp]} {
        set referenceRamp [file join /home/helios/oagData/booster/ramps/IRamp/current-IRamp $referenceRamp]
    }
    set type [file type $referenceRamp]
}
set installedRamp $referenceRamp
set testRamp /home/helios/OAG/oagData/booster/ramps/psTestRamps/IRef-test-000
set steps 10

ttk::frame .userFrame.f1
pack .userFrame.f1 -fill x -padx 2 -pady 5

ttk::label .userFrame.f1.refRampLabel -text "Reference Ramp: "
ttk::entry .userFrame.f1.refRampEntry -textvariable referenceRamp -state readonly -width 60
APSButton .refRampPlotButton -parent .userFrame.f1 -text Plot -size small -gridPack "-row 0 -column 2 -sticky w" -command "Plot -mode reference"
grid .userFrame.f1.refRampLabel -row 0 -column 0 -sticky e
grid .userFrame.f1.refRampEntry -row 0 -column 1 -sticky w

ttk::label .userFrame.f1.installedRampLabel -text "Installed Ramp: "
ttk::entry .userFrame.f1.installedRampEntry -textvariable installedRamp -state readonly -width 60
APSButton .installedRampPlotButton -parent .userFrame.f1 -text Plot -size small -gridPack "-row 1 -column 2 -sticky w" -command "Plot -mode installed"
grid .userFrame.f1.installedRampLabel -row 1 -column 0 -sticky e
grid .userFrame.f1.installedRampEntry -row 1 -column 1 -sticky w

ttk::label .userFrame.f1.testRampLabel -text "Test Ramp: "
ttk::entry .userFrame.f1.testRampEntry -textvariable testRamp -width 60
APSButton .testRampPlotButton -parent .userFrame.f1 -text Plot -size small -gridPack "-row 2 -column 2 -sticky w" -command "Plot -mode test"
APSButton .testRampSelect -parent .userFrame.f1 -text F -size small -gridPack "-row 2 -column 3 -sticky w" -command "GetTestRamp"
grid .userFrame.f1.testRampLabel -row 2 -column 0 -sticky e
grid .userFrame.f1.testRampEntry -row 2 -column 1 -sticky w

ttk::label .userFrame.f1.stepsLabel -text "Steps: "
ttk::entry .userFrame.f1.stepsEntry -textvariable steps -width 10
grid .userFrame.f1.stepsLabel -row 3 -column 0 -sticky e
grid .userFrame.f1.stepsEntry -row 3 -column 1 -sticky w

ttk::frame .userFrame.f2
pack .userFrame.f2 -fill x -padx 2
ttk::frame .userFrame.f3
pack .userFrame.f3 -fill x -padx 2

APSButton .plotSteps -parent .userFrame.f2 -text "Plot Ramp Steps" -width "" -command "Plot -mode steps"
APSButton .startRampChange -parent .userFrame.f3 -text "Start Ramp Change" -width "" -command "Ramp -mode Start"
APSButton .continueRampChange -parent .userFrame.f3 -text "Continue Ramp Change" -width "" -command "Ramp -mode Continue"
APSButton .previousRampChange -parent .userFrame.f3 -text "Step Back Ramp Change" -width "" -command "Ramp -mode StepBack"
.userFrame.f3.continueRampChange.button configure -state disabled
.userFrame.f3.previousRampChange.button configure -state disabled

proc GetTestRamp {args} {
    global testRamp
    set f [APSFileSelectDialog .fs -path /home/helios/OAG/oagData/booster/ramps/psTestRamps -pattern IRef-test-???]
    if {[file exists $f]} {
        set testRamp $f
    }
}

proc Plot {args} {
    global referenceRamp installedRamp testRamp steps
    APSStrictParseArguments {mode}
    if {$mode == "reference"} {
        if {![file exists $referenceRamp]} {
            APSSetVarAndUpdate status "Reference ramp file does not exist"
            bell
            return
        }
        exec sddsplot "-topline=Reference Ramp" -split=page -sep=namestring $referenceRamp -column=Index,(B:BM:CurrentWF,B:QF:CurrentWF,B:QD:CurrentWF,B:SF:CurrentWF,B:SD:CurrentWF) -column=time,(BM-I,QF-I,QD-I,SF-I,SD-I) &
    }
    if {$mode == "installed"} {
        if {![file exists $installedRamp]} {
            APSSetVarAndUpdate status "Installed ramp file does not exist"
            bell
            return
        }
        exec sddsplot "-topline=Installed Ramp" -split=page -sep=namestring $installedRamp -column=Index,(B:BM:CurrentWF,B:QF:CurrentWF,B:QD:CurrentWF,B:SF:CurrentWF,B:SD:CurrentWF) -column=time,(BM-I,QF-I,QD-I,SF-I,SD-I) &
    }
    if {$mode == "test"} {
        if {![file exists $testRamp]} {
            APSSetVarAndUpdate status "Test ramp file does not exist"
            bell
            return
        }
        exec sddsplot "-topline=Test Ramp" -split=page -sep=namestring $testRamp -column=Index,(B:BM:CurrentWF,B:QF:CurrentWF,B:QD:CurrentWF,B:SF:CurrentWF,B:SD:CurrentWF) -column=time,(BM-I,QF-I,QD-I,SF-I,SD-I) &
    }
    if {$mode == "steps"} {
        if {[catch {PrepareTestWaveforms} results]} {
            bell
            return
        }
        set outputFiles ""
        for {set s 1} {$s < $steps} {incr s} {
            lappend outputFiles /tmp/IRef-test.step$s
        }
        set plotcommand ""
        foreach col "B:BM:CurrentWF B:QF:CurrentWF B:QD:CurrentWF B:SF:CurrentWF B:SD:CurrentWF" {
            append plotcommand "-column=Index,$col $installedRamp -graph=line,type=0 -legend=specified=Installed "
            for {set s 1} {$s < $steps} {incr s} {
                append plotcommand "-column=Index,$col /tmp/IRef-test.step$s -graph=line,type=2 "
            }
            append plotcommand "-column=Index,$col $testRamp -graph=line,type=1 -legend=specified=Test "
        }
        foreach col "BM-I QF-I QD-I SF-I SD-I" {
            append plotcommand "-column=time,$col $installedRamp -graph=line,type=0 -legend=specified=Installed "
            for {set s 1} {$s < $steps} {incr s} {
                append plotcommand "-column=time,$col /tmp/IRef-test.step$s -graph=line,type=2 "
            }
            append plotcommand "-column=time,$col $testRamp -graph=line,type=1 -legend=specified=Test "
        }

        eval exec sddsplot -sep=namestring $plotcommand &
    }
    APSSetVarAndUpdate status "Data plotted."
}

proc SuspendBControl {args} {
    set magnets {BM QF QD SF SD}
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Suspend} results]} {
            APSSetVarAndUpdate status "Problem occurred while suspending $magnet bcontrol controllaw\n$results"
            return -code error
	}
    }
}
proc ResumeBControl {args} {
    set magnets {BM QF QD SF SD}
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Resume} results]} {
            APSSetVarAndUpdate status "Problem occurred while resuming $magnet bcontrol controllaw\n$results"
            return -code error
	}
    }
}
proc LinkRampFile {args} {
    global currentStep initialRamp installedRamp testRamp steps
    if {$currentStep == 0} {
        set pwd [pwd]
        cd /home/helios/oagData/booster/ramps/IRamp/current-IRamp
        file delete -force IRef
        file link -symbolic IRef $initialRamp
        set installedRamp $initialRamp
        cd $pwd
    } elseif {$currentStep == $steps} {
        set pwd [pwd]
        cd /home/helios/oagData/booster/ramps/IRamp/current-IRamp
        file delete -force IRef
        file link -symbolic IRef $testRamp
        set installedRamp $testRamp
        cd $pwd
    } else {
        set pwd [pwd]
        cd /home/helios/oagData/booster/ramps/IRamp/current-IRamp
        file delete -force IRef
        file link -symbolic IRef /tmp/IRef-test.step$currentStep
        set installedRamp /tmp/IRef-test.step$currentStep
        cd $pwd
    }
}

proc Ramp {args} {
    global currentStep steps initialRamp installedRamp
    APSStrictParseArguments {mode}
    if {$mode == "Start"} {
        set answer [tk_messageBox -message "Are you sure you want to change the ramp?" -type yesno -icon question]
        if {$answer != "yes"} {
            return
        }
        set currentStep 1
        set initialRamp $installedRamp
    } elseif {$mode == "Continue"} {
        incr currentStep
    } elseif {$mode == "StepBack"} {
        incr currentStep -1
    }
    .userFrame.f3.startRampChange.button configure -state disabled
    .userFrame.f3.continueRampChange.button configure -state disabled
    .userFrame.f3.previousRampChange.button configure -state disabled

    if {$mode == "Start"} {
        APSSetVarAndUpdate status "Calculating the ramps for all steps"
        if {[catch {PrepareTestWaveforms} results]} {
            bell
            .userFrame.f3.startRampChange.button configure -state normal
            .userFrame.f3.continueRampChange.button configure -state disabled
            .userFrame.f3.previousRampChange.button configure -state disabled
            return
        }
    }

    APSSetVarAndUpdate status "Suspending bcontrol controllaws"
    if {[catch {SuspendBControl} results]} {
        bell
        .userFrame.f3.startRampChange.button configure -state normal
        .userFrame.f3.continueRampChange.button configure -state disabled
        .userFrame.f3.previousRampChange.button configure -state disabled
        return
    }

    APSSetVarAndUpdate status "Loading ramps for step \#$currentStep"
    LinkRampFile

    APSSetVarAndUpdate status "Resuming bcontrol controllaws"
    if {[catch {ResumeBControl} results]} {
        bell
        .userFrame.f3.startRampChange.button configure -state normal
        .userFrame.f3.continueRampChange.button configure -state disabled
        .userFrame.f3.previousRampChange.button configure -state disabled
        return
    }

    if {$currentStep == $steps} {
        APSSetVarAndUpdate status "Finished loading test ramp\n"
        .userFrame.f3.startRampChange.button configure -state normal
        .userFrame.f3.continueRampChange.button configure -state disabled
        .userFrame.f3.previousRampChange.button configure -state disabled
    } elseif {$currentStep == 0} {
        APSSetVarAndUpdate status "Finished loading reference ramp\n"
        .userFrame.f3.startRampChange.button configure -state normal
        .userFrame.f3.continueRampChange.button configure -state disabled
        .userFrame.f3.previousRampChange.button configure -state disabled
    } else {
        APSSetVarAndUpdate status "Pausing until the user presses Continue\n"
        .userFrame.f3.continueRampChange.button configure -state normal
        .userFrame.f3.previousRampChange.button configure -state normal\
    }
}

proc PrepareTestWaveforms {args} {
    global referenceRamp installedRamp testRamp steps
    if {$steps < 2} {
        APSSetVarAndUpdate status "Steps must be 1 or more"
        return -code error
    }
    if {![file exists $referenceRamp]} {
        APSSetVarAndUpdate status "Reference ramp file does not exist"
        return -code error
    }
    set installedRamp /home/helios/oagData/booster/ramps/IRamp/current-IRamp/IRef
    set type [file type $installedRamp]
    while {$type == "link"} {
        set installedRamp [file readlink $installedRamp]
        if {![file exists $installedRamp]} {
            set installedRamp [file join /home/helios/oagData/booster/ramps/IRamp/current-IRamp $installedRamp]
        }
        set type [file type $installedRamp]
    }
    if {![file exists $installedRamp]} {
        APSSetVarAndUpdate status "Installed ramp file does not exist"
        return -code error
    }
    if {![file exists $testRamp]} {
        APSSetVarAndUpdate status "Test ramp file does not exist"
        return -code error
    }
    
    #Use the installed ramp instead of the reference ramp because we might be going from one test ramp to another.
    sdds load $installedRamp refRamp
    sdds load $testRamp tRamp
    set refBMWaveform [lindex $refRamp(Column.B:BM:CurrentWF) 0]
    set testBMWaveform [lindex $tRamp(Column.B:BM:CurrentWF) 0]
    set refQFWaveform [lindex $refRamp(Column.B:QF:CurrentWF) 0]
    set testQFWaveform [lindex $tRamp(Column.B:QF:CurrentWF) 0]
    set refQDWaveform [lindex $refRamp(Column.B:QD:CurrentWF) 0]
    set testQDWaveform [lindex $tRamp(Column.B:QD:CurrentWF) 0]
    set refSFWaveform [lindex $refRamp(Column.B:SF:CurrentWF) 0]
    set testSFWaveform [lindex $tRamp(Column.B:SF:CurrentWF) 0]
    set refSDWaveform [lindex $refRamp(Column.B:SD:CurrentWF) 0]
    set testSDWaveform [lindex $tRamp(Column.B:SD:CurrentWF) 0]
    set refBMI [lindex $refRamp(Column.BM-I) 0]
    set testBMI [lindex $tRamp(Column.BM-I) 0]
    set refQFI [lindex $refRamp(Column.QF-I) 0]
    set testQFI [lindex $tRamp(Column.QF-I) 0]
    set refQDI [lindex $refRamp(Column.QD-I) 0]
    set testQDI [lindex $tRamp(Column.QD-I) 0]
    set refSFI [lindex $refRamp(Column.SF-I) 0]
    set testSFI [lindex $tRamp(Column.SF-I) 0]
    set refSDI [lindex $refRamp(Column.SD-I) 0]
    set testSDI [lindex $tRamp(Column.SD-I) 0]
    
    set outputFiles ""
    for {set s 1} {$s < $steps} {incr s} {
        set bmWaveform ""
        set qfWaveform ""
        set qdWaveform ""
        set sfWaveform ""
        set sdWaveform ""
        set bmI ""
        set qfI ""
        set qdI ""
        set sfI ""
        set sdI ""
        foreach ref $refBMWaveform test $testBMWaveform {
            set value [expr round($ref + ($s * ($test - $ref) / (1.0 * $steps)))]
            lappend bmWaveform $value
        }
        set tRamp(Column.B:BM:CurrentWF) [list $bmWaveform]
        foreach ref $refQFWaveform test $testQFWaveform {
            set value [expr round($ref + ($s * ($test - $ref) / (1.0 * $steps)))]
            lappend qfWaveform $value
        }
        set tRamp(Column.B:QF:CurrentWF) [list $qfWaveform]
        foreach ref $refQDWaveform test $testQDWaveform {
            set value [expr round($ref + ($s * ($test - $ref) / (1.0 * $steps)))]
            lappend qdWaveform $value
        }
        set tRamp(Column.B:QD:CurrentWF) [list $qdWaveform]
        foreach ref $refSFWaveform test $testSFWaveform {
            set value [expr round($ref + ($s * ($test - $ref) / (1.0 * $steps)))]
            lappend sfWaveform $value
        }
        set tRamp(Column.B:SF:CurrentWF) [list $sfWaveform]
        foreach ref $refSDWaveform test $testSDWaveform {
            set value [expr round($ref + ($s * ($test - $ref) / (1.0 * $steps)))]
            lappend sdWaveform $value
        }
        set tRamp(Column.B:SD:CurrentWF) [list $sdWaveform]

        foreach ref $refBMI test $testBMI {
            set value [expr $ref + ($s * ($test - $ref) / (1.0 * $steps))]
            lappend bmI $value
        }
        set tRamp(Column.BM-I) [list $bmI]
        foreach ref $refQFI test $testQFI {
            set value [expr $ref + ($s * ($test - $ref) / (1.0 * $steps))]
            lappend qfI $value
        }
        set tRamp(Column.QF-I) [list $qfI]
        foreach ref $refQDI test $testQDI {
            set value [expr $ref + ($s * ($test - $ref) / (1.0 * $steps))]
            lappend qdI $value
        }
        set tRamp(Column.QD-I) [list $qdI]
        foreach ref $refSFI test $testSFI {
            set value [expr $ref + ($s * ($test - $ref) / (1.0 * $steps))]
            lappend sfI $value
        }
        set tRamp(Column.SF-I) [list $sfI]
        foreach ref $refSDI test $testSDI {
            set value [expr $ref + ($s * ($test - $ref) / (1.0 * $steps))]
            lappend sdI $value
        }
        set tRamp(Column.SD-I) [list $sdI]


        sdds save /tmp/IRef-test.step$s tRamp
        lappend outputFiles /tmp/IRef-test.step$s
        APSAddToTempFileList /tmp/IRef-test.step$s
    }
}
