
/*
	OutputControl.c: output model results for control methods.
*/
#include "../../../config.h"

#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)

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

#undef __FUNCT__ 
#define __FUNCT__ "OutputControl"

#undef CLEANUP
#define CLEANUP OutputControlLocalCleanup();

void OutputControlLocalCleanup(void);
	
int OutputControl(WorkspaceParams* workspaceparams,BatchParams* batchparams,Vec* u_g,Vec* partition, char* filename,char* analysis_type){

	/* error handling: */
	int i;
	int		noerr=1;	
	
	/* output: */
	FILE* fid=NULL;

	/* standard output: */
	double* serial_partition=NULL;
	int     serial_partition_rows;
	int     dummy=1;
	int    analysis_size;

	double* serial_u_g=NULL;
	int     serial_u_g_rows;

	double* parameter=NULL;
	int     parameter_rows;

	/*serialize outputs: */
	VecShift(partition,1.0); //matlab indexing
	VecGetSize(*partition,&serial_partition_rows);
	noerr=VecToMPISerial(&serial_partition,partition);TESTEXIT(noerr);

	VecGetSize(*u_g,&serial_u_g_rows);
	noerr=VecToMPISerial(&serial_u_g,u_g);TESTEXIT(noerr);

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

		/*Write solution type: */
		WriteDataToDisk(analysis_type,NULL,NULL,"String",fid);
		
		/*Write uset.gsize: */
		WriteDataToDisk(&uset->gsize,NULL,NULL,"Integer",fid);

		/*Write partition: */
		WriteDataToDisk(serial_partition,&serial_partition_rows,&dummy,"Mat",fid);
		
		/*Write misfit J vector: */
		WriteDataToDisk(&workspaceparams->num_control_parameters,NULL,NULL,"Integer",fid);
		WriteDataToDisk(&workspaceparams->nsteps,NULL,NULL,"Integer",fid);
		WriteDataToDisk(workspaceparams->J,&workspaceparams->nsteps,&dummy,"Mat",fid);
		
		/*Go through all control parameters, and write optimized parameters: */
		for(i=0;i<workspaceparams->num_control_parameters;i++){
			char* control_type=workspaceparams->control_types[i];
			parameter=WorkspaceParamsGetParameter(workspaceparams,control_type);
			parameter_rows=uset->gsize;
			WriteDataToDisk(parameter,&parameter_rows,&dummy,"Mat",fid);
		}

		/*Write solution: */
		WriteDataToDisk(serial_u_g,&serial_u_g_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:
	TESTEXIT(noerr);

	EXIT(noerr);
}	
void OutputControlLocalCleanup(void){
	return;
}


#endif //#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)

