/*----------------------------------------------------------------------------
     Routine to allocate various parameters used by the q/n estimator of
     VTS-order1. 
     It uses alloc2d() to allocate two dimensional arrays, and malloc()
     to allocate 1d arrays.
     In case of failure of allocation echoes a warning and returns error.
------------------------------------------------------------------------------*/
#include <stdlib.h>
//#include <malloc.h>
#include <stdio.h>

#include "VTS.h"

int mmsealloc(float ***f, float ***wta,	/*  Various simplifying terms in the algorithm */
	      float ***wtb, float ***zmean,	/* The parameters of z */
	      float ***zvar, float **zcorprod, float **pk,	/* Posterior probabilities of gaussians */
	      int nmodes,	/* Number of modes in distribution */
	      int ndim		/* distribution dimensionality */
    )
{
	float *pkbuff;
	float *zcorprodbuff;
	float **fbuff = NULL;
	float **wtabuff = NULL;
	float **wtbbuff = NULL;
	float **zmeanbuff = NULL;
	float **zvarbuff = NULL;
	int NOERROR = 1;

	if ((pkbuff = (float *) malloc(nmodes * sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer pk[]\n"));
		NOERROR = 0;
	} else {
		*pk = pkbuff;
		NOERROR = 1;
	}

	if ((zcorprodbuff =
	     (float *) malloc(nmodes * sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer zcorprod[]\n"));
		NOERROR = 0;
	} else {
		*zcorprod = zcorprodbuff;
		NOERROR = 1;
	}

	if ((fbuff =
	     (float **) alloc2d(nmodes, ndim, sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer f[][]\n"));
		NOERROR = 0;
	} else {
		*f = fbuff;
		NOERROR = 1;
	}

	if ((zmeanbuff =
	     (float **) alloc2d(nmodes, ndim, sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer zmean[][]\n"));
		NOERROR = 0;
	} else {
		*zmean = zmeanbuff;
		NOERROR = 1;
	}

	if ((zvarbuff =
	     (float **) alloc2d(nmodes, ndim, sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer zvar[][]\n"));
		NOERROR = 0;
	} else {
		*zvar = zvarbuff;
		NOERROR = 1;
	}

	if ((wtabuff =
	     (float **) alloc2d(nmodes, ndim, sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer wta[][]\n"));
		NOERROR = 0;
	} else {
		*wta = wtabuff;
		NOERROR = 1;
	}

	if ((wtbbuff =
	     (float **) alloc2d(nmodes, ndim, sizeof(float))) == NULL) {
		WARNING(("Unable to allocate space for buffer wtb[][]\n"));
		NOERROR = 0;
	} else {
		*wtb = wtbbuff;
		NOERROR = 1;
	}

	return (NOERROR);
}
