/*---------------------------------------------------------------------------*
 * This routine reads the text file holding mean, variance and mode 
 * probablities of the mixture density parameters computed by EM. It returns 
 * prob/sqrt(mod var) instead of var to simplify computation in VTS
 ----------------------------------------------------------------------------*/

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#include "VTS.h"

#define QUIT(x) {printf x; fflush (stdout); exit(-1);}


float egy(float *x, int d)
{
	int kk;
	float e;

	e = 0;
	for (kk = 0; kk < d; kk++)
		e += x[kk];
	return (e);
}

int readdistribution(char *filename, float ***mean, float ***vars,
		     float **prob, int *ncodes, int *Ndim)
{
	int i, j, ndim, idx;
	float min, tmp, chk;
	float **meanbuff;
	float **varbuff;
	float *probbuff;

	FILE *codefile;

	if ((codefile = fopen(filename, "r")) == NULL)
		QUIT(("Unable to open Codebook file\n"));

	fscanf(codefile, "%d %d", ncodes, &ndim);
	if ((meanbuff =
	     (float **) alloc2d((*ncodes), ndim, sizeof(float))) == NULL)
		QUIT(("Unable to allocate space for codebook\n"));

	if ((varbuff =
	     (float **) alloc2d((*ncodes), ndim, sizeof(float))) == NULL)
		QUIT(("Unable to allocate space for variances\n"));

	if ((probbuff =
	     (float *) malloc((*ncodes) * sizeof(float))) == NULL)
		QUIT(("Unable to allocate space for mode probabilites\n"));

	for (i = 0; i < (*ncodes); ++i) {
		fscanf(codefile, "%f", &probbuff[i]);
		for (j = 0; j < ndim; ++j)
			fscanf(codefile, "%f", &meanbuff[i][j]);

		for (j = 0; j < ndim; ++j)
			fscanf(codefile, "%f", &varbuff[i][j]);
	}

	fclose(codefile);

	/* Reorganize to have the lowest energy gaussian first */
	min = 1.0e+30f;
	for (i = 0; i < (*ncodes); i++) {
		chk = egy(meanbuff[i], ndim);
		if (chk < min) {
			min = chk;
			idx = i;
		}
	}
	tmp = probbuff[idx];
	probbuff[idx] = probbuff[0];
	probbuff[0] = tmp;
	for (i = 0; i < ndim; i++) {
		tmp = meanbuff[idx][i];
		meanbuff[idx][i] = meanbuff[0][i];
		meanbuff[0][i] = tmp;
		tmp = varbuff[idx][i];
		varbuff[idx][i] = varbuff[0][i];
		varbuff[0][i] = tmp;
	}

	*mean = meanbuff;
	*vars = varbuff;
	*prob = probbuff;
	*Ndim = ndim;

	return (0);
}

