/*\file BamgConvertMesh.c
 *\brief: bamg module.
 */
#include "./BamgConvertMesh.h"

void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){

	/*input: */
	double* index=NULL;
	int     index_rows;
	double* x=NULL;
	int     x_cols;
	double* y=NULL;
	int     y_rows;
	int     y_cols;

	/*Output*/
	BamgMesh* bamgmesh=NULL;
	BamgGeom* bamggeom=NULL;
	mxArray* bamgmesh_mat=NULL;
	mxArray* bamggeom_mat=NULL;

	/*Intermediary*/
	int nods;
	int nels;
	int verbose=0;

	/*Boot module: */
	MODULEBOOT();

	/*checks on arguments on the matlab side: */
	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgConvertMeshUsage);

	/*Initialize Bamg outputs*/
	bamggeom=new BamgGeom();
	bamgmesh=new BamgMesh();

	/*Input datasets: */
	if (verbose) printf("Fetching inputs\n");
	FetchData(&index,&nels,&index_rows,INDEXHANDLE);
	FetchData(&x,&nods,&x_cols,XHANDLE);
	FetchData(&y,&y_rows,&y_cols,YHANDLE);

	/*Check inputs*/
	if (nels<0){
		_error_("Number of elements must be positive, check index number of lines");
	}
	if (nods<0){
		_error_("Number of nods must be positive, check x and y sizes");
	}
	if (index_rows!=3){
		_error_("index should have 3 columns");
	}
	if (y_rows!=nods){
		_error_("x and y do not have the same length");
	}
	if (x_cols>1 || y_cols>1){
		_error_("x and y should have only one column");
	}

	/* Run core computations: */
	if (verbose) printf("Call core\n");
	BamgConvertMeshx(bamgmesh,bamggeom,index,x,y,nods,nels);

	/*Generate output Matlab Structures*/
	WriteData(BAMGGEOMOUT,bamggeom);
	WriteData(BAMGMESHOUT,bamgmesh);

	/*Clean up*/
	delete bamggeom;
	delete bamgmesh;

	/*end module: */
	MODULEEND();
}

void BamgConvertMeshUsage(void)
{
	_printf_(true,"BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
	_printf_(true,"\n");
	_printf_(true,"   Usage:\n");
	_printf_(true,"      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y);\n");
	_printf_(true,"      index: index of the mesh\n");
	_printf_(true,"      x,y: coordinates of the nodes\n");
	_printf_(true,"\n");
}
