#include <math.h>

#include "coduo_x87emu.h" /* defines EMULATE_X87; x87 shim when it is 1 */

#include "core_math_private.h"

long double vectoyaw(const vec3_t vector)
{
    float yaw;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x08066ff0): the double
     * atan2 result is scaled by 180.0/pi entirely in 80-bit (fmulp; fdivp — no
     * intermediate double store) and rounded to float; a negative result gets a
     * 360.0f wrap added in 80-bit and re-rounded. atan2 is a libm call left
     * native (see [[x87-transcendental-audit]]: bit-identical on the same host;
     * a separate arm64-vs-x86 libm concern, not the x87 envelope's). */
    if (vector[1] == 0.0f && vector[0] == 0.0f) {
        yaw = 0.0f;
    } else {
        yaw = x87f_store_f32(x87f_div(
            x87f_mul(
                x87f_load_f64(atan2((double)vector[1], (double)vector[0])),
                x87f_load_f64(180.0)),
            x87f_load_f64(3.141592653589793)));
        if (yaw < 0.0f) {
            yaw = x87f_store_f32(
                x87f_add(x87f_load_f32(yaw), x87f_load_f32(360.0f)));
        }
    }
#else
    if (vector[1] == 0.0f && vector[0] == 0.0f) {
        yaw = 0.0f;
    } else {
        yaw = (float)((atan2((double)vector[1], (double)vector[0]) * 180.0) /
                      3.141592653589793);
        if (yaw < 0.0f) {
            yaw += 360.0f;
        }
    }
#endif

    return (long double)yaw;
}
