/*!\file:  ParameterInputsInits.cpp
 * \brief inputs routine is in the io for initializing a ParameterInputs structure out of the matlab workspace.
 */ 

#ifdef HAVE_CONFIG_H
	#include "config.h"
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

#ifdef _SERIAL_

#include "../objects/objects.h"
#include "../shared/shared.h"
#include "../include/macros.h"
#include "./io.h"

#undef __FUNCT__ 
#define __FUNCT__ "ParameterInputsInit" 
void  ParameterInputsInit(ParameterInputs** pinputs, const mxArray* inputhandle){
		
	int dummy;
	int i;
	int nelems;
	int field_name_length;
	
	/*output: */
	ParameterInputs* inputs=NULL;

	/*First allocate ParameterInputs: */
	inputs=NewParameterInputs();

	/*Now populate the structure: */

	/*How many fields? :*/
	inputs->nfields = mxGetNumberOfFields(inputhandle); //tells us how many parameters we have 
	
	/*Check that we don't have a multi-dimensional structure array: */
	nelems  = mxGetNumberOfElements(inputhandle); 
	
	if(nelems!=1){
		_printf_("%s%s\n",__FUNCT__," error message: input parameter structure must be of size 1!");
		mexErrMsgTxt(" ");
	}
	
	/*Allocate fields and field names: */
	inputs->fields=(double**)xmalloc(inputs->nfields*sizeof(double*));
	inputs->field_names=(char**)xmalloc(inputs->nfields*sizeof(char*));
	inputs->fields_length=(int*)xmalloc(inputs->nfields*sizeof(int));

	/*Initialize, we never know: */
	for(i=0;i<inputs->nfields;i++){
		inputs->fields[i]=NULL;
		inputs->field_names[i]=NULL;
		inputs->fields_length[i]=0;
	}


	/*Go through input structure fields and populate our ParameterInputs object:*/
	for (i=0;i<inputs->nfields;i++){
		
		/*Recover field value: */
		FetchData((void**)&inputs->fields[i],&inputs->fields_length[i],&dummy,mxGetFieldByNumber( inputhandle,0,i),"Matrix","Mat");

		/*Recover field name: */
		const char* field_name=mxGetFieldNameByNumber(inputhandle,i);
		field_name_length=strlen(field_name)+1;
		inputs->field_names[i]=(char*)xmalloc(field_name_length*sizeof(char));
		strcpy(inputs->field_names[i],field_name);
	}
		
	/*Assign output poiters:*/
	*pinputs=inputs;

}
#endif //#ifdef _SERIAL-
