/*!\file:  diagnostic.cpp
 * \brief: diagnostic solution
 */ 

#include "../issm.h"
#include "./parallel.h"

#undef __FUNCT__ 
#define __FUNCT__ "diagnostic"

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


int main(int argc,char* *argv){
	
	/*I/O: */
	FILE* fid=NULL;
	char* inputfilename=NULL;
	char* outputfilename=NULL;
	char* lockname=NULL;
	char* analysis_type="diagnostic_horiz";

	/*Intermediary: */
	FemModel femmodel;
	Vec u_g=NULL;
	ParameterInputs* inputs=NULL;
	int waitonlock=0;

	MODULEBOOT();

	#if !defined(_PARALLEL_) || (defined(_PARALLEL_) && !defined(_HAVE_PETSC_))
	throw ErrorException(__FUNCT__," parallel executable was compiled without support of parallel libraries!");
	#endif

	PetscInitialize(&argc,&argv,(char *)0,"");  

	/*Size and rank: */
	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);  
	MPI_Comm_size(MPI_COMM_WORLD,&num_procs); 

	_printf_("recover , input file name and output file name:\n");
	inputfilename=argv[2];
	outputfilename=argv[3];
	lockname=argv[4];

	/*Open handle to data on disk: */
	fid=fopen(inputfilename,"rb");
	if(fid==NULL) throw ErrorException(__FUNCT__,exprintf("%s%s%s","could not open file ",inputfilename," for binary reading")); 
	
	_printf_("read and create finite element model:\n");
	CreateFemModel(&femmodel,fid,analysis_type);

	/*Initialize inputs: */
	inputs=NewParameterInputs();

	_printf_("call computational core:\n");
	diagnostic_core_nonlinear(&u_g,NULL,NULL,inputs,femmodel);

	_printf_("write results to disk:\n");
	OutputDiagnostic(u_g,femmodel.partition,outputfilename,femmodel.nodesets,analysis_type);

	_printf_("write lock file:\n");
	femmodel.parameters->FindParam((void*)&waitonlock,"waitonlock");
	if (waitonlock){
		WriteLockFile(lockname);
	}
		
	_printf_("closing MPI and Petsc\n");
	MPI_Barrier(MPI_COMM_WORLD);

	/*Close MPI libraries: */
	PetscFinalize(); 


	/*end module: */
	MODULEEND();
	
	return 0; //unix success return;
}
