/*  intrpolc.h   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include "ObjProUsr/intrpol.h"
#include "ObjProGen/newaloc.h"
#include "ObjProComGui/cgidbg.h"

void Interpolate::ctor()
{
	ElementSize = 0 ;
    LastInputSample = 0 ;
    NextInputSample = 0 ;
    InputDivOutput = ((double) GetDeltaIn()) / GetDeltaOut() ;
    OutputIndex = 0 ;
    InputHighIndex = -1 ;
	input_sample_index = 0 ;
	output_sample_index = 0 ;
}

void Interpolate::dtor()
{
	delete LastInputSample ;
	delete NextInputSample ;
}

int Interpolate::UpdateInput(int Needed)
{
	int DidInput = 0 ;
	while (InputHighIndex < Needed) {
		for (int i = 0 ; i < ElementSize; i++)  {
			LastInputSample[i] = NextInputSample[i];	
			NextInputSample[i] = ReadWord();
		}
/*
 *		LogOut << "Read i = " << input_sample_index << ", o = " <<
 *			output_sample_index << "\n" ;
 */
		input_sample_index++ ;
		InputHighIndex++ ;
		DidInput++ ;
	}
	return DidInput ;
}

ErrCode Interpolate::kernel(int32 k)
{
	if (!LastInputSample) {
		ElementSize = GetEltSize();
		LastInputSample = NEW(MachWord,ElementSize);
		NextInputSample = NEW(MachWord,ElementSize);
		for (int i = 0 ; i < ElementSize; i++)
			NextInputSample[i] = 0 ;
	}
	for (int l = 0 ; l < k ; l++) 
	 for (int c = 0 ; c < GetDeltaOut(); c++)
	  for (int b = 0 ; b < GetBlockSize(); b++) {
			double InputPosition = InputDivOutput * OutputIndex ;
			int InputLow = (int) InputPosition ;
			double HighDiff = InputPosition - InputLow ;
/*
 *	 	 	LogOut << "InputHighIndex = " << InputHighIndex
 *				<< ", OutputIndex = " << OutputIndex << "\n" ;
 */
			if (HighDiff < 1.e-3) {
				UpdateInput(InputLow);
				for (int i=0; i < ElementSize;i++) {
					WriteWord(NextInputSample[i]);
				}
/*
 *				LogOut << "Write i = " << input_sample_index << ", o = " <<
 *					output_sample_index << "\n" ;
 */
				output_sample_index++ ;
				OutputIndex++ ;
				continue ;
			}
			UpdateInput(InputLow+1) ;
			for (int i=0; i < ElementSize;i++) {
				double LowDiff = 1.0 - HighDiff ;
				MachWord Low = (MachWordCast) (LowDiff *
					((double) LastInputSample[i])) ;
				MachWord High = (MachWordCast)  (HighDiff *
					((double) NextInputSample[i]));
				WriteWord((MachWordCast) Low + (MachWordCast) High) ;
/*
 *				LogOut << "write "
 *					<< ((MachWordCast) Low + (MachWordCast) High) << "\n" ;
 *
 *				LogOut << "Low = " << (MachWordCast)  Low << ", High = "
 *					<< (MachWordCast) High << "\n" ;
 *				LogOut << "LowDiff = " << LowDiff << ", HighDiff = "
 *					<< HighDiff << "\n" ;
 *				LogOut << "Next = " << (MachWordCast) NextInputSample[i] << 
 *					", Last = " << (MachWordCast) LastInputSample[i] << "\n" ;
 */
 			}
/*
 *			LogOut << "Write i = " << input_sample_index << ", o = " <<
 *				output_sample_index << "\n" ;
 */
			output_sample_index++ ;
			OutputIndex++;
	}
	return OK ;
}
