#!/bin/sh  
# \
exec oagwish "$0" "$@"

#
# $Log: not supported by cvs2svn $
# Revision 1.3  1998/11/04 03:33:39  borland
# Restored a commented-out statement.
#
# Revision 1.2  1998/11/04 03:33:05  borland
# Fixed some sddsprocess problems.
#
# Revision 1.1  1998/11/04 03:26:36  borland
# First version.
#
#

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

set CVSRevisionAuthor "\$Revision: 1.4 $ \$Author: emery $"

APSApplication . -name ramp2728Trims -version $CVSRevisionAuthor 
set tcl_precision 4

set mainStatus "Working..."
APSScrolledStatus .status -parent .userFrame -textVariable mainStatus -width 80 \
        -withButtons 1 -lineLimit 1000 -height 8 -label "Status"
update

set rampDir /home/helios/oagData/sr/bumpRamps
set S27BFile $rampDir/S27B.deltas
set S28AFile $rampDir/S28A.deltas
set logFile /home/helios/oagData/logDaemonData/S2728TrimState.log

proc logRampMessage {message} {
    global apsScriptUser apsScriptHost
    regsub -all { } $message {} message0
    if [catch {exec logMessage -sourceId=S2728TrimState -tag=User $apsScriptUser -tag=Host $apsScriptHost \
                 -tag=Action $message0} result] {
        APSAlertBox [APSUniqueName .] -errorMessage "logMessage problem: $result"
        exit 1
    }
}

proc CheckForExistingProcess {} {
    global logFile
    if [catch {sdds open $logFile} logFID] {
        APSAlertBox [APSUniqueName .] -errorMessage "Log file problem: $logFID"
        exit 1
    }
    foreach column {User Host Action} {
        set data [APSGetSDDSColumn -sddsFD $logFID -column $column]
        set $column [lindex $data end]
    }
    catch {sdds close $logFID}
    if [string compare $Action StartScript]==0 {
        bell
        switch [APSMultipleChoice [APSUniqueName .] \
                  -question "WARNING: this script *appears* to be running already under user $User on host $Host.  Please check whether this is true." \
                  -labelList {"Yes. It is running." "No. It is not running."} \
                  -returnList {running notRunning}] {
                      running {
                          APSAlertBox [APSUniqueName .] -errorMessage "Script already running.  This script will exit."
                          exit 1
                      }
                  }
    }
}

proc SetUpPVLinks {} {
    global PSList PVlist PSRootList varList 
    set PSList [list S27B:MT S27B:H4 S27B:H3 S28A:MT S28A:H3 S28A:H4 ]
    foreach item $PSList {
        lappend PVList $item:StatusCALC
        regsub : $item {} varRootname
        lappend PSRootList $varRootname
        lappend varList ${varRootname}Status
        global ${varRootname}Status  ${varRootname}Display 
        set ${varRootname}Status -1
        set ${varRootname}Display ?
        APSLabeledOutput [APSUniqueName .] -parent .userFrame \
          -label "$item status: " -textVariable ${varRootname}Display
    }

    if {[pv linkw $varList $PVList]} {
        APSAlertBox [APSUniqueName .] -errorMessage "CA problem:  $errorCode\nCan't run!"
        exit 1
    }
}

proc UpdatePVValues {} {
    global varList PSRootList 
    eval global $varList 
    if {[pv getw $varList]} {
        APSAlertBox [APSUniqueName .] -errorMessage "CA problem:  $errorCode\nCan't run!"
        exit 1
    }
    foreach item $varList root $PSRootList {
        set itemStatus [subst \$$item]
        global ${root}Display
        if $itemStatus==0 {
            set ${root}Display OK
        } else {
            set ${root}Display "Not OK"
        }
    }
}

