AI = find_dataref("sim/operation/prefs/ai_flies_aircraft")
AP = find_dataref("sim/cockpit2/autopilot/flight_director_mode")
AT = find_dataref("sim/cockpit2/autopilot/autothrottle_enabled")
VNAV = find_dataref("sim/cockpit2/autopilot/fms_vnav")
L_N2_speed = find_dataref("sim/cockpit2/engine/indicators/N2_percent[0]") 
R_N2_speed = find_dataref("sim/cockpit2/engine/indicators/N2_percent[1]")
L_fadec = find_dataref("sim/cockpit2/engine/actuators/fadec_on[0]")
R_fadec = find_dataref("sim/cockpit2/engine/actuators/fadec_on[1]")
N1_Limit0 = find_dataref("sim/cockpit2/engine/actuators/N1_target_bug[0]")
N1_Limit1 = find_dataref("sim/cockpit2/engine/actuators/N1_target_bug[1]")
ThrotMax = find_dataref("sim/aircraft/engine/acf_throtmax_FWD")
Fuel0 = find_dataref("sim/cockpit2/fuel/fuel_quantity[0]")
Fuel1 = find_dataref("sim/cockpit2/fuel/fuel_quantity[1]")
alt = find_dataref("sim/cockpit2/autopilot/altitude_readout_preselector")
indicated_airspeed = find_dataref("sim/flightmodel/position/indicated_airspeed")
autopilot_airspeed = find_dataref("sim/cockpit/autopilot/airspeed")
vnav_descent_speed_range = find_dataref("sim/cockpit2/autopilot/vnav_descent_speed_range")
--AT = -1
limit = 1
speed_descrep = 0

--sim/cockpit/autopilot/airspeed (airspeed set in AP)
--sim/flightmodel/position/indicated_airspeed (actual airpseed)
--sim/cockpit2/autopilot/fms_vnav (vnav enabled or not)

--sim/cockpit2/autopilot/vnav_descent_speed_range
--0=exact speed, 1=ECON speed range +20/-20, 2=ECON speed range constrained to +5/-20




-- Limit throttle based on weight and altitude when autothrottle is enabled
-- or AI is flying the plane
function adjust_autothrottle()
	if AI > 0 then
	--print("AI is active")
		L_fadec = 1
		R_fadec = 1
		fuel = Fuel0 + Fuel1
		alt_mod = alt / 2500
		limit = (fuel / 382.2858 + 75 + alt_mod) / 100
		if limit > 1 then 
			limit = 1
		end
		ThrotMax = limit
		--print("AI On, Set Limit to " .. limit)
	else
		L_fadec = 0
		R_fadec = 0
	end
	if (VNAV == 1 or AT > 0) and AI == 0 then
		fuel = Fuel0 + Fuel1
		alt_mod = alt / 2500
		limit = (fuel / 382.2858 + 75 + alt_mod) / 100
		if limit > 1 then 
			limit = 1
		end
		ThrotMax = limit
		--print("AI Off, Set Limit to " .. limit)
		elseif AI == 0 then
		ThrotMax = 1.2
	end
end

-- VNAV will let the speed drop too far during descent, so re-enable it if the 
-- speed drops more than 20 knots below the target speed
function watch_vnav_autothrottle()

	speed_descrep = indicated_airspeed - autopilot_airspeed
	if VNAV == 1 and speed_descrep < -20 and AT == 0 and vnav_descent_speed_range == 2 then
	AT = 1
	end
end



function debug()
print("\nLimit: " .. limit .. "\nThrotMax: " .. ThrotMax .. "\nSpeed Descrepancy: " .. speed_descrep)
end

run_at_interval(adjust_autothrottle, 0.25)
run_at_interval(watch_vnav_autothrottle, 2)
--run_at_interval(debug, 2)
