#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <string.h>
void fit_wavelength2
(
 double inimage[], double ximage[], double yimage[], int npixi,
 double outimage[], double ximageo[], double yimageo[], int npixo,
 int fit_deg, double a[], int printout
 );

#define is_close_abs(a, expected, abs) \
    assert(fabs((a) - (expected)) <= (abs))

#define is_close_rel(a, expected, rel) \
    do { \
        assert(isfinite(a)); \
        if (((fabs((a) - (expected))) / fabs(expected)) > (rel)) { \
            printf("%g - %g = (%g %g%%)\n", a, expected, fabs(a - expected), \
                   100*fabs((a - expected) / expected)); \
            assert(((fabs((a) - (expected))) / fabs(expected)) <= (rel)); \
        } \
    } \
    while (0)

void fit_offset
(
 float x[], float y[], int count,
 float ain[], int npt
 );


void test_fit_offset(void)
{
    int i;
    float x[12];
    for (i = 0; i < 12; i++) {
        x[i] = i;
    }
    float y[12] = {
        0.,
        -101,
        -300,
        -404,
        -99,
        -199,
        -303,
        -399,
        -204,
        -300,
        -104,
        -96
    };
    float a[7] = {0.};

    fit_offset(x, y, 11, a, 6);
    double rel = 0.0001;
    double exp[] = {
        0.,
        150.464676,
        150.798019,
        -100.868629,
        -235.535294,
        -66.201973,
        -98.86866};

    /* fit has no offset parameter so its absolute value is sensitive to very
       small numerical offsets, fitoff subtracts the mean of the parameters to
       fix that */
    is_close_rel(a[1] - a[1], exp[1] - exp[1], rel);
    is_close_rel(a[2] - a[1], exp[2] - exp[1], rel);
    is_close_rel(a[3] - a[1], exp[3] - exp[1], rel);
    is_close_rel(a[4] - a[1], exp[4] - exp[1], rel);
    is_close_rel(a[5] - a[1], exp[5] - exp[1], rel);
    is_close_rel(a[6] - a[1], exp[6] - exp[1], rel);
}

int main(int argc, const char *argv[])
{
    test_fit_offset();
    return 0;
}
