#include <nds.h>
#include <math.h>
#include "math.h"
#include "../bang.h"

#define CLEAR \
    math->sqrt_rc = FALSE;\
    math->atan_rc = FALSE;\
    math->prod_rc = FALSE;\
    math->quot_rc = FALSE;\
    math->rem_rc  = FALSE;

void set_op1_high(MathDevice *math, u8 high) { SET_HIGH(math->op1, high); CLEAR; }
void set_op1_low( MathDevice *math, u8  low) {  SET_LOW(math->op1,  low); CLEAR; }
void set_op2_high(MathDevice *math, u8 high) { SET_HIGH(math->op2, high); CLEAR; }
void set_op2_low( MathDevice *math, u8  low) {  SET_LOW(math->op2,  low); CLEAR; }

u16 get_sqrt(MathDevice *math) {
    if (!math->sqrt_rc) {
        u32 input = math->op1 << 16 | math->op2;
        math->sqrt = sqrt32(input);
        math->sqrt_rc = TRUE;
    }
    return math->sqrt;
}

u16 get_atan(MathDevice *math) {
    if (!math->atan_rc) {
        if (math->op1 || math->op2) {
            double op1 = (s16) math->op1;
            double op2 = (s16) math->op2;
            const double scale = 10430.378350470453; // PI * 32768
            math->atan = (s32) (atan2(op1, op2) * scale);
        }
        math->atan_rc = TRUE;
    }
    return math->atan;
}

u32 get_prod(MathDevice *math) {
    if (!math->prod_rc) {
        math->prod = math->op1 * math->op2;
        math->prod_rc = TRUE;
    }
    return math->prod;
}

u16 get_quot(MathDevice *math) {
    if (!math->quot_rc) {
        if (math->op2) {
            math->quot = div32(math->op1, math->op2);
        }
        math->quot_rc = TRUE;
    }
    return math->quot;
}

u16 get_rem(MathDevice *math) {
    if (!math->rem_rc) {
        if (math->op2) {
            math->rem = mod32(math->op1, math->op2);
        }
        math->rem_rc = TRUE;
    }
    return math->rem;
}