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

set CVSRevisionAuthor "\$Revision: 1.5 $ \$Author: borland $"

proc RampCathode {args} {
    set gun 2
    set maxWatts 0
    set timeAtMaxWatts 0
    set stepSize 0.01
    set pauseTime 5
    APSStrictParseArguments {gun maxWatts timeAtMaxWatts stepSize pauseTime}

    global abortBakeIn vacuumVP1 vacuumVP2 vacuumTWVP1 vacuumTWVP2 rfgun
    set abortBakeIn 0

    if {[expr $maxWatts+0.5]>30.51} {
        APSSetVarAndUpdate status "Max Watts too large!"
        return
    }

    if {$gun == 0} {
	APSSetVarAndUpdate status "Please select a RF Gun"
	return
    }

    if {[catch {APSDevSend \
		    -group LinacRFGun \
		    -operation ReadCathodeHeaterCurrent \
		    -deviceList $gun} current]} {
	APSSetVarAndUpdate status "$current"
	bell
	return
    }
    set finalCurrent $current

    if {$current < 0.1} {
	APSSetVarAndUpdate status "Please turn on the cathode heater and start the Cathode Warmup script"
	bell
	return
    }
    
    if {[catch {APSDevSend \
		    -group LinacRFGun \
		    -operation ReadCathodeHeaterPower \
		    -deviceList $gun} watts]} {
	APSSetVarAndUpdate status "$watts"
	bell
	return
    }
    set oldWatts $watts

    update
    if {$abortBakeIn} { return }

    if {$rfgun == $gun} {
	APSSetVarAndUpdate status "Suspending rfGunInterlock"
	if {[catch {APSMpLSuspendResumeRunControl \
			-value "Suspend" \
			-name "RFGunInterlock" \
			-group "LinacRFGun" \
			-deviceList 0} result]} {
	    APSSetVarAndUpdate status "$result"
	    return
	}
	
	update
	if {$abortBakeIn} { return }
	
	APSSetVarAndUpdate status "Suspending fixedCurrent"
	if {[catch {APSMpLSuspendResumeRunControl \
			-value "Suspend" \
			-name FixedCurrent \
			-group "LinacRFGun" \
			-deviceList 0} result]} {
	    APSSetVarAndUpdate status "$result"
	    return
	}
	
	update
	if {$abortBakeIn} { return }
	
	APSSetVarAndUpdate status "Turn L1 LLRF off"
	if {[catch {APSLINAC_LLRFOnOff -button "Off" -deviceList 1} result]} {
	    APSSetVarAndUpdate status "$result"
	    return
	}
    }

    update
    if {$abortBakeIn} { return }

    global powerTrip${gun}
    set powerTrip${gun} [expr $maxWatts + 0.5]
    if {[pv putw powerTrip${gun}]} {
	global errorCode
	APSSetVarAndUpdate status "$errorCode"
	return
    }

    update
    if {$abortBakeIn} {
	ResetPowerTrip
	return
    }

    set notChanged 0
    set above10 0
    set nearMax 0
    while {$watts < $maxWatts} {
	if {!$above10} {
	    if {$watts > 10} {
		set stepSize [expr $stepSize * .5]
		set pauseTime [expr $pauseTime * 2]
		APSSetVarAndUpdate status "Heater power above 10 Watts"
		APSSetVarAndUpdate status "Decreasing Step Size by half"
		APSSetVarAndUpdate status "Increasing Pause Time Step"
		set above10 1
	    }
	}
	if {!$nearMax} {
	    if {$watts >= [expr $maxWatts - 0.5]} {
		set stepSize [expr $stepSize * .5]
		APSSetVarAndUpdate status "Heater power nearing max power"
		APSSetVarAndUpdate status "Decreasing Step Size by half"
		set nearMax 1
	    }
	}
	update
	if {$abortBakeIn} {
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return
	}

	if {[pv getw "vacuumVP$gun vacuumTWVP$gun"]} {
	    global errorCode
	    APSSetVarAndUpdate status "$errorCode"
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return
	}
	if {([set vacuumVP$gun] > 5.0e-07) || ([set vacuumTWVP$gun] > 5.0e-07)} {
	    bell
	    APSSetVarAndUpdate status "Vacuum Problem"
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return
	}

	set current [expr $current + $stepSize]
	APSSetVarAndUpdate status "Changing cathode heater current to $current"
	if {[catch {APSDevSend \
			-group LinacRFGun \
			-operation SetCathodeHeaterCurrent \
			-deviceList $gun \
			-value $current} result]} {
	    APSSetVarAndUpdate status "$result"
	    for {set i 0} {$i < 3} {incr i} bell
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return
	}
	APSWaitWithUpdate -waitSeconds $pauseTime
	if {[catch {APSDevSend \
			-group LinacRFGun \
			-operation ReadCathodeHeaterPower \
			-deviceList $gun} watts]} {
	    APSSetVarAndUpdate status "$watts"
	    for {set i 0} {$i < 3} {incr i} bell
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return
	}
	if {$oldWatts < $watts} {
	    set notChanged 0
	    set oldWatts $watts
	} else {
	    incr notChanged
	}
	if {$notChanged == 5} {
	    APSSetVarAndUpdate status "Cathode power is not responding to changes in the current"
	    for {set i 0} {$i < 3} {incr i} bell
	    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent
	    return	    
	}
    }
    
    APSSetVarAndUpdate status "Holding max power for $timeAtMaxWatts seconds" 
    APSWaitWithUpdate -waitSeconds $timeAtMaxWatts

    SetFinalCurrent -gun $gun -finalCurrent $finalCurrent

}

