% Generated by EML-lang MATLAB backend
% Source module: aerospace_actuator_guard_band
% Kernel digest: sha256:0b0ef5a5baecb59acc7d28dc64bc959d9f3378cfbc278204c737cef5bc755aaa
% Functions:     1
% Constants:     0 (inlined at use-sites)

function r = aerospace_actuator_guard_band(error, integral, deriv, kp, ki, kd, u_min, u_max)
    % Primary entry point -- delegates to actuator_command_within_band.
    % MATLAB requires the file's first function to share
    % the file name; the actual implementation is below.
    r = actuator_command_within_band(error, integral, deriv, kp, ki, kd, u_min, u_max);
end

% actuator_command_within_band
% Pfaffian chain count (eml-cost pfaffian_r): 0    Cost class: p0-d4-w0-c0
% EML depth:   4  Symbolic band: LOW (from pfaffian_r only)
% Numerical:   cancellation exposure NONE  (no mixed-sign subtraction)
% source obligations for actuator_command_within_band: {O1, O2}
%   O1 [43d7c3ff9568] -> PRESERVED (equivalent)  runtime assert before return
%        build: unconditional -- MATLAB assert() has no NDEBUG-equivalent off switch
%   O2 [ca2e303109b7] -> PRESERVED (equivalent)  runtime assert before return
%        build: unconditional -- MATLAB assert() has no NDEBUG-equivalent off switch
function r = actuator_command_within_band(error, integral, deriv, kp, ki, kd, u_min, u_max)
    % @verify(lean, theorem = "actuator_command_within_band")
    assert((u_min <= u_max), 'actuator_command_within_band: requires violated');
    r = eml_builtin_max(u_min, eml_builtin_min((((kp * error) + (ki * integral)) + (kd * deriv)), u_max));
    assert((u_min <= r), 'actuator_command_within_band: ensures violated');
    assert((r <= u_max), 'actuator_command_within_band: ensures violated');
end

function r = eml_builtin_max(a, b)
    % EML max: NaN where either argument is NaN; octave's max returns the other one.
    r = max(a, b);
    r(isnan(a) | isnan(b)) = NaN;
    % a == b is the SIGNED ZERO case: IEEE 754-2019 maximum returns the POSITIVE zero, where
    % octave's max(0, -0) is -0 (measured by bits). (-0)+(+0) is +0 and (-0)+(-0) is -0,
    % so a + b IS the maximum of two zeros. `s` broadcasts exactly as `r` does.
    z = (a == 0) & (b == 0);
    s = a + b;
    r(z) = s(z);
end

function r = eml_builtin_min(a, b)
    % EML min: NaN where either argument is NaN; octave's min returns the other one.
    r = min(a, b);
    r(isnan(a) | isnan(b)) = NaN;
    % a == b is the SIGNED ZERO case: IEEE 754-2019 minimum returns the NEGATIVE zero, where
    % octave's min(-0, 0) is 0 (measured by bits). -((-a) + (-b)) is -0 unless both are +0.
    z = (a == 0) & (b == 0);
    s = -((-a) + (-b));
    r(z) = s(z);
end
