/*! \file FetchRifts.cpp
 *  \brief: special i/o here to recover the rifts data. Because serially, the rifts are held into a matlab array strucutre, 
 *  hard to parse. In parallel, it's easier, as we have marshalled the data into a binary buffer.
 */

#undef __FUNCT__
#define __FUNCT__ "FetchRifts"

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

int FetchRifts(int** priftsnumpenaltypairs,double*** priftspenaltypairs,int** priftsfill,double** priftsfriction,ConstDataHandle model_handle,int numrifts){

	int      i;
	int      noerr=1;
	
	/*output: */
	int*     riftsnumpenaltypairs=NULL;
	double** riftspenaltypairs=NULL;
	int*     riftsfill=NULL;
	double*  riftsfriction=NULL;

	/*intermediary: */
	double   fill;
	double*  riftpenaltypairs=NULL;
	#ifdef _SERIAL_
	mxArray* pmxa_rifts=NULL;
	#endif

	if(numrifts){

		/*Allocate arrays: */
		riftsnumpenaltypairs=(int*)xmalloc(numrifts*sizeof(int));
		riftspenaltypairs=(double**)xmalloc(numrifts*sizeof(double*));
		riftsfill=(int*)xmalloc(numrifts*sizeof(int));
		riftsfriction=(double*)xmalloc(numrifts*sizeof(double));

		#ifdef _SERIAL_
		/*From model handle, recover rifts handle: */
		pmxa_rifts=mxGetField(model_handle,0,"rifts");

		for(i=0;i<numrifts;i++){
		
			/*riftspenaltypairs: */
			FetchData((void**)&riftpenaltypairs,riftsnumpenaltypairs+i,NULL,mxGetField(pmxa_rifts,i,"penaltypairs"),"Matrix","Mat");
			riftspenaltypairs[i]=riftpenaltypairs;
			
			/*Riftsfill: */
			FetchData((void**)&fill,NULL,NULL,mxGetField(pmxa_rifts,i,"fill"),"Scalar",NULL);
			riftsfill[i]=(int)fill;
			
			/*Riftsfriction: */
			FetchData((void**)riftsfriction+i,NULL,NULL,mxGetField(pmxa_rifts,i,"friction"),"Scalar",NULL);
		}
		#else
		for(i=0;i<numrifts;i++){
			ModelFetchData((void**)&riftpenaltypairs,riftsnumpenaltypairs+i,NULL,model_handle,exprintf("%s%i","penaltypairs",i),"Matrix","Mat");
			riftspenaltypairs[i]=riftpenaltypairs;
			
			ModelFetchData((void**)&fill,NULL,NULL,model_handle,exprintf("%s%i","fill",i),"Matrix","Mat");
			riftsfill[i]=(int)fill;
			
			ModelFetchData((void**)riftsfriction,NULL,NULL,model_handle,exprintf("%s%i","friction",i),"Matrix","Mat");
		}

		#endif
	}

	/*Assign output pointers: */
	*priftsnumpenaltypairs=riftsnumpenaltypairs;
	*priftspenaltypairs=riftspenaltypairs;
	*priftsfill=riftsfill;
	*priftsfriction=riftsfriction;
	

	return noerr;
}
	