proc SetFinalCurrent {args} {
    set gun 2
    set finalCurrent 0
    APSStrictParseArguments {gun finalCurrent}

    APSSetVarAndUpdate status "Resetting current"
    if {[catch {APSDevSend \
		    -group LinacRFGun \
		    -operation SetCathodeHeaterCurrent \
		    -deviceList $gun \
		    -value $finalCurrent} result]} {
	APSSetVarAndUpdate status "$result"
	bell
    }

    APSSetVarAndUpdate status "Waiting five seconds"
    APSWaitWithUpdate -waitSeconds 5

    global powerTrip1 oldPowerTrip1 powerTrip2 oldPowerTrip2
    set powerTrip1 $oldPowerTrip1
    set powerTrip2 $oldPowerTrip2
    if {[pv putw powerTrip1]} {
	global errorCode
	APSSetVarAndUpdate status "$errorCode"
    }
    if {[pv putw powerTrip2]} {
	global errorCode
	APSSetVarAndUpdate status "$errorCode"
    }
    APSSetVarAndUpdate status "Done"
}

proc ResetPowerTrip {args} {
    global powerTrip1 oldPowerTrip1 powerTrip2 oldPowerTrip2
    set powerTrip1 $oldPowerTrip1
    set powerTrip2 $oldPowerTrip2
    if {[pv putw powerTrip1]} {
	global errorCode
	APSSetVarAndUpdate status "$errorCode"
    }
    if {[pv putw powerTrip2]} {
	global errorCode
	APSSetVarAndUpdate status "$errorCode"
    }
}

APSApplication . \
    -name "Bake In Cathode" \
    -version $CVSRevisionAuthor 

set status "Ready..."
APSScrolledStatus .status \
    -parent .userFrame \
    -textVariable status \
    -width 60 \
    -height 10

set gun 2
APSRadioButtonFrame .gun \
    -parent .userFrame \
    -label "Select Gun:" \
    -variable gun \
    -buttonList "RG1 RG2" \
    -valueList "1 2" \
    -orientation horizontal

set maxWatts 23.0
APSLabeledEntry .maxWatts \
    -parent .userFrame \
    -label "Max Watts:" \
    -textVariable maxWatts \
    -type real

set timeAtMaxWatts 120
APSLabeledEntry .timeAtWatts \
    -parent .userFrame \
    -label "Time at Max Watts (seconds):" \
    -textVariable timeAtMaxWatts \
    -type integer

set stepSize 0.03
APSLabeledEntry .stepSize \
    -parent .userFrame \
    -label "Current Step Size (Amps):" \
    -textVariable stepSize \
    -type real

set pauseTime 5
APSLabeledEntry .pauseTime \
    -parent .userFrame \
    -label "Pause Between Steps (seconds):" \
    -textVariable pauseTime \
    -type real

APSButton .ramp \
    -parent .userFrame \
    -text "Ramp Cathode" \
    -command {
	.userFrame.ramp.button configure -state disable
	RampCathode \
	    -gun $gun \
	    -maxWatts $maxWatts \
	    -timeAtMaxWatts $timeAtMaxWatts \
	    -stepSize $stepSize \
	    -pauseTime $pauseTime
	.userFrame.ramp.button configure -state normal
    }

set abortBakeIn 0
APSButton .abort \
    -parent .userFrame \
    -text "Abort" \
    -command {APSSetVarAndUpdate status "Aborting" ; set abortBakeIn 1}

if {[catch {APSLinkToLINACPVs} result]} {
    set status "$result"
}

if {[catch {APSRFGUN_DetectSelectedGun} rfgun]} {
    set status "$rfgun"
}
if {$rfgun == "RG1"} {
    set gun 1
    set rfgun 1
} else {
    set gun 2
    set rfgun 2
}
set gun 0

if {[pv linkw "powerTrip1 powerTrip2 vacuumVP1 vacuumVP2 vacuumTWVP1 vacuumTWVP2" "L1:RG1:HTR:PowerCC.HIHI L1:RG2:HTR:PowerCC.HIHI L1:RG1:VP:CO1 L1:RG2:VP:CO1 L1:RG1:TW:VP:CO1 L1:RG2:TW:VP:CO1"]} {
    global errorCode
    APSSetVarAndUpdate status "$errorCode"
    return
}
set oldPowerTrip1 $powerTrip1
set oldPowerTrip2 $powerTrip2

dp_atexit append ResetPowerTrip
