/*
 * // Copyright (c) Radzivon Bartoshyk 9/2025. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::common::{f_fmla, is_integerf};
use crate::polyeval::f_polyeval5;
use crate::sin_cosf::sincosf_eval::sincospif_eval;

/// Computes sin(PI\*x)/(PI\*x)
///
/// Produces normalized sinc.
///
/// ulp 0.5
pub fn f_sincpif(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let xd = x as f64;

    if x_abs <= 0x3d80_0000u32 {
        // |x| <= 1/16
        if x_abs < 0x3580_2126u32 {
            // |x| < 0.0000009546391
            if x_abs == 0u32 {
                // Signed zeros.
                return 1.;
            }

            // Small values approximated with Taylor poly
            // sincpi(x) ~ 1 - x^2*Pi^2/6 + O(x^4)
            #[cfg(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            ))]
            {
                use crate::common::f_fmlaf;
                const M_SQR_PI_OVER_6: f32 = f32::from_bits(0xbfd28d33);
                return f_fmlaf(x, M_SQR_PI_OVER_6 * x, 1.);
            }
            #[cfg(not(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            )))]
            {
                const M_SQR_PI_OVER_6: f64 = f64::from_bits(0xbffa51a6625307d3);
                let x2 = xd * xd;
                let p = f_fmla(x2, M_SQR_PI_OVER_6, 1.);
                return p as f32;
            }
        }

        let xsqr = xd * xd;

        // Generated by Sollya:
        // d = [0, 1/16];
        // f_sincpif = sin(y*pi)/(y*pi);
        // Q = fpminimax(f_sincpif, [|0, 2, 4, 6, 8|], [|D...|], d, relative, floating);
        // See ./notes/sincpif.sollya
        let p = f_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xbffa51a662530723),
            f64::from_bits(0x3fe9f9cb401e8e85),
            f64::from_bits(0xbfc86a8da89c9234),
            f64::from_bits(0x3f9ac0a16798157e),
        );
        return p as f32;
    }

    // Numbers greater or equal to 2^23 are always integers or NaN
    // integers are always 0
    if x_abs >= 0x4b00_0000u32 || is_integerf(x) {
        if x_abs >= 0x7f80_0000u32 {
            return x + f32::NAN;
        }
        return if x.is_sign_negative() { -0. } else { 0. };
    }

    const PI: f64 = f64::from_bits(0x400921fb54442d18);
    let rs = sincospif_eval(xd);
    let sf = f_fmla(rs.sin_y, rs.cos_k, f_fmla(rs.cosm1_y, rs.sin_k, rs.sin_k));
    (sf / (PI * xd)) as f32
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sincpif_eval() {
        assert_eq!(f_sincpif(1.0), 0.);
        assert_eq!(f_sincpif(2.0), 0.);
        assert_eq!(f_sincpif(3.0), 0.);
        assert_eq!(f_sincpif(0.0543242), 0.99515265);
        assert_eq!(f_sincpif(0.002134242), 0.9999925);
        assert_eq!(f_sincpif(0.00000005421321), 1.0);
        assert!(f_sincpif(f32::INFINITY).is_nan());
        assert!(f_sincpif(f32::NEG_INFINITY).is_nan());
        assert!(f_sincpif(f32::NAN).is_nan());
    }
}
