/*
 * BatchDebug: get a matrix or a vector written to disk, so that it can be read on the matlab 
 * side and compared with ISSM code: 
 */
#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)

#include "../include/cielo.h"

#undef __FUNCT__ 
#define __FUNCT__ "OutputControl"


int BatchDebug(Mat* Kgg,Vec* pg,FemModel* femmodel,char* filename){

	int noerr=1;
	
	/* standard output: */
	Vec* tpartition=NULL;
	double* serial_tpartition=NULL;
	int     serial_tpartition_rows;
	int     dummy=1;
	FILE* fid=NULL;

	double* serial_pg=NULL;
	int     serial_pg_rows;
	double* serial_Kgg=NULL;
	int     serial_Kgg_rows,serial_Kgg_cols;

	/*recover parameters: */
	tpartition=femmodel->tpartition;

	/*serialize partition vector: */
	VecGetSize(*tpartition,&serial_tpartition_rows);
	VecToMPISerial(&serial_tpartition,tpartition);

	/*Serialize output matrices and vectors if they exist: */
	if(Kgg){
		MatGetSize(*Kgg,&serial_Kgg_rows,&serial_Kgg_cols);
		MatToSerial(&serial_Kgg,Kgg);
	}

	if(pg){
		VecGetSize(*pg,&serial_pg_rows);
		VecToMPISerial(&serial_pg,pg);
	}


	/* Open output file to write raw binary data: */
	if(my_rank==0){
		fid=fopen(filename,"wb");
		if(fid==NULL){
			_printf_("%s%s\n",__FUNCT__," error message: could not open file ",filename," for binary writing.");
			noerr=0; goto cleanup_and_return;
		}

		/*Write tpartition: */
		WriteDataToDisk(serial_tpartition,&serial_tpartition_rows,&dummy,"Mat",fid);

		/*Write Kgg if it exists: */
		if(Kgg)WriteDataToDisk(serial_Kgg,&serial_Kgg_rows,&serial_Kgg_cols,"Mat",fid);
		
		/*Write pg if it exists: */
		if(pg)WriteDataToDisk(serial_pg,&serial_pg_rows,&dummy,"Mat",fid);
		
		
		/*Close file: */
		if(fclose(fid)!=0){
			_printf_("%s%s%s\n",__FUNCT__," error message: could not close file ",filename);
			noerr=0; goto cleanup_and_return;
		}
	}

	cleanup_and_return:
	return noerr;
}
#endif //#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)
	
