#include <stat/merger.h>

using namespace bdm;

int main()
{
  UIFile Cfg("merger_mx.cfg");
	
	// Sources
	Array<mpdf*> Sources;
	//abuse Mer to store sources
	Setting& _Sources=Cfg.lookup("Sources");
	int Slen=_Sources.getLength();
	Sources.set_size(Slen);
	for (int i=0; i<Slen; i++){
		try{
			mpdf* mtmp = UI::build<mpdf>(_Sources,i);
			Sources(i)=mtmp;
		}
		catch (UIbuildException e){
			// it is not mpdf - see if it is epdf
			try {
				epdf* etmp = UI::build<epdf>(_Sources,i);
				if (etmp){
					Sources(i) = new mepdf(etmp, true);
				}
				
			}
			catch (...) {it_error("no mpdfs or epdfs found!");}
		}

	}

	merger_base* Merger=UI::build<merger_base>(Cfg,"Merger");

	// Support
	Setting & _Supp=Cfg.lookup("Support");
	
	if (_Supp.exists("grid") &&  _Supp.exists("nbins")) {
	Array<vec> bounds (0);
	UI::get (bounds, _Supp, "grid");
	ivec nbins(0);
	UI::get (nbins, _Supp, "nbins");
	Merger->set_support (bounds,nbins);
	
	}else {
		if (_Supp.exists("pdf") &&  _Supp.exists("nsamples")){
			epdf *g0=UI::build<epdf> (_Supp, "pdf");
			int npoints=100;
			_Supp.lookupValue("nsamples",npoints);
			Merger->set_support (*g0,npoints);
			delete g0;	
		}
		else it_error("Use either [grid,nbins] or [pdf,nsamples].");
	}
// COMPUTE RESULTS
	Merger->set_sources(Sources,true); // takes care of deletion of sources
	Merger->merge();
	
}
