/* CC_and_TableOfReal.c
 * 
 * Copyright (C) 2000-2002 David Weenink
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 djmw 20020315 GPL header
 */

#include "CC_and_TableOfReal.h"

int CC_and_TableOfReal_copyFrame (I, TableOfReal thee, double t,
	long row_to, long col_first, int interpolation)
{
	iam (CC);
	CC_Frame cf;
	long i, j, col_last, frame_t, frame_t1;

	if (t < my xmin || t > my xmax) return Melder_error
		("CC_and_TableOfReal_copyFrame: time out of range.");
		
	if (col_first < 1) col_first = 1;
	
	col_last = col_first + my maximumNumberOfCoefficients - 1;
	if (col_last > thy numberOfColumns) return Melder_error
		("CC_and_TableOfReal_copyFrame: columns don't fit.");
	
	if (row_to < 1 || row_to > thy numberOfRows) return Melder_error
		 ("CC_and_TableOfReal_copyFrame: rows don't fit.");	

	frame_t = interpolation ? Sampled_xToLowIndex (me, t) :
		Sampled_xToNearestIndex (me, t);
	frame_t1 = frame_t + 1;
	
	if (frame_t < 1)
	{
		frame_t1 = frame_t = 1;
	}
	if (frame_t >= my nx)
	{
		frame_t1 = frame_t = my nx;
	}
	
	cf = & my frame[frame_t];
	
	if (interpolation)
	{
		double y, y1, t1 = Sampled_indexToX (me, frame_t1) ;
		CC_Frame cf1 = & my frame[frame_t1];	
	
		for (i = 1; i <= my maximumNumberOfCoefficients; i++, col_first++)
		{
			y  = i <= cf  -> numberOfCoefficients ? cf  -> c[i] : 0;
			y1 = i <= cf1 -> numberOfCoefficients ? cf1 -> c[i] : 0;
			thy data[row_to][col_first] = y + (t - t1) * (y - y1) / my dx;
		}
	}
	else
	{
		for (i = 1; i <= my maximumNumberOfCoefficients; i++, col_first++)
		{
			thy data[row_to][col_first] = i <= cf -> numberOfCoefficients ?
				cf -> c[i] : 0;
		}
	}
	
	return 1;
} 

/* End of file CC_and_TableOfReal.h */
