
// (C)2007 Attila Kovacs <attila@submm.caltech.edu>

import java.io.*;
import java.util.*;

public abstract class Interpolator extends Vector<InterpolatorData> {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7962217110619389946L;

	public Interpolator(String fileName) throws IOException {
		readData(fileName);
		System.err.println(getClass().getSimpleName() + "> " + size() + " records parsed.");	
		Collections.sort(this);
	}
	
	public abstract void readData(String fileName) throws IOException; 
	
	// Linear interpolation.
	// Throws Exception if MJD is outside of the interpolator range.
	public double getValue(double MJD) throws ArrayIndexOutOfBoundsException {
		int lower = 0, upper = size()-1;
		
		if(MJD < get(lower).MJD || MJD > get(upper).MJD) 
			throw new ArrayIndexOutOfBoundsException(getClass().getSimpleName() + "> outside of interpolator range.");
		
		while(upper - lower > 1) {
			int i = (upper + lower) / 2;
			double iMJD = get(i).MJD;
			if(MJD >= iMJD) lower = i;
			if(MJD <= iMJD) upper = i;
		}
		
		double dt1 = MJD - get(lower).MJD;
		double dt2 = get(upper).MJD - MJD;
		
		return (dt2 * get(lower).value + dt1 * get(upper).value) / (dt1 + dt2);	
	}	
}

