
/*!
\file
\brief Multi-Estimator (developped for PMSM)


 */

#include "user_info.h"
#include "stat/loggers.h"
#include "estim/kalman.h"
#include "pmsmDS.h"


using namespace bdm;
int main ( int argc, char* argv[] ) {
	const char *fname;
	if ( argc>1 ) {fname = argv[1];	}
	else { cout << "Missing configuration file.\n Usage: \n $> estimator config_file.cfg"<<endl; abort(); }
	UIFile F ( fname );

	logger* L = UI::build <logger>( F, "logger" );
	DS * pDS = UI::build<DS> ( F, "system" );
	Array<BM*> Es;			// array of estimators
	UI::get( Es, F, "estimator" );
	int nE = Es.length();	//number of estimators
	int Ndat;				//number of data records
	F.lookupValue ( "experiment.ndat",Ndat );
		
	pDS->log_add ( *L );
	string nic="";
	for (int i=0; i<nE; i++){
		Es(i)->log_add(*L,nic); // estimate
	}
	L->init();

	vec dt=zeros ( pDS->_drv()._dsize() );   //data variable
	Array<datalink*> Dls(nE); 
	for (int i=0; i<nE; i++){
		Dls(i)=new datalink( Es(i)->_drv(),pDS->_drv() ); //datalink between a datasource and estimator
	}
	
	// Main cycle
	for ( int tK=1;tK<Ndat;tK++ ) {
		// Data Source
		pDS->step();							// simulator step
		pDS->getdata ( dt );					// read data
		pDS->logit ( *L );
		
		// Estimators
		for (int i=0; i<nE; i++){
			Es(i)->bayes ( Dls(i)->pushdown ( dt ) );		// update estimates

			Es(i)->logit (*L);
		}
		// Regulators
		L->step();
	}

	L->finalize();

	delete L;
	delete pDS;
	for (int i=0; i<nE; i++){
		delete Dls(i);
		delete Es(i);
	}
	return 0;
}

