#include "emix.h"

namespace bdm{

void emix::set_parameters ( const vec &w0, const Array<epdf*> &Coms0, bool copy ) {
	w = w0/sum ( w0 );
	dim = Coms0(0)->dimension();
	int i;
	for ( i=0;i<w.length();i++ ) {
		it_assert_debug ( dim== ( Coms0 ( i )->dimension() ),"Component sizes do not match!" );
	}
	if ( copy ) {
		Coms.set_length(Coms0.length());
		for ( i=0;i<w.length();i++ ) {it_error("Not imp...");
			*Coms ( i ) =*Coms0 ( i );}
		destroyComs=true;
	}
	else {
		Coms = Coms0;
		destroyComs=false;
	}
}

vec emix::sample() const {
	//Sample which component
	vec cumDist = cumsum ( w );
	double u0;
	#pragma omp critical
	u0 = UniRNG.sample();

	int i=0;
	while ( ( cumDist ( i ) <u0 ) && ( i< ( w.length()-1 ) ) ) {i++;}

	return Coms ( i )->sample();
}

emix* emix::marginal(const RV &rv) const{
	it_assert_debug(isnamed(), "rvs are not assigned");
			
	Array<epdf*> Cn(Coms.length());
	for(int i=0;i<Coms.length();i++){Cn(i)=Coms(i)->marginal(rv);}
	emix* tmp = new emix();
	tmp->set_parameters(w,Cn,false);
	tmp->ownComs();
	return tmp;
}

mratio* emix::condition(const RV &rv) const{
	it_assert_debug(isnamed(), "rvs are not assigned");
	return new mratio(this,rv);
};

}
// mprod::mprod ( Array<mpdf*> mFacs, bool overlap) : mpdf ( RV(), RV() ), n ( mFacs.length() ), epdfs ( n ), mpdfs ( mFacs ), rvinds ( n ), rvcinrv ( n ), irvcs_rvc ( n ) {
// 		int i;
// 		bool rvaddok;
// 		// Create rv
// 		for ( i = 0;i < n;i++ ) {
// 			rvaddok=rv.add ( mpdfs ( i )->_rv() ); //add rv to common rvs.
// 			// If rvaddok==false, mpdfs overlap => assert error.
// 			it_assert_debug(rvaddok||overlap,"mprod::mprod() input mpdfs overlap in rv!");
// 			epdfs ( i ) = & ( mpdfs ( i )->_epdf() ); // add pointer to epdf
// 		};
// 		// Create rvc
// 		for ( i = 0;i < n;i++ ) {
// 			rvc.add ( mpdfs ( i )->_rvc().subt ( rv ) ); //add rv to common rvs.
// 		};
//
// //		independent = true;
// 		//test rvc of mpdfs and fill rvinds
// 		for ( i = 0;i < n;i++ ) {
// 			// find ith rv in common rv
// 			rvsinrv ( i ) = mpdfs ( i )->_rv().dataind ( rv );
// 			// find ith rvc in common rv
// 			rvcinrv ( i ) = mpdfs ( i )->_rvc().dataind ( rv );
// 			// find ith rvc in common rv
// 			irvcs_rvc ( i ) = mpdfs ( i )->_rvc().dataind ( rvc );
// 			//
// /*			if ( rvcinrv ( i ).length() >0 ) {independent = false;}
// 			if ( irvcs_rvc ( i ).length() >0 ) {independent = false;}*/
// 		}
// 	};
