/*!
\file
\brief wrapper function for MixEF.init() + MixEF.bayes_batch()


 */

#include <estim/mixtures.h>
#include <estim/arx.h>

using namespace bdm;

#ifdef MEX
#include <mex/mex_parser.h>
#include <mex/mex_function.h>

void mexFunction ( int n_output, mxArray *output[], int n_input, const mxArray *input[] ) {
	// Check the number of inputs and output arguments
	if ( n_input<1 ) mexErrMsgTxt ( "Usage:\n"
		                                "Mix=mixef_init(Data, Com1)\n"
		                                "  Data = [];                                 % matrix of data \n"
		                                "  Com1 = struct('class','BMEF_offspring');   % A typical component \n"
		                                "  no_com = [10];                             % requested numbebr of component \n"
		                                "output:\n"
		                                "  structure with description of mixture." );

	//input check
	if (!mxIsNumeric(input[0])) mexErrMsgTxt("Given input #1 is not a data matrix.");
	if (n_input<2) mexErrMsgTxt("No initial component, dont know what type of mixture to fit.");
	if (!mxIsStruct(input[1])) mexErrMsgTxt("Given input #2 is not a struct.");
	//output check
	if ( n_output<1 ) mexErrMsgTxt ( "No output - nothing to do!" );

	// act
	RV::clear_all();

	mat Data=mxArray2mat(input[0]);
	
	UImxArray Cfg(input[1]);
 	Cfg.writeFile("mixef_init.cfg");

	int no_com=10;
	if (n_input>2){
		no_com = mxArray2double(input[2]);
	}
#else
int main() {
	UIFile Cfg ( "mixef_init.cfg" );
	mat Data=randn(2,100); // <<<<<<<<< ============== beware!!!
	int no_com =10;
#endif
	
	shared_ptr<BMEF> com1=UI::build<BMEF>(Cfg.getRoot());
	MixEF mix;
	mix.init(&(*com1),Data,no_com);
//	mix.bayes_batch(Data,zeros(0,Data.cols()));
	shared_ptr<epdf> p=mix.epredictor(vec(0));
	UIFile prf;
	UI::save(p.get(), prf.getRoot(),"predictor");
	prf.writeFile("mix_pred.cfg");
		
#ifdef MEX	
 	UImxArray out;
	UI::save( &mix, out );
	output[0]= out.create_mxArray();
	if (n_output>1){
		UImxArray ep;
		shared_ptr<epdf> p=mix.epredictor(vec(0));
		UI::save( p.get(), ep );
		output[1] = ep.create_mxArray();
	}
	
#else
	UIFile out;
	UI::save ( &mix, out, "test" );
	out.save ( "mixef_init.out" );
#endif
}
