/*\file SystemMatrices.c
 *\brief: build system matrices (stiffness matrix, loads vector)
 */

#include "./SystemMatrices.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         kflag,pflag;
	int         connectivity;
	int         numberofdofspernode;
	ParameterInputs* inputs=NULL;
	int               analysis_type;
	
	/* output datasets: */
	Mat Kgg=NULL;
	Vec pg=NULL;

	/*Boot module: */
	MODULEBOOT();

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

	/*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);
	/*parameters: */
	FetchData((void**)&kflag,NULL,NULL,mxGetField(PARAMETERS,0,"kflag"),"Integer",NULL);
	FetchData((void**)&pflag,NULL,NULL,mxGetField(PARAMETERS,0,"pflag"),"Integer",NULL);
	FetchData((void**)&connectivity,NULL,NULL,mxGetField(PARAMETERS,0,"connectivity"),"Integer",NULL);
	FetchData((void**)&numberofdofspernode,NULL,NULL,mxGetField(PARAMETERS,0,"numberofdofspernode"),"Integer",NULL);
	FetchData((void**)&analysis_type,NULL,NULL,mxGetField(PARAMETERS,0,"analysis_type"),"Integer",NULL);

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

	/*!Generate internal degree of freedom numbers: */
	SystemMatricesx(&Kgg, &pg,elements,nodes,loads,materials,kflag,pflag,connectivity,numberofdofspernode,inputs,analysis_type); 

	/*write output datasets: */
	WriteData(KGG,Kgg,0,0,"Matrix",NULL); 
	WriteData(PG,pg,0,0,"Vector",NULL); 
	
	
	/*Free ressources: */
	delete elements;
	delete nodes;
	delete loads;
	delete materials;
	DeleteParameterInputs(&inputs);
	MatFree(&Kgg);
	VecFree(&pg);

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

void SystemMatricesUsage(void)
{
	_printf_("\n");
	_printf_("   usage: [Kgg,pg] = %s(eleemnts,nodes,loads,materials,params,inputs);\n",__FUNCT__);
	_printf_("\n");
}
