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


 */

#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(BM_struct, yt, cond)\n"
		"  BM_struct = struct('class','BM_offspring',...);    % description of Bayesian Model (BM)\n"
		"  yt = [...];                                        % vector of observed data\n"
		"  cond = [...];                                      % vector of conditioning variables\n"
		"output:\n"
		"  bm_struct = struct('class','BM_offsprin',...);     % description of BM afret 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){	
		vec yt;
		vec cond;
		if (n_input<2){
		} else {
			yt=mxArray2vec(input[1]);
			if (n_input>2){
				cond =mxArray2vec(input[2]);
			}
		}
		//if ( n_output<1 ) mexErrMsgTxt ( "No output - nothing to do!" );
		bm->bayes(yt,cond);
		UImxArray Out;
		UI::save(bm.get(), Out);
		output[0]=UImxArray::create_mxArray(Out);
		if (n_output>1){
			mxArray *le=mxCreateDoubleScalar(mxREAL);
			double2mxArray(bm->_ll(), le);
			output[1]=le;
		}
	} else { 
		mexErrMsgTxt ( "Given object is not BM" );
	}
}
#endif
