#include <math.h>

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

#include "core_math_private.h"

long double vectopitch(const vec3_t vector)
{
    float horizontalLength;
    float pitch;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x080670ee): horizontal
     * length is the 80-bit squared sum rounded to double64 for sqrt then to
     * float; pitch = -180.0*atan2/pi in 80-bit rounded to float, with a 360.0f
     * wrap for negatives. atan2/sqrt are libm calls left native (see
     * [[x87-transcendental-audit]]). */
    if ((vector[1] == 0.0f) && (vector[0] == 0.0f)) {
        if (0.0f < vector[2]) {
            pitch = 270.0f;
        } else {
            pitch = 90.0f;
        }
    } else {
        horizontalLength = (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)horizontalLength))),
            x87f_load_f64(3.141592653589793)));
        if (pitch < 0.0f) {
            pitch = x87f_store_f32(
                x87f_add(x87f_load_f32(pitch), x87f_load_f32(360.0f)));
        }
    }
#else
    if ((vector[1] == 0.0f) && (vector[0] == 0.0f)) {
        if (0.0f < vector[2]) {
            pitch = 270.0f;
        } else {
            pitch = 90.0f;
        }
    } else {
        horizontalLength =
            (float)sqrt((double)((vector[0] * vector[0]) +
                                 (vector[1] * vector[1])));
        pitch = (float)((-180.0 * atan2((double)vector[2],
                                        (double)horizontalLength)) /
                        3.141592653589793);
        if (pitch < 0.0f) {
            pitch += 360.0f;
        }
    }
#endif

    return (long double)pitch;
}
