// Generated by EML-lang Swift backend
// Source module: aerospace_actuator_guard_band
// Kernel digest: sha256:0b0ef5a5baecb59acc7d28dc64bc959d9f3378cfbc278204c737cef5bc755aaa
// Functions:     1
// Constants:     0

import Foundation

// _forge_max -- EML's max, as C's eml_builtin_max: NaN when either argument is NaN (Swift.max
// drops a NaN second argument), and IEEE 754-2019 maximum on a tie, so max(-0.0, 0.0) is 0.0 in
// either order -- fmax leaves that implementation-defined (C99 F.10.9.2).
@inline(__always) public func _forge_max(_ a: Double, _ b: Double) -> Double {
    if a.isNaN { return a }
    if b.isNaN { return b }
    if a < b { return b }
    if b < a { return a }
    return a.sign == .minus ? b : a
}

// _forge_min -- EML's min, as C's eml_builtin_min: NaN when either argument is NaN (Swift.min
// drops a NaN second argument), and IEEE 754-2019 minimum on a tie, so min(-0.0, 0.0) is -0.0 in
// either order -- fmin leaves that implementation-defined (C99 F.10.9.2).
@inline(__always) public func _forge_min(_ a: Double, _ b: Double) -> Double {
    if a.isNaN { return a }
    if b.isNaN { return b }
    if a < b { return a }
    if b < a { return b }
    return a.sign == .minus ? a : b
}

/// actuator_command_within_band
/// Pfaffian profile: pfaffian_r=0, cost_class=p0-d4-w0-c0, drift_risk=LOW.
/// - forge.requires: (u_min <= u_max)
/// - forge.ensures: (u_min <= result)
/// - forge.ensures: (result <= u_max)
///  source obligations for actuator_command_within_band: {O1, O2}
///    O1 [43d7c3ff9568] -> PRESERVED (equivalent)  fatalError before return; NOT `assert` (removed at -O) and NOT bare `precondition`, which at -O traps without printing which clause failed
///         build: unconditional -- fatalError, which survives -O; `assert` is removed there and bare `precondition` traps without naming the clause
///    O2 [ca2e303109b7] -> PRESERVED (equivalent)  fatalError before return; NOT `assert` (removed at -O) and NOT bare `precondition`, which at -O traps without printing which clause failed
///         build: unconditional -- fatalError, which survives -O; `assert` is removed there and bare `precondition` traps without naming the clause
/// - forge.verify: lean theorem=actuator_command_within_band
@inline(__always) public func actuator_command_within_band(_ error: Double, _ integral: Double, _ deriv: Double, _ kp: Double, _ ki: Double, _ kd: Double, _ u_min: Double, _ u_max: Double) -> Double {
    precondition((u_min <= u_max), "actuator_command_within_band: requires (u_min <= u_max)")
    let result = _forge_max(u_min, _forge_min((((kp * error) + (ki * integral)) + (kd * deriv)), u_max))
    if !((u_min <= result)) { fatalError("actuator_command_within_band: ensures violated: (u_min <= result)") }
    if !((result <= u_max)) { fatalError("actuator_command_within_band: ensures violated: (result <= u_max)") }
    return result
}
