
proc ReturnFromRampCorrection {args} {
    set error ""
    set supply ""
    APSStrictParseArguments {error supply}
    #first unlock ramp
    if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=0 -pend=10} result] {
        return -code error "Unable to unlock $supply: $result"
    }
    return -code error "$error"
}
proc BoosterRampVCorrectAndCheck {args} {
    set supply ""
    set application ""
    set user ""
    set host ""
    set statusCallback ""
    set runControlPV ""
    set LLTime1 ""
    set LTime1 ""
    APSStrictParseArguments {supply application user host runControlPV LLTime1 LTime1 statusCallback} 
    
    global apsScriptUser apsScriptHost apsScriptCommand
    if ![string length $supply] {
        return -code error "BoosterRampVCorrectAndCheck(1): No supply provided."
    }
    if ![string length $user] {
        set user $apsScriptUser
    }
    if ![string length $host] {
        set host $apsScriptHost
    }
    if ![string length $application] {
        set application $apsScriptCommand
    }
    if {$statusCallback!=""} {
        $statusCallback "$supply supply selected..."
    }
    
    set boosterFileDir  /home/helios/oagData/booster/ramps/VRamp/current
    set boosterSafetyFileDir /home/helios/oagData/booster/ramps/VRamp/safety
    set boosterErrorFileDir /home/helios/oagData/booster/rampLogFiles/VRamp/rampErrLogFiles
    set filtFile $boosterFileDir/40.180.3.coeffs
    set convFile $boosterFileDir/conv${supply}.sdds
    set parFile /home/helios/oagData/booster/ramps/VRamp/rampParameters.sdds
    set tmpFile /tmp/[APSTmpString]
    
    if [catch {exec sddsprocess $parFile $tmpFile -match=par,Supply=$supply} result] {
        return -code error "BoosterRampVCorrectAndCheck(2): sddsprocess -- error in finding $supply in $parFile: $result"
    }
    
    set variableNames [exec sdds2stream -col=VariableName $tmpFile]
    set values [exec sdds2stream -col=Value $tmpFile]
    file delete -force $tmpFile
    foreach var $variableNames value $values {
        set $var $value
    }
    set gainStart [exec rpnl $gainStartFactor $Vscale /]
    set gainStop [exec rpnl $gainStopFactor $Vscale /]
    # set sparse [format %.0f $sparse]
    # set smoothPt [format %.0f $smoothPt]
    # set filtDelay [format %.0f $filtDelay]
    # set smoothPass [format %.0f $smoothPass]
    # set npoints [format %.0f $npoints]
    #use the value from input if there is.
    if [string length $LLTime1] {
        set LLTime $LLTime1
    }
    if [string length $LTime1] {
        set LTime $LTime1
    }
    set fileList ""
    set tmpstring [APSTmpString]
    set rampLinkDir [file readlink /home/helios/oagData/booster/ramps/VRamp]
    set outDir /home/helios/oagData/booster/rampLogFiles/VRamp/rampCorrectionLogFiles
    set outDir $outDir/[clock format [clock seconds] -format %Y-%m%d]
    
    if ![file exist $outDir] {
        after 1000
        catch {exec mkdir $outDir}
    }
    set newMagRampFile /tmp/${supply}new${tmpstring}.afg100
    set newMagRampFile1 $outDir/${supply}new${tmpstring}.afg100
    lappend fileList $newMagRampFile
    set logMagRampFile $outDir/${supply}log${tmpstring}.file
    lappend fileList $logMagRampFile
    set currentFile /tmp/${supply}current${tmpstring}.file
    lappend fileList $currentFile
    set convFile $boosterFileDir/conv${supply}.sdds
    
    set timeout [expr [clock seconds] + 10]
    while {[clock seconds]<$timeout} {
        if [file exist $boosterFileDir/${supply}Vref.afg100] {
            break
        }
        after 1000
    }
    if ![file exist $boosterFileDir/${supply}Vref.afg100] {
        return -code error "BoosterRampVcorrectAndCheck3: $boosterFileDir/${supply}Vref.afg100 does not exist!"
    }
    if [string length $runControlPV] {
        if [catch {PingRunControl -runControlPV $runControlPV} result] {
            return -code error "BoosterRampVcorrectAndCheck5 -Error of PingRunControl in VcorrectAndCheck before starting: $result"
        }
    }
    #lock the ramp so that bcontrol won't change the parameter during ramp correction
    if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=1 -pend=10} result] {
        return -code error "Unable to lock $supply: $result"
    }
    if [catch {exec fixramplv $boosterFileDir/${supply}Vref.afg100 $newMagRampFile \
                 -currentFile=$currentFile \
                 -logFile=$logMagRampFile \
                 -converter=$convFile,Acoeffs,Bcoeffs \
                 -filter=$filtFile,Acoeffs,Bcoeffs \
                 -fitrange=$fitStart,$fitEnd \
                 -lowtransition=$LLTime,$LTime \
                 -crop=$crop \
                 -hightransition=$HTime,$HHTime \
                 -averageTime=$LAvgTime,$HAvgTime \
                 -sparse=[format %.0f $sparse] \
                 -smooth=[format %.0f $smoothPt],[format %.0f $smoothPass] \
                 -shift=$shift \
                 -gain=$gainStart,$gainStop,$gainCurv \
                 -delay=[format %.0f $filtDelay] \
                 -npoints=[format %.0f $npoints] \
                 -normalize=$normalize } result] {
        ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck6: $result"
    }
    if [catch {exec sddsprocess -nowarning $logMagRampFile \
                 -reprint=par,RampDir,$rampLinkDir } result] {
        ReturnFromRampCorrection -supply $supply -error "Error print RampDir parameter to $logMagRampFile: $result"
    }
    catch { exec rm ${logMagRampFile}~ }
    if {$supply=="BM"} {
        if [catch {exec sddsprocess $currentFile -process=B:${supply}:CurrentWF,max,MaxCurrent -pipe=out \
                     | sdds2stream -pipe -par=MaxCurrent} maxCurrent] {
            ReturnFromRampCorrection -supply $supply -error "error in getting peak current: $maxCurrent"
        }
        if {$maxCurrent<30000} {
            #do not correction if it not is fulll power
            if {$statusCallback!=""} {
                $statusCallback "no correction is done for BM because the power is too low.."
            }
            if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=0 -pend=10} result] {
                return -code error "Unable to unlock $supply: $result"
            }
            catch {exec rm $currentFile  $newMagRampFile $logMagRampFile}
            return
        }
    }
    set dataFileUniqueLabel [APSOffsetDateInfo -today 1 -dateFormat Y-M-D]_[lindex [exec date] 3]
    if [catch {exec sddschanges -pipe=out $newMagRampFile \
                 -changesIn=RampSetpoint \
                 -Baseline=${boosterSafetyFileDir}/${supply}Vref.afg100 \
                 | sddsxref -pipe $newMagRampFile \
                 -take=RampTime,RampSetpoint \
                 -rename=col,RampSetpoint=RampSetpointCorrection \
                 | sddsxref -pipe ${boosterSafetyFileDir}/${supply}Vref.afg100 \
                 -take=RampTime,RampSetpoint \
                 -rename=col,RampSetpoint=RampSetpointSafety \
                 | sddsprocess -pipe -filter=col,RampTime,-200,245 \
                 | sddsprocess -pipe=in /tmp/${supply}Err${dataFileUniqueLabel}.sdds \
                 -process=ChangeInRampSetpoint,maximum,ChangeMax \
                 -process=ChangeInRampSetpoint,maximum,ChangeMaxPos,functionOf=RampTime,position \
                 -process=ChangeInRampSetpoint,minimum,ChangeMin \
                 -process=ChangeInRampSetpoint,minimum,ChangeMinPos,functionOf=RampTime,position \
                 -process=ChangeInRampSetpoint,sigma,ChangeSigma } result] {
        ReturnFromRampCorrection -supply $supply -error "BoosterVcorrectAndCheck7: $result"
    }
    
    if [string length $runControlPV] {
        if [catch {PingRunControl -runControlPV $runControlPV} result] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck7a -Error of PingRunControl in VcorrectAndCheck after processing files: $result"
        }
    }
    # Verify that calculated ramp correction is within bounds as defined by the safety ramp.
    # If not, generate an error, plot and archive the bad data.
    set tmpOutput /tmp/${supply}Err${dataFileUniqueLabel}.sdds
    if [catch {exec sdds2stream -par=ChangeMax $tmpOutput} ChangeMax] {
        ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck8: $ChangeMax"
    }
    set ChangeMax [expr abs($ChangeMax)]
    if [catch {exec sdds2stream -par=ChangeMin $tmpOutput} ChangeMin] {
        ReturnFromRampCorrection -supply $supply -error "BoosterVcorrectAndCheck9: $ChangeMin"
    }
    set ChangeMin [expr abs($ChangeMin)]
    if {$ChangeMax > $ChangeRef || $ChangeMin > $ChangeRef} {
        if [catch {file rename -force /tmp/${supply}Err${dataFileUniqueLabel}.sdds \
                     ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds } result] {
            ReturnFromRampCorrection -supply $supply -error "VcorrectAndCheck7: $result"
        }
        exec sddsplot -graph=line,vary -subticksettings=xdivisions=5,ydivisions=5 \
          -yScalesGroup=namestring "-xLabel=Time (ms)" \
          "-topline=Correction Safety and Difference Voltage Ramps for ${supply}" \
          -col=RampTime,RampSetpointCorrection ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Correction" \
          -col=RampTime,RampSetpointSafety ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Safety" \
          -col=RampTime,ChangeInRampSetpoint ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Difference" \
          -yLabel=Difference &
        if [catch {eval file delete -force $fileList} result] {
            ReturnFromRampCorrection -supply $supply -error  "VcorrectAndCheck7a: error in deleting log files; $result"
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" \
                     -tag=execution VCorrectAndCheck -tag=action Error \
                     -tag=description "Vcorrect Ramp for $supply was corrupted"} result] {
            #ReturnFromRampCorrection -supply $supply -error "logMessage error7: $result"
        }
        if [string length $runControlPV] {  
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(7a) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
        ReturnFromRampCorrection -supply $supply -error  "$supply ramp correction will not be done.  Ramp was corrupted.  Visually check the $supply AFG, voltage and current ramp waveform shape before correcting again."    
    } else {
        if [catch {file delete -force /tmp/${supply}Err${dataFileUniqueLabel}.sdds} result] {
            ReturnFromRampCorrection -supply $supply -error "VcorrectAndCheck8: $result"
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" -tag=execution VCorrectAndCheck -tag=action Start \
                     -tag=description "Start VcorrectAndCheck"} result] {
            #  ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(10) -- logMessage error8: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(10a) -Error of PingRunControl in VcorrectAndCheck before setting glitch pv: $result"
            }
        }
        if [catch {APScavput -list=B:${supply}:Ramp:AutoCorrGlitchBO=1 -pend=20} result] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVCorrectAndCheck(11) -- Error in setting $supply glitch pv: $result"
        }
        
        if [catch {exec sddsprocess "-redefine=col,RampSetpoint,RampTime 5 < RampSetpoint 0 < && pop pop ? 0 : RampSetpoint \$" \
                     $newMagRampFile $newMagRampFile1 } result] {
            ReturnFromRampCorrection -supply $supply  -error  "BoosterRampVCorrectAndCheck(11b) -- Error in reprocessing table: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(11a) -Error of PingRunControl in VcorrectAndCheck before loading ramps: $result"
            }
        }
        if [catch {file copy -force $newMagRampFile1 $boosterFileDir/${supply}Vref.afg100} result] {
            ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(15): $result"
        }
        exec rampload $newMagRampFile
        
        if [catch {APScavput -list=B:${supply}:Ramp:AutoCorrGlitchBO=0 -pend=20} result] {
            ReturnFromRampCorrection -supply $supply  -error  "BoosterRampVCorrectAndCheck(14): Error in setting $supply glitch pv: $result"
        }
        
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error  "BoosterRampVcorrectAndCheck(14a) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
        #do swap/sync if swap/sync server is not running
        if [catch {exec cavget -list=B:SwapSyncRC.RUN -printErrors -pend=20} swap] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14b) -- error reading swap/sync runcontrol: $swap"
        }
        if !$swap {
            #run swap/sync
            if [catch {exec cavput -list=B:${supply}:VoltageRT.SWAP=1 -pend=10} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14c) -- error swaping $supply: $result"
            }
            after 500
            if [catch {exec cavput -list=B:PSAFG100SyncBO=1 -pend=10} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14d) -- error doing sync: $result"
            }
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" -tag=execution VCorrectAndCheck -tag=action End \
                     -tag=description "VcorrectAndCheck completed."} result] {
            #ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(16) -- logMessage error: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error  "BoosterRampVcorrectAndCheck(17) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
    }
    #unlock ramp 
    #after 500
    if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=0 -pend=10} result] {
        return -code error "BoosterRampVCorrectAndCheck(15a): Unable to unlock $supply: $result"
    }
    #remove $newMagRampFile
    catch {exec rm $newMagRampFile $currentFile}
    if {$statusCallback!=""} {
        $statusCallback "$supply supply ramp corrected."
    }
}

