/*!
\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"
		"[bmef_struct,logevidence]=bm_bayesweighted(BMEF_struct, yt, cond, weight)\n"
		"  BMEF_struct = struct('class','BMEF_offspring',...);% description of Bayesian Model (BM) form exp. family\n"
		"  yt = [...];                                        % vector of observed data\n"
		"  cond = [...];                                      % vector of conditioning variables\n"
		"  weight = [1.0];                                    % weight of the date vector\n"
		"output:\n"
		"  bmef_struct = struct('class','BMEF_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<BMEF> bm=UI::build<BMEF>(Cfg);
	
	if (bm){	
		vec yt;
		vec cond;
		double weight;
		if (n_input<2){
		} else {
			yt=mxArray2vec(input[1]);
			if (n_input>2){
				cond =mxArray2vec(input[2]);
			}
			if (n_input>3){
				weight = mxArray2double(input[3]);
			}
		}
		//if ( n_output<1 ) mexErrMsgTxt ( "No output - nothing to do!" );
		bm->bayes_weighted(yt,cond,weight);
		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
