/*\file Misfit.c
 *\brief: compute misfit between modeled velocity and observed velocity
 */

#include "./Misfit.h"

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

	/*diverse: */
	int   noerr=1;

	/*input datasets: */
	DataSet* elements=NULL;
	DataSet* nodes=NULL;
	DataSet* loads=NULL;
	DataSet* materials=NULL;
	int      analysis_type;
	double*  u_g=NULL;
	double*  u_g_obs=NULL;
	ParameterInputs* inputs=NULL;

	/* output datasets: */
	double J;

	/*Boot module: */
	MODULEBOOT();

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

	/*Input datasets: */
	FetchData((void**)&elements,NULL,NULL,ELEMENTS,"DataSet",NULL);
	FetchData((void**)&nodes,NULL,NULL,NODES,"DataSet",NULL);
	FetchData((void**)&loads,NULL,NULL,LOADS,"DataSet",NULL);
	FetchData((void**)&materials,NULL,NULL,MATERIALS,"DataSet",NULL);
	FetchData((void**)&analysis_type,NULL,NULL,mxGetField(PARAMETERS,0,"analysis_type"),"Integer",NULL);
	FetchData((void**)&u_g,NULL,NULL,UG,"Vector","Vec");
	FetchData((void**)&u_g_obs,NULL,NULL,UGOBS,"Vector","Vec");

	/*Fetch inputs: */
	ParameterInputsInit(&inputs,INPUTS);

	/*!Call core code: */
	Misfitx(&J, elements,nodes,loads,materials,u_g,u_g_obs,inputs,analysis_type);

	/*write output : */
	WriteData(MISFIT,&J,0,0,"Scalar",NULL);

	/*Free ressources: */
	delete elements;
	delete nodes;
	delete loads;
	delete materials;
	xfree((void**)&u_g);
	xfree((void**)&u_g_obs);
	DeleteParameterInputs(&inputs);

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

void MisfitUsage(void)
{
	_printf_("\n");
	_printf_("   usage: [J] = %s(elements, nodes,loads, materials, parameters, u_g, u_g_obs,inputs);\n",__FUNCT__);
	_printf_("\n");
}
