/* Implemnetation of *m_fixed.c/h

This provides fixed-point arithmetic as 32-bit 16.16
*/

pub const FRACBITS: i32 = 16;
pub const FRACUNIT: i32 = 1 << FRACBITS;

pub const MININT: i32 = 0x80000000;
pub const MAXINT: i32 = 0x7fffffff;
/// Struct representing a fixed point 32-bit value
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct FixedPoint {
    pub value: i32,
}

impl FixedPoint {

    #[allow(non_snake_case)]
    pub fn FixedMul(a: FixedPoint, b: FixedPoint) -> FixedPoint {
        let value = ((a.value as u64) * (b.value as u64) >> FRACBITS) as i32;
        FixedPoint{value}
    }

    #[allow(non_snake_case)]
    pub fn FixedDiv(a: FixedPoint, b: FixedPoint) -> FixedPoint {
        if (i32::abs(a.value) >> 14) >= i32::abs(b.value) {
            if a.value^b.value == 0 {
                FixedPoint{value: MININT};
            }
            else {
               FixedPoint{value: MAXINT};
            }
        }
        FixedPoint::FixedDiv2(a,b)
    }

    #[allow(non_snake_case)]
    pub fn FixedDiv2(a: FixedPoint, b: FixedPoint) -> FixedPoint {
        let c: f64 = ((a.value as f64) / (b.value as f64)) * FRACUNIT as f64;
        if c >= 2147483648.0 || c < -2147483648.0 {
            panic!("FixedDiv: divide by zero");
        }
        FixedPoint { value: c as i32 }
    }

} 