proc APSBoosterLoadSafetyRamp {args} {
    set BM 0
    set QD 0
    set QF 0
    set SD 0
    set SF 0
    set Magnet ""
    set statusCallback ""
    set description ""
    set IRamp 0
    APSStrictParseArguments {BM QD QF SD SF statusCallback description Magnet IRamp}
    
    global apsScriptUser apsScriptHost apsScriptCommand
    if $IRamp {
        set rampdir /home/helios/oagData/booster/ramps/IRamp
        set subDir current-IRamp
    } else {
        set rampdir /home/helios/oagData/booster/ramps/VRamp
        set subDir current
    }
    if [string length $Magnet] {
        set $Magnet 1
    }
    if [catch {exec cavget -list=B:SampleperiodAI -pend=20 -printErrors} samplePeriod] {
        return -code error "Error in reading sample period pv B:SampleperiodAI: $samplePeriod"
    }
    foreach magnet {BM QD QF SD SF} {
        if [set $magnet] {
            if [string length $statusCallback] {
                $statusCallback "Loading safety ramp for $magnet..."
            }
            if [catch {exec cavget -list=B:${magnet}:VoltageRT.USEC -pend=20 -printErrors} clockTick] {
                return -code error "Error reading B:${magnet}:VoltageRT.USEC : $clockTick"
            }
            file copy -force $rampdir/$subDir/${magnet}Vref.afg100 $rampdir/$subDir/${magnet}Vref.afg100.old 
            file delete -force $rampdir/$subDir/${magnet}Vref.afg100
            exec cp $rampdir/safety/${magnet}Vref.afg100 $rampdir/$subDir/${magnet}Vref.afg100 
            if [catch {exec logMessage -sourceId=${magnet}AutoCorrection -tag=applicationName "$apsScriptCommand" \
                         -tag=user "$apsScriptUser" -tag=host "$apsScriptHost" -tag=execution LoadSafetyRamp \
                         -tag=action Start -tag=description "$description" } result] {
                #return -code error "Error in logMessage for loading $magnet safety ramp: $result"
            }
            #  exec rampload $rampdir/safety/${magnet}Vref.afg100
            set afgGain [ exec sdds2stream  $rampdir/safety/${magnet}Vref.afg100 -para=afgGain ]
            set afgTrigger [ exec sdds2stream  $rampdir/safety/${magnet}Vref.afg100 -para=afgTrigger]
            set magnet1 [string index $magnet 0][string tolower [string index $magnet 1]]
            if [catch {exec sdds2stream -par=SamplePeriod $rampdir/safety/${magnet}Vref.afg100} samplePeriod0] {
                #does not have this parameter: do nothing
            } else {
                if {[expr abs($samplePeriod -  $samplePeriod0)]>1.0} {
                    return -code error "The sample period in ramp table ($samplePeriod0) does not match current sample period ($samplePeriod)"
                }
            }
            if [catch {exec sdds2stream -par=ClockTick $rampdir/safety/${magnet}Vref.afg100} clockTick0] {
                #does not have this parameter: do nothing
            } else {
                if {[expr abs($clockTick - $clockTick0)]>1} {
                    return -code error "The clockTick in ramp table ($clockTick0) does not match current clockTick ($clockTick)"
                }
            }
            if [catch {exec cavget -list=B:${magnet}:VoltageRT.GAIN} gain] {
                return -code error "Error in reading afg gain: $gain"
            }
            if {[expr abs($gain-$afgGain)/$gain]<0.2} {
                if [catch {exec cavput -list=B:${magnet}:VoltageRT.GAIN=$afgGain -pend=30} result] {
                    return -code error "Error in restore afg gain: $result"
                }
            }
            if [catch {exec cavput -list=It:Bs:${magnet1}VafgTrigAO.VAL=$afgTrigger \
                         -pend=30} result] {
                return -code error "APSBoosterLoadSafetyRamp1: Unable to load $magnet trigger: $result"
            }
            exec rampload $rampdir/safety/${magnet}Vref.afg100
            if [catch {exec cavget -list=B:SwapSyncRC.RUN -printErrors -pend=20} swap] {
                return -code error "APSBoosterLoadSafetyRamp1a -- error reading swap/sync runcontrol: $swap"
            }
            if !$swap {
                #run swap/sync
                if [string length $statusCallback] {
                    $statusCallback "swap/sync..."
                }
                if [catch {exec cavput -list=B:$magnet:VoltageRT.SWAP=1 -pend=20} result] {
                    return -code error "APSBoosterLoadSafetyRamp2: unable to do swap: $result"
                }
                after 500 
                if [catch {exec cavput -list=B:PSAFG100SyncBO=1 -pend=20} result] {
                    return -code error "APSBoosterLoadSafetyRamp3: unable to do sync: $result"
                }
            } else {
                if [string length $statusCallback] {
                    $statusCallback "swap/sync skipped due to swap/sync server running." 
                }
            }
            if [string length $statusCallback] {
                $statusCallback "$magnet safety ramp loaded."
            }
        }
    }
}

