/*\file Gradj.c
 *\brief: compute gradients for inverse control method
 */

#include "./Gradj.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;
	char*    control_type=NULL;
	double*  u_g=NULL;
	double*  lambda_g=NULL;
	ParameterInputs* inputs=NULL;

	/* output datasets: */
	Vec grad_g=NULL;


	/*Boot module: */
	MODULEBOOT();

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

	/*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**)&control_type,NULL,NULL,mxGetField(PARAMETERS,0,"control_type"),"String",NULL);
	FetchData((void**)&u_g,NULL,NULL,UG,"Vector","Vec");
	FetchData((void**)&lambda_g,NULL,NULL,LAMBDAG,"Vector","Vec");

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

	/*!Call core code: */
	Gradjx(&grad_g, elements,nodes,loads,materials,u_g,lambda_g,inputs,analysis_type,control_type);

	/*write output : */
	WriteData(GRADG,grad_g,0,0,"Vector",NULL);

	/*Free ressources: */
	delete elements;
	delete nodes;
	delete loads;
	delete materials;
	xfree((void**)&u_g);
	xfree((void**)&lambda_g);
	xfree((void**)&control_type);
	DeleteParameterInputs(&inputs);
	VecFree(&grad_g);

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

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