proc RampBump {args} {
    global varList logFile
    eval global $varList 
    set sector ""
    set out 0
    APSStrictParseArguments {sector out} 

    UpdatePVValues 
    foreach item {MT H4 H3} {
        set statusVar ${sector}${item}Status
        if [set $statusVar]!=0 {
            bell
            APSSetVarAndUpdate mainStatus "Unable to ramp for $sector: ${sector}:${item} has bad status."
            return
        }
    }
    if [catch {exec sddsprocess $logFile -pipe=out -nowarning \
                 "-match=column,Action=${sector}Ramped*" \
                 | sdds2stream -column=Action -pipe \
                 | tail -1} lastAction] {
        bell
        APSSetVarAndUpdate mainStatus "Unable to ramp for $sector: $lastAction"
        return
    }
    if {[string length $lastAction]==0} {
        APSSetVarAndUpdate mainStatus "No prior actions for this bump."
        set chSign 0
        if $out {
            set chSign 1
        } 
    } elseif [string compare $lastAction "${sector}RampedIn"]==0 {
        if !$out {
            bell
            if [APSMultipleChoice [APSUniqueName .] \
                  -question "$sector appears to be ramped in already." \
                  -returnList {1 0} \
                  -labelList {"Ok, don't do anything."  "Override!"}] {
                return 
            }
            logRampMessage ${sector}OverrideIn
            set chSign 0
        } else {
            set chSign 1
        }
    } elseif [string compare $lastAction "${sector}RampedOut"]==0 {
        if $out {
            bell
            if [APSMultipleChoice [APSUniqueName .] \
                  -question "$sector appears to be ramped out already." \
                  -returnList {1 0} \
                  -labelList {"Ok, don't do anything."  "Override!"}] {
                return 
            }
            logRampMessage ${sector}OverrideOut
            set chSign 1
        } else {
            set chSign 0
        }
    } else {
        bell
        APSSetVarAndUpdate mainStatus "Action $lastAction not recognized for $sector!"
        return
    }
    global ${sector}File 
    set sectorFile [set ${sector}File]
    if ![file exists $sectorFile] {
        bell
        APSSetVarAndUpdate mainStatus "File $sectorFile not found!"
        return
    }
    if $chSign {
        set tmpFile /tmp/[APSTmpString]
        APSAddToTempFileList $tmpFile
        if [catch {exec sddsprocess $sectorFile $tmpFile \
                     "-redefine=column,DeltaValue,DeltaValue -1 *"} result] {
            bell
            APSSetVarAndUpdate mainStatus "Processing error: $result"
            return
        }
        set sectorFile $tmpFile
    }
    set snapFile /tmp/[APSTmpString]
    set outputFile /tmp/[APSTmpString]
    eval APSAddToTempFileList $snapFile $outputFile
    if [catch {exec burtrb -f $sectorFile -o $snapFile} result] {
        bell
        APSSetVarAndUpdate mainStatus "burtrb problem: $result"
        exit
    }
    if [catch {exec sddsprocess $snapFile -pipe=out \
                 -scan=column,Value,ValueString,%le,type=double \
                 | sddsconvert -pipe -delete=column,ValueString \
                 | sddsxref -pipe $sectorFile -take=DeltaValue \
                 | sddsprocess -pipe=in $outputFile \
                 "-define=column,NewValue,Value DeltaValue +" \
                 "-print=column,ValueString,%21.15le,NewValue"} result] {
        bell
        APSSetVarAndUpdate mainStatus "Processing problem: $result"
        return
    }
    APSSetVarAndUpdate mainStatus "Ramping..."

    if [catch {APSRampToSnapshot -fileName $outputFile -steps 30 -pause 0.1 \
                 -percentage 100 -statusCallback "APSSetVarAndUpdate mainStatus" \
                 -initDialog 1} result] {
        APSSetVarAndUpdate mainStatus "Cancelled or error: $result"
        return
    }
 
    if $out {
        logRampMessage ${sector}RampedOut
    } else {
        logRampMessage ${sector}RampedIn
    }
    APSSetVarAndUpdate mainStatus "Ramp complete."
}

SetUpPVLinks
UpdatePVValues
CheckForExistingProcess

APSButton .rampIn27 -parent .userFrame -text "Ramp in S27" -command \
  "RampBump -sector S27B" -contextHelp "Ramps in the trim, correctors, and BPM setpoints for S27"
APSButton .rampOut27 -parent .userFrame -text "Ramp out S27" -command \
  "RampBump -sector S27B -out 1" -contextHelp "Ramps out the trim, correctors, and BPM setpoints for S27"
APSButton .rampIn28 -parent .userFrame -text "Ramp in S28" -command \
  "RampBump -sector S28A" -contextHelp "Ramps in the trim, correctors, and BPM setpoints for S28"
APSButton .rampOut28 -parent .userFrame -text "Ramp out S28" -command \
  "RampBump -sector S28A -out 1" -contextHelp "Ramps out the trim, correctors, and BPM setpoints for S28"

update

logRampMessage StartScript
dp_atexit append "logRampMessage ExitScript"


