/*!
\file
\brief wrapper function for BM.bayes_batch()


 */

#include <stat/emix.h>

using namespace bdm;

#ifdef MEX
#include <estim/arx_ext.h>
#include <estim/kalman.h>
#include <estim/particles.h>
#include <estim/mixtures.h>
#include <mex/mex_BM.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"
		"[bm_struct,logevidence]=bm_bayes_batch(BM_struct, Yt, Cond)\n"
		"  BM_struct = struct('class','BM_offspring',...);    % description of Bayesian Model (BM)\n"
		"  Yt = [...];                                        % matrix of observed data - columns are data\n"
		"  Cond = [...];                                      % Mector of conditioning variables - columns are conditions\n"
		"output:\n"
		"  bm_struct = struct('class','BM_offsprin',...);     % description of BM after update.\n"
		"  logevidence  = 0.0;                                % logarithm of normalizing constant f(yt|cond)"
		);

	RV::clear_all();
	//CONFIG
	if (n_input<2){			bdm_error("no observed data entered"); }
	
	UImxArray Cfg(input[0]);
	Cfg.writeFile("BM_bayes.cfg");

	shared_ptr<BM> bm=UI::build<BM>(Cfg);
	
	if (bm){	
		mat yt;
		mat cond;
		if (n_input<2){
		} else {
			yt=mxArray2mat(input[1]);
			if (n_input>2){
				cond =mxArray2mat(input[2]);
			} else{
				cond.set_size(0,yt.cols());
			}
		}
		//if ( n_output<1 ) mexErrMsgTxt ( "No output - nothing to do!" );
		double logev=bm->bayes_batch(yt,cond);
		UImxArray Out;
		UI::save(bm.get(), Out);
		output[0]=UImxArray::create_mxArray(Out);
		if (n_output>1){
			mxArray *le=mxCreateDoubleScalar(mxREAL);
			double2mxArray(logev, le);
			output[1]=le;
		}
	} else { 
		mexErrMsgTxt ( "Given object is not BM" );
	}
}
#endif
