/*
 * HeaderAddToDataSetRef.c
 *     Description:  This function adds a header structure to a dataset reference. This is 
 *     normally done in WriteDataSet, but modules don't call WriteDataSet when the data 
 *     returned is remote. In these cases, we call HeaderAddToDataSetRef. Why do we call 
 *     this other function instead of WriteDataSet? Because for ex in modules View and 
 *     Rmg, remote data is not downloaded, and WriteDataSet would not be able to retrieve 
 *     M,N, nnz, isempty, issparse from the input dataset  reference, only garbage. 
 */

/* hosting environment: */
#include "../include/cielo.h"


int HeaderAddToDataSetRef(mxArray* pdatasetref,double M,double N,double nnz,double IsEmpty,double IsSparse){

	int noerr=1;
	int i;
	
	/*Header variables*/
	int nfields=5;
	const	char*	fnames[nfields];
	mwSize		onebyone[2] = {1,1};
	mwSize		ndim=2;
	mxArray* pmxa_header=NULL;
	double* pM=NULL;
	double* pN=NULL;
	double* pnnz=NULL;
	double* pIsEmpty=NULL;
	double* pIsSparse=NULL;
	mxArray* pmxa_M=NULL;
	mxArray* pmxa_N=NULL;
	mxArray* pmxa_nnz=NULL;
	mxArray* pmxa_IsEmpty=NULL;
	mxArray* pmxa_IsSparse=NULL;


	
	
	fnames[0] = "M";
	fnames[1] = "N";
	fnames[2] = "nnz";
	fnames[3] = "isempty";
	fnames[4] = "issparse";
	
	pmxa_header=mxCreateStructArray( ndim,onebyone,nfields,fnames);

	pM=(double*)xcalloc(1,sizeof(double));
	pN=(double*)xcalloc(1,sizeof(double));
	pnnz=(double*)xcalloc(1,sizeof(double));
	pIsEmpty=(double*)xcalloc(1,sizeof(double));
	pIsSparse=(double*)xcalloc(1,sizeof(double));

	*pM=M;
	*pN=N;
	*pnnz=nnz;
	*pIsEmpty=IsEmpty;
	*pIsSparse=IsSparse;
	
	pmxa_M = mxCreateDoubleMatrix(1,1,mxREAL);
	mxSetM(pmxa_M,1);
	mxSetN(pmxa_M,1);
	mxSetPr(pmxa_M,pM);
	
	pmxa_N = mxCreateDoubleMatrix(1,1,mxREAL);
	mxSetM(pmxa_N,1);
	mxSetN(pmxa_N,1);
	mxSetPr(pmxa_N,pN);

	pmxa_nnz = mxCreateDoubleMatrix(1,1,mxREAL);
	mxSetM(pmxa_nnz,1);
	mxSetN(pmxa_nnz,1);
	mxSetPr(pmxa_nnz,pnnz);


	pmxa_IsEmpty = mxCreateDoubleMatrix(1,1,mxREAL);
	mxSetM(pmxa_IsEmpty,1);
	mxSetN(pmxa_IsEmpty,1);
	mxSetPr(pmxa_IsEmpty,pIsEmpty);

	pmxa_IsSparse = mxCreateDoubleMatrix(1,1,mxREAL);
	mxSetM(pmxa_IsSparse,1);
	mxSetN(pmxa_IsSparse,1);
	mxSetPr(pmxa_IsSparse,pIsSparse);
	
	mxSetField( pmxa_header, 0, "M",     pmxa_M);
	mxSetField( pmxa_header, 0, "N",     pmxa_N);
	mxSetField( pmxa_header, 0, "nnz",     pmxa_nnz);
	mxSetField( pmxa_header, 0, "isempty",     pmxa_IsEmpty);
	mxSetField( pmxa_header, 0, "issparse",     pmxa_IsSparse);

	/*Add header to pOuputStructure*/
	mxAddField(pdatasetref,"header");
	mxSetField(pdatasetref,0,"header",pmxa_header);

	return noerr;
}
