(begin

; setpoint is the maximum velocity we want to achieve
; we read in the user-provided value
; note that if the user left this field blank, we will get a zero
(define setpoint AGC.Input)

; gain is how aggressively we want to try to achieve the setpoint
; or in other words, it's the proportional gain term
(define gain 5)

; compute the magnitude of the velocity
(define velocity (magnitude3 (vessel.srf_velocity)))

; this computes a maximum throttle with a proportional-only style controller
; stolen from mechjeb! :)
; because of the inverting that happens, it's controlling in the opposite
; direction you'd expect from a normal PID controller, so the undershoot
; due to only proportional control results in us not limiting as much as
; we need to for the setpoint, and so this controller tends to always
; allow the throttle to be set such that our actual velocity is above
; the setpoint (unless you set the gain high enough that it oscillates
; about it)
; note if our velocity is less than the setpoint, we allow full throttle
(define velocityRatio (/ velocity setpoint))
(define maxThrottle (if (> velocityRatio 1)
	(saturate (- 1 (* gain (- velocityRatio 1))))
	1))

; if setpoint is nonsense or unspecified, don't limit, otherwise limit the throttle
(if (<= setpoint 0) () (ctrlState.mainThrottle (min (ctrlState.mainThrottle) maxThrottle)))

; show the velocityRatio and our computed maxThrottle
(define AGC.Status (list 
	velocityRatio
	maxThrottle
	))

)

