#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "func_ptr.h"
#include "integral.h"

double accurate_integral(func_ptr f, method_ptr method, double a,
        double b, double accuracy, unsigned int decimals) {
    unsigned int steps = 5000, i, prefix;
    double result = 0, old = 1;

    while( fabs(old - result) >= accuracy ) {
        steps *= 2;
        old = result;
        result = integral(f, method, a, b, steps);
    }

    for( decimals += 2, prefix = (int)result; prefix; prefix /= 10 )
        decimals++;

    printf("%.30f\n", old);

    for( i = 0; i < decimals; i++ )
        printf(" ");

    printf("| could deviate from here\n%.30f\n", result);

    return result;
}

double f1(double x) {
    return x * pow(M_E, -x);
}

#define PRINT_INTEGRAL(func, method, a, b, decimals) { \
    accurate_integral(&func, &method, a, b, \
            pow(10, -1.0 * decimals), decimals); \
}

int main(int argc, char *argv[]) {
    if( argc != 2 ) {
        printf("Usage: %s DECIMALS", argv[0]);
        return 1;
    }

    PRINT_INTEGRAL(f1, gauss, 0, 2, atoi(argv[1]));

    return 0;
}
