package chromaticTuner.tuner;

public class AudioInterpolator {
	private int m_interpolationFirstIndex=0;
	private int m_interpolationSecondIndex=0;

	public double interpolatedBufferValue(short[] buffer, float index) {
		m_interpolationFirstIndex = (int) Math.floor(index);
		m_interpolationSecondIndex = (int) Math.floor(index + 1);

		if (m_interpolationSecondIndex >= buffer.length || m_interpolationFirstIndex < 0 || m_interpolationSecondIndex < 0) {
			return 0;
		}

		float firstMultiplier = index - m_interpolationFirstIndex;
		return (double) (firstMultiplier * buffer[m_interpolationFirstIndex] +
				(1.0 - firstMultiplier)	* buffer[m_interpolationSecondIndex]);
	}

	private int i0;
	private int i1;
	private int i2;
	private int i3;
	float x;
	public double cubicInterpolatedBufferValue(short[] buffer, float index) {

		if (index <= 0 || index >= buffer.length)
		{
			return 0;
		}

		i0 = (int)Math.floor(index)-1;
		i1 = (int)Math.floor(index);
		i2 = (int)Math.floor(index)+1;
		i3 = (int)Math.floor(index)+2;
		x = index -(int)Math.floor(index);

		if (i0<0) i0=0;
		if (i2<buffer.length) i2 = buffer.length-1;
		if (i3<buffer.length) i3 = buffer.length-1;

		return buffer[i1] + 0.5 * x*(buffer[i2] - buffer[i0] + x*
				(2.0*buffer[i0] - 5.0*buffer[i1] + 4.0*buffer[i2] - buffer[i3] + x*(3.0*
						(buffer[i1] - buffer[i2]) + buffer[i3] - buffer[i0])));
	}
}
