#include <math.h>

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

#include "core_math_private.h"

long double VectorNormalize2D(vec2_t vector)
{
    float length;
    float reciprocal;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x080667f2): the squared sum
     * (vector[0]*vector[0]) + (vector[1]*vector[1]) is accumulated in 80-bit and
     * rounded to the float length slot (fstps at 0x8066814), reloaded and widened
     * to double for the correctly-rounded CRT sqrt, then the reciprocal and both
     * component scales are each computed in 80-bit and rounded to float. */
    length = x87f_store_f32(
        x87f_add(x87f_mul(x87f_load_f32(vector[0]), x87f_load_f32(vector[0])),
                 x87f_mul(x87f_load_f32(vector[1]), x87f_load_f32(vector[1]))));
    length = (float)sqrt(x87f_store_f64(x87f_load_f32(length)));
    if (length != 0.0f) {
        reciprocal =
            x87f_store_f32(x87f_div(x87f_load_f32(1.0f), x87f_load_f32(length)));
        vector[0] = x87f_store_f32(
            x87f_mul(x87f_load_f32(vector[0]), x87f_load_f32(reciprocal)));
        vector[1] = x87f_store_f32(
            x87f_mul(x87f_load_f32(vector[1]), x87f_load_f32(reciprocal)));
    }
#else
    length = (vector[0] * vector[0]) + (vector[1] * vector[1]);
    length = (float)sqrt((double)length);
    if (length != 0.0f) {
        reciprocal = 1.0f / length;
        vector[0] = vector[0] * reciprocal;
        vector[1] = vector[1] * reciprocal;
    }
#endif

    return (long double)length;
}
