#include <math.h>
#include <string.h>

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

#include "core_math_private.h"

void vectosignedangles(const vec3_t vector, vec3_t angles)
{
    float yaw;
    float pitch;
    float forward;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x080673ad): yaw =
     * 180.0*atan2/pi and pitch = -180.0*atan2/pi each in 80-bit rounded to float
     * (signed — no 360 wrap); forward is the 80-bit squared sum through double64
     * sqrt to float. atan2/sqrt are libm calls left native. */
    if ((vector[1] == 0.0f) && (vector[0] == 0.0f)) {
        yaw = 0.0f;
        if (vector[2] > 0.0f) {
            pitch = -90.0f;
        } else {
            pitch = 90.0f;
        }
    } else {
        yaw = x87f_store_f32(x87f_div(
            x87f_mul(
                x87f_load_f64(180.0),
                x87f_load_f64(atan2((double)vector[1], (double)vector[0]))),
            x87f_load_f64(3.141592653589793)));
        forward = (float)sqrt(x87f_store_f64(
            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])))));
        pitch = x87f_store_f32(x87f_div(
            x87f_mul(x87f_load_f64(-180.0),
                     x87f_load_f64(atan2((double)vector[2],
                                         (double)forward))),
            x87f_load_f64(3.141592653589793)));
    }
#else
    if ((vector[1] == 0.0f) && (vector[0] == 0.0f)) {
        yaw = 0.0f;
        if (vector[2] > 0.0f) {
            pitch = -90.0f;
        } else {
            pitch = 90.0f;
        }
    } else {
        yaw = (float)((180.0 * atan2((double)vector[1],
                                     (double)vector[0])) /
                      3.141592653589793);
        forward = (float)sqrt((double)((vector[0] * vector[0]) +
                                       (vector[1] * vector[1])));
        pitch = (float)((-180.0 * atan2((double)vector[2],
                                        (double)forward)) /
                        3.141592653589793);
    }
#endif

    memcpy(&angles[0], &pitch, sizeof(angles[0]));
    memcpy(&angles[1], &yaw, sizeof(angles[1]));
    angles[2] = 0.0f;
}
