#pragma once
#include "eigen_tpedefs.h"

class Interpolator {
private:
    Array2d xy;
    double x1;
    double ddx;

    public:
    Interpolator(std::string& fname) {
        xy0 = load_npy_2(fname);
        init(xy0);
    }

    Interpolator(Array2d& xy0) {
        init(xy0);
    }

    void init(Array2d& xy0) {
        xy = xy0;
        int n = xy.rows();
        ddx = 1.0 / (xy[[1,0]] - xy[[0,0]]);
        x1  = xy(0,0);
    }

    double fn y_at(double x) {
        int ix = std::min( ((x - x1) * ddx), xy.rows() - 2);

        double u = (x - xy((ix,0))) * ddx;
        return (1.0 - u) * xy(ix,1) + u * xy(ix+1,1);
    }

    pub fn yy_at(&self, x: f64, id: usize) -> f64 {
        let ix : usize = std::cmp::min( ((x - self.x1) * self.ddx) as usize, self.xy.nrows()-2 );
        let u = (x - self.xy[[ix,0]]) * self.ddx;
        if self.xy.ncols() <= id+1 {
            println!("{} {}", self.xy.ncols(), id)
        }
        (1.0 - u) * self.xy[[ix,id+1]] + u * self.xy[[ix+1,id+1]]
    }
}
