/* LPC_and_Cepstrum.c */
/*
	David Weenink, 20001214
	20001214 djmw: bug in Cepstrum_Frame_into_LPC_Frame, after each call
		cepstal coefficients were changed c[i] *= i.
*/

#include "LPC_and_Cepstrum.h"

void LPC_Frame_into_Cepstrum_Frame (LPC_Frame me, Cepstrum_Frame thee)
{
	int i, k, n = my nCoefficients > thy nCoefficients ? thy nCoefficients : my nCoefficients;
	float *c = thy c, *a = my a;
	
	c[0] = 0.5 * log (my gain);
	if (n == 0) return;
	
	c[1] = -a[1];
	for (i=2; i <= n; i++)
	{
		c[i] = 0;
		for (k=1; k < i; k++) c[i] += a[i-k] * c[k] * k;
		c[i] = -a[i] - c[i] / i;
	}
}

void Cepstrum_Frame_into_LPC_Frame (Cepstrum_Frame me, LPC_Frame thee)
{
	int i, j;
	float *c = my c, *a = thy a;
	thy gain = exp (2 * c[0]);
	if (thy nCoefficients == 0) return;
	a[1] = -c[1];
	for (i=2; i <= thy nCoefficients; i++) c[i] *= i;
	for (i=2; i <= thy nCoefficients; i++)
	{
		a[i] = c[i];
		for (j=1; j < i; j++) a[i] += a[j] * c[i-j];
		a[i] /= -i;
	}
	for (i=2; i <= thy nCoefficients; i++) c[i] /= i;
	
}

Cepstrum LPC_to_Cepstrum (LPC me)
{
	Cepstrum thee; long i;
	if ((thee = Cepstrum_create (my xmin, my xmax, my nx, my dx, my x1, 
		my maxnCoefficients, 1.0 / my samplingInterval)) == NULL) return thee;
	for (i=1; i <= my nx; i++)
	{
		if (! Cepstrum_Frame_init (& thy frame[i], my frame[i].nCoefficients)) { forget (thee); break; } 
		LPC_Frame_into_Cepstrum_Frame (& my frame[i], & thy frame[i]);
	}
	return thee;
}

LPC Cepstrum_to_LPC (Cepstrum me)
{
	LPC thee; long i;
	if ((thee = LPC_create (my xmin, my xmax, my nx, my dx, my x1, 
		my maxnCoefficients, 1.0 / my samplingFrequency)) == NULL) return thee;
	for (i=1; i <= my nx; i++)
	{
		if (! LPC_Frame_init (& thy frame[i], my frame[i].nCoefficients)) { forget (thee); break; } 
		Cepstrum_Frame_into_LPC_Frame (& my frame[i], & thy frame[i]);
	}
	return thee;
}

/* End of file LPC_and_Cepstrum.c  */
