#include "string.h"

#include "calpoint.h"
#include "calcurve.h"



void calcurve_coeffs(const Point *points, Coeff *coeffs) {

    double x0=0, y0=0, x1=0, y1=0, x2=0, y2=0;
    double a, b, c, denom;

    // copy argument points to keep caller array ordered
    Point pts[CAL_POINTS_COUNT];
    memcpy(pts, points, sizeof(pts));

    int n = calpoints_pack(pts);

    if (n == 0) {
        coeffs[0] = 0;
        coeffs[1] = 1;
        coeffs[2] = 0;
        return;
    }
    
    x0 = pts[0].x;
    y0 = pts[0].y;

    if (n > 1) {
        x1 = pts[1].x;
        y1 = pts[1].y;
    }

    if (n > 2) {
        x2 = pts[2].x;
        y2 = pts[2].y;
    }

    switch (n) {

        case 1:
            a = y0 - x0;
            b = 1;
            c = 0;
            break;

        case 2:
            b = (y1-y0)/(x1-x0);
            a = y0 - b * x0;
            c = 0;
            break;

        case 3:
        default:
            denom = (x0 - x1) * (x0 - x2) * (x1 - x2);
            c =  1.0 / denom * ( x2*(y1-y0) + x1*(y0-y2) + x0*(y2-y1) );
            b = -1.0 / denom * ( x2*x2*(y1-y0) + x1*x1*(y0-y2) + x0*x0*(y2-y1) );
            a =  1.0 / denom * ( x1*x2*y0*(x1-x2) + x2*x0*y1*(x2-x0) + x0*x1*y2*(x0-x1) );
            break;
    }

    coeffs[0] = a;
    coeffs[1] = b;
    coeffs[2] = c;

}

