/* this module converts from logspectra to cepstra */

/* input : preallocated logspec array, numof 40-d vectors */
/* output: computed cep array */

#include <math.h>
#include "VTS.h"
#if !defined(M_PI)
# define M_PI           3.14159265358979323846  /* pi */
#endif
float **logspec2cep(float **logspec, int numvectors, int Nfilters,
		    int cepdim)
{
	static int firstcall = 1;
	static float **cosine;
	int i, j, k;
	float **cep;

	if (firstcall) {
		cosine =
		    (float **) alloc2d(cepdim, Nfilters, sizeof(float));
		for (i = 0; i < cepdim; i++)
			for (j = 0; j < Nfilters; j++)
				cosine[i][j] =
				    cos(M_PI * i * (j + 0.5) / Nfilters);
		firstcall = 0;
	}
	cep = (float **) alloc2d(numvectors, cepdim, sizeof(float));

	for (i = 0; i < numvectors; i++) {
		for (j = 0; j < cepdim; j++) {
			cep[i][j] = 0.5f * logspec[i][0] * cosine[j][0];
			for (k = 1; k < Nfilters; k++) {
				cep[i][j] += logspec[i][k] * cosine[j][k];
			}
			cep[i][j] /= (float) Nfilters;
		}
	}
	return (cep);
}
