#include "base/loggers.h"

namespace bdm {
int mxReplaceFieldNM ( mxArray *X, const char * fname, mxArray *X1 ) {
	mxArray *Old;
	int i;

	if ( ( i = mxGetFieldNumber ( X, fname ) ) == -1 ) {
		if ( ( i = mxAddField ( X, fname ) ) == -1 ) return i;

	}

	Old = mxGetFieldByNumber ( X, 0, i );
	if ( Old ) mxDestroyArray ( Old );
	mxSetFieldByNumber ( X, 0, i, X1 );
	return i;

};

void Arrayvec2mxArray ( const Array<vec> &in, mxArray *out ) {
	int rows, cols, r, c;

	double* temp = ( double * ) mxGetPr ( out );
	if ( temp == 0 ) mexErrMsgTxt ( "mat2mxArray: Pointer to data is NULL" );

	cols = in.size();
	if ( cols == 0 ) mexErrMsgTxt ( "mat2mxArray: Data has zero columns" );

	rows = in ( 0 ).length(); //length of the first vec
	if ( rows == 0 ) mexErrMsgTxt ( "mat2mxArray: Data has zero rows" );

	for ( c = 0; c < cols; c++ ) {
		for ( r = 0; r < rows; r++ ) {
			*temp++ = in ( c ) ( r );
		}
	}

}

//! Logger storing results into an mxArray
class mexlog : public memlog {
public:
	//! constructor
	mexlog() : memlog ( 0, "" ) {};
	//!
	mxArray* toCell() {
		mxArray* tmp = mxCreateStructMatrix ( 1, 1, 0, NULL );

		//copied from itsave
		int i;
		string vec_name = "";
		int istart, iend;

		mat M; //temporary matrix
		for ( i = 0; i < entries.length(); i++ ) {
			istart = 0;
			for ( int j = 0; j < entries ( i ).length(); j++ ) { // same for as in add!!!
				vec_name = names ( i ) + entries ( i ).name ( j );
				iend = istart + entries ( i ).size ( j ) - 1;
				M = vectors ( i ).get_cols ( istart, iend );
				istart = iend + 1;
				// copy the selection to mx
				mxArray* fld = mxCreateDoubleMatrix ( M.rows(), M.cols(), mxREAL );
				mat2mxArray ( M, fld );
				mxReplaceFieldNM ( tmp, vec_name.c_str(), fld );
			}
		}
		return tmp;
	}
	void from_setting ( const Setting &root ) {
		maxlen = root["maxlen"];
	}
};
UIREGISTER ( mexlog );
SHAREDPTR ( mexlog );
}