proc BoosterRampVCurrentCorrectAndCheck {args} {
    set supply ""
    set application ""
    set user ""
    set host ""
    set statusCallback ""
    set runControlPV ""
    set LLTime1 ""
    set LTime1 ""
    set HTime1 ""
    set HHTime1 ""
    set shift0 ""
    APSStrictParseArguments {supply application user host runControlPV LLTime1 LTime1 shift0 HTime1 HHTime1 statusCallback} 
    
    global apsScriptUser apsScriptHost apsScriptCommand
    if ![string length $supply] {
        return -code error "BoosterRampVCorrectAndCheck(1): No supply provided."
    }
    if ![string length $user] {
        set user $apsScriptUser
    }
    if ![string length $host] {
        set host $apsScriptHost
    }
    if ![string length $application] {
        set application $apsScriptCommand
    }
    if {$statusCallback!=""} {
        $statusCallback "$supply supply selected..."
    }
    set number2Ave 1
    set boosterFileDir  /home/helios/oagData/booster/ramps/IRamp/current-IRamp
    set boosterSafetyFileDir /home/helios/oagData/booster/ramps/IRamp/safety
    set boosterErrorFileDir /home/helios/oagData/booster/rampLogFiles/IRamp/rampErrLogFiles
    # set filtFile $boosterFileDir/40.180.3.coeffs
    set convFile $boosterFileDir/conv${supply}.sdds
    set parFile /home/helios/oagData/booster/ramps/IRamp/rampParametersCurrent.sdds
    set tmpFile /tmp/[APSTmpString]
    
    if [catch {exec sddsprocess $parFile $tmpFile -match=par,Supply=$supply} result] {
        return -code error "BoosterRampVCorrectAndCheck(2): sddsprocess -- error in finding $supply in $parFile: $result"
    }
    
    set variableNames [exec sdds2stream -col=VariableName $tmpFile]
    set values [exec sdds2stream -col=Value $tmpFile]
    file delete -force $tmpFile
    foreach var $variableNames value $values {
        set $var $value
    }
    set filtFile $boosterFileDir/$filtFile
    set filtRows [exec sdds2stream $filtFile -rows=bar]
    set filtDelay [expr $filtRows / 2]
    set gainStart [exec rpnl $gainStartFactor $Vscale /]
    set gainStop [exec rpnl $gainStopFactor $Vscale /]
    # set sparse [format %.0f $sparse]
    # set smoothPt [format %.0f $smoothPt]
    # set filtDelay [format %.0f $filtDelay]
    # set smoothPass [format %.0f $smoothPass]
    # set npoints [format %.0f $npoints]
    #use the value from input if there is.
    if [string length $LLTime1] {
        set LLTime $LLTime1
    }
    if [string length $LTime1] {
        set LTime $LTime1
    }
    if [string length $shift0] {
        set shift $shift0
    }
    if [string length $HTime1] {
        set HTime $HTime1
    }
    if [string length $HHTime1] {
        set HHTime $HHTime1
    }
    set fileList ""
    set tmpstring [APSTmpString]
    set outDir /home/helios/oagData/booster/rampLogFiles/IRamp/rampCorrectionLogFiles
    set outDir $outDir/[clock format [clock seconds] -format %Y-%m%d]
    if ![file exist $outDir] {
        exec mkdir $outDir
    }
    set newMagRampFile /tmp/${supply}new${tmpstring}.afg100
    set newMagRampFile1 $outDir/${supply}new${tmpstring}.afg100
    lappend fileList $newMagRampFile
    set logMagRampFile $outDir/${supply}log${tmpstring}.file
    lappend fileList $logMagRampFile
    set currentFile /tmp/${supply}current${tmpstring}.file
    lappend fileList $currentFile
    set timeout [expr [clock seconds] + 10]
    while {[clock seconds]<$timeout} {
        if [file exist $boosterFileDir/${supply}Vref.afg100] {
            break
        }
        after 1000
    }
    if ![file exist $boosterFileDir/${supply}Vref.afg100] {
        return -code error "BoosterRampVcorrectAndCheck3: $boosterFileDir/${supply}Vref.afg100 does not exist!"
    }
    if [string length $runControlPV] {
        if [catch {PingRunControl -runControlPV $runControlPV} result] {
            return -code error "BoosterRampVcorrectAndCheck5 -Error of PingRunControl in VcorrectAndCheck before starting: $result"
        }
    }
    #lock the ramp so that bcontrol won't change the parameter during ramp correction
    if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=1 -pend=10} result] {
        return -code error "Unable to lock $supply: $result"
    }
    set currRefFile $boosterFileDir/IRef
    if {$supply=="BM"} {
        set time0 5.0
    } else {
        set time0 0
    }
    if [catch {exec fixrampcurrent \
                 $boosterFileDir/${supply}Vref.afg100 $newMagRampFile \
                 -number2Ave=$number2Ave \
                 -referenceCurrentFile=$currRefFile \
                 -currentFile=$currentFile \
                 -logFile=$logMagRampFile \
                 -converter=$convFile,Acoeffs,Bcoeffs \
                 -filter=$filtFile,Acoeffs,Bcoeffs \
                 -fitrange=$fitStart,$fitEnd \
                 -lowtransition=$LLTime,$LTime \
                 -crop=$crop \
                 -Hightransition=$HTime,$HHTime \
                 -averageTime=$LAvgTime,$HAvgTime \
                 -sparse=[format %.0f $sparse] \
                 -smooth=[format %.0f $smoothPt],[format %.0f $smoothPass] \
                 -shift=$shift \
                 -gain=$gainStart,$gainStop,$gainCurv \
                 -delay=[format %.0f $filtDelay] \
                 -npoints=[format %.0f $npoints] \
                 -normalize=$normalize \
                 -afgTriggerGain=$AfgTriggerGain \
                 -afgAmpgain=$AfgAmpGain  } result] {
        ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck6: $result"
    }
    set rampLinkDir [file readlink /home/helios/oagData/booster/ramps/IRamp]
    if [catch {exec sddsprocess -nowarning $logMagRampFile \
                 -reprint=par,RampDir,$rampLinkDir } result] {
        ReturnFromRampCorrection -supply $supply -error "Error print RampDir parameter to $logMagRampFile: $result"
    }
    catch {exec rm ${logMagRampFile}~}
    if {$supply=="BM"} {
        if [catch {exec sddsprocess $currentFile -process=B:${supply}:CurrentWF,max,MaxCurrent -pipe=out \
                     | sdds2stream -pipe -par=MaxCurrent} maxCurrent] {
            ReturnFromRampCorrection -supply $supply -error "error in getting peak current: $maxCurrent"
        }
        if {$maxCurrent<30000} {
            #do not correction if it not is fulll power
            if {$statusCallback!=""} {
                $statusCallback "no correction is done for BM because the power is too low.."
            }
            if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=0 -pend=10} result] {
                return -code error "Unable to unlock $supply: $result"
            }
            catch {exec rm $currentFile  $newMagRampFile $logMagRampFile}
            return
        }
    }
    set dataFileUniqueLabel [APSOffsetDateInfo -today 1 -dateFormat Y-M-D]_[lindex [exec date] 3]
    if [catch {exec cavget -list=B:SampleperiodAI -pend=10} samplePeriod] {
        ReturnFromRampCorrection -supply $supply -error "Error reading sample Period: $samplePeriod"
    }
    if {$samplePeriod>477} {
        set endTime 490
    } else {
        set endTime 245
    }
    if [catch {exec sddschanges -pipe=out $newMagRampFile \
                 -changesIn=RampSetpoint \
                 -Baseline=${boosterSafetyFileDir}/${supply}Vref.afg100 \
                 | sddsxref -pipe $newMagRampFile \
                 -take=RampTime,RampSetpoint \
                 -rename=col,RampSetpoint=RampSetpointCorrection \
                 | sddsxref -pipe ${boosterSafetyFileDir}/${supply}Vref.afg100 \
                 -take=RampTime,RampSetpoint \
                 -rename=col,RampSetpoint=RampSetpointSafety \
                 | sddsprocess -pipe -filter=col,RampTime,$time0,$endTime \
                 | sddsprocess -pipe=in /tmp/${supply}Err${dataFileUniqueLabel}.sdds \
                 -process=ChangeInRampSetpoint,maximum,ChangeMax \
                 -process=ChangeInRampSetpoint,maximum,ChangeMaxPos,functionOf=RampTime,position \
                 -process=ChangeInRampSetpoint,minimum,ChangeMin \
                 -process=ChangeInRampSetpoint,minimum,ChangeMinPos,functionOf=RampTime,position \
                 -process=ChangeInRampSetpoint,sigma,ChangeSigma } result] {
        ReturnFromRampCorrection -supply $supply -error "BoosterVcorrectAndCheck7: $result"
    }
    
    if [string length $runControlPV] {
        if [catch {PingRunControl -runControlPV $runControlPV} result] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck7a -Error of PingRunControl in VcorrectAndCheck after processing files: $result"
        }
    }
    # Verify that calculated ramp correction is within bounds as defined by the safety ramp.
    # If not, generate an error, plot and archive the bad data.
    set tmpOutput /tmp/${supply}Err${dataFileUniqueLabel}.sdds
    if [catch {exec sdds2stream -par=ChangeMax $tmpOutput} ChangeMax] {
        ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck8: $ChangeMax"
    }
    set ChangeMax [expr abs($ChangeMax)]
    if [catch {exec sdds2stream -par=ChangeMin $tmpOutput} ChangeMin] {
        ReturnFromRampCorrection -supply $supply -error "BoosterVcorrectAndCheck9: $ChangeMin"
    }
    set ChangeMin [expr abs($ChangeMin)]
    if {$ChangeMax > $ChangeRef || $ChangeMin > $ChangeRef} {
        if [catch {file rename -force /tmp/${supply}Err${dataFileUniqueLabel}.sdds \
                     ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds } result] {
            ReturnFromRampCorrection -supply $supply -error "VcorrectAndCheck7: $result"
        }
        exec sddsplot -graph=line,vary -subticksettings=xdivisions=5,ydivisions=5 \
          -yScalesGroup=namestring "-xLabel=Time (ms)" \
          "-topline=Correction Safety and Difference Voltage Ramps for ${supply}" \
          -col=RampTime,RampSetpointCorrection ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Correction" \
          -col=RampTime,RampSetpointSafety ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Safety" \
          -col=RampTime,ChangeInRampSetpoint ${boosterErrorFileDir}/${supply}Err${dataFileUniqueLabel}.sdds \
          "-legend=specified=Difference" \
          -yLabel=Difference &
        if [catch {eval file delete -force $fileList} result] {
            ReturnFromRampCorrection -supply $supply -error  "VcorrectAndCheck7a: error in deleting log files; $result"
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" \
                     -tag=execution VCorrectAndCheck -tag=action Error \
                     -tag=description "Vcorrect IRamp for $supply was corrupted"} result] {
            #ReturnFromRampCorrection -supply $supply -error "logMessage error7: $result"
        }
        if [string length $runControlPV] {  
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(7a) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
        ReturnFromRampCorrection -supply $supply -error  "$supply ramp correction will not be done.  Ramp was corrupted.  Visually check the $supply AFG, voltage and current ramp waveform shape before correcting again."    
    } else {
        if [catch {file delete -force /tmp/${supply}Err${dataFileUniqueLabel}.sdds } result] {
            ReturnFromRampCorrection -supply $supply -error "VcorrectAndCheck8: $result"
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" -tag=execution VCorrectAndCheck -tag=action Start \
                     -tag=description "Start IRamp VcorrectAndCheck"} result] {
            #  ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(10) -- logMessage error8: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(10a) -Error of PingRunControl in VcorrectAndCheck before setting glitch pv: $result"
            }
        }
        if [catch {APScavput -list=B:${supply}:Ramp:AutoCorrGlitchBO=1 -pend=20} result] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVCorrectAndCheck(11) -- Error in setting $supply glitch pv: $result"
        }
        
        if [catch {exec sddsprocess "-redefine=col,RampSetpoint,RampTime 5 < RampSetpoint 0 < && pop pop ? 0 : RampSetpoint \$" \
                     $newMagRampFile $newMagRampFile1 } result] {
            ReturnFromRampCorrection -supply $supply  -error  "BoosterRampVCorrectAndCheck(11b) -- Error in reprocessing table: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(11a) -Error of PingRunControl in VcorrectAndCheck before loading ramps: $result"
            }
        }
        if [catch {file copy -force $newMagRampFile1 $boosterFileDir/${supply}Vref.afg100} result] {
            ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(15): $result"
        }
        exec rampload $newMagRampFile
        if [catch {APScavput -list=B:${supply}:Ramp:AutoCorrGlitchBO=0 -pend=20} result] {
            ReturnFromRampCorrection -supply $supply  -error  "BoosterRampVCorrectAndCheck(14): Error in setting $supply glitch pv: $result"
        }
        
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error  "BoosterRampVcorrectAndCheck(14a) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
        #do swap/sync if swap/sync server is not running
        if [catch {exec cavget -list=B:SwapSyncRC.RUN -printErrors -pend=20} swap] {
            ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14b) -- error reading swap/sync runcontrol: $swap"
        }
        if !$swap {
            #run swap/sync
            if [catch {exec cavput -list=B:${supply}:VoltageRT.SWAP=1 -pend=10} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14c) -- error swaping $supply: $result"
            }
            after 500
            if [catch {exec cavput -list=B:PSAFG100SyncBO=1 -pend=10} result] {
                ReturnFromRampCorrection -supply $supply -error "BoosterRampVcorrectAndCheck(14d) -- error doing sync: $result"
            }
        }
        if [catch {exec logMessage -sourceId=${supply}AutoCorrection -tag=applicationName $application \
                     -tag=user $user -tag=host "$host" -tag=execution VCorrectAndCheck -tag=action End \
                     -tag=description "IRamp VcorrectAndCheck completed."} result] {
            #ReturnFromRampCorrection -supply $supply -error  "BoosterRampVCorrectAndCheck(16) -- logMessage error: $result"
        }
        if [string length $runControlPV] {
            if [catch {PingRunControl -runControlPV $runControlPV} result] {
                ReturnFromRampCorrection -supply $supply -error  "BoosterRampVcorrectAndCheck(17) -- Error of PingRunControl in VCorrectAndCheck after setting glitch pvs: $result"
            }
        }
    }
    #unlock ramp 
    #after 500
    if [catch {exec cavput -list=B:${supply}:BconLockedMBBO=0 -pend=10} result] {
        return -code error "BoosterRampVCorrectAndCheck(15a): Unable to unlock $supply: $result"
    }
    #remove $newMagRampFile
    catch {exec rm $newMagRampFile $currentFile}
    if {$statusCallback!=""} {
        $statusCallback "$supply supply ramp corrected."
    }
}
