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

#include "./Gradj.h"

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

	/*input datasets: */
	int         control_index,num_controls;
	double     *norm_list    = NULL;
	Elements   *elements     = NULL;
	Nodes      *nodes        = NULL;
	Vertices   *vertices     = NULL;
	Loads      *loads        = NULL;
	Materials  *materials    = NULL;
	Parameters *parameters   = NULL;

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

	/*Boot module: */
	MODULEBOOT();

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

	/*Input datasets: */
	FetchMatlabData((DataSet**)&elements,ELEMENTS);
	FetchMatlabData((DataSet**)&nodes,NODES);
	FetchMatlabData((DataSet**)&vertices,VERTICES);
	FetchMatlabData((DataSet**)&loads,LOADS);
	FetchMatlabData((DataSet**)&materials,MATERIALS);
	FetchMatlabData(&parameters,PARAMETERS);
	parameters->FindParam(&num_controls,InversionNumControlParametersEnum); 

	/*configure: */
	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);

	/*!Call core code: */
	Gradjx(&gradient,&norm_list,elements,nodes, vertices,loads, materials,parameters);

	/*write output : */
	WriteMatlabData(NORMLIST,norm_list,num_controls,1);
	WriteMatlabData(GRADG,gradient);

	/*Free ressources: */
	delete elements;
	delete nodes;
	delete vertices;
	delete loads;
	delete materials;
	delete parameters;
	VecFree(&gradient);

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

void GradjUsage(void)
{
	_printf_(true,"\n");
	_printf_(true,"   usage: [gradient] = %s(elements,nodes,vertices,loads, materials, parameters,control_type);\n",__FUNCT__);
	_printf_(true,"\n");
}
