/*
 * GradJCheck.c:
 */

#include "../../../config.h"

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

#include "../include/cielo.h"
#include "../modules.h"
#include "./parallel.h"

#undef __FUNCT__ 
#define __FUNCT__ "GradJCheck"
#undef CLEANUP
#define CLEANUP GradJCheckLocalCleanup();

void GradJCheckLocalCleanup(void);

int GradJCheck(WorkspaceParams* workspaceparams,int step,int status){
	
	int reloop=0;
	int i;

	if (step==0){
		/*Ok, this is the first time we are running the GradJSearch. No criterion applied here. : */
	}
	else{
		if  (workspaceparams->J[step]>workspaceparams->J[step-1]){
			/*Ok, the GradJSearch yielded a worse cost function. reloop and increate maxiter by 5 for the rest of the model. As well, 
			 * lower tolx: */
			if(status==0){
				/*tolerance was breached! Are we under 10^-10?: */
				if (workspaceparams->tolx<10^-10){
					/*Ok, we are never converging!: */
					_printf_("%s\n","      convergence failed. getting out!");
					reloop=0;
				}
				else{
					workspaceparams->tolx=workspaceparams->tolx/5;
					_printf_("%s%g\n","      optimization failed. relooping with tolx changed to: ",workspaceparams->tolx);
					reloop=1;
				}
			}
			else{
				/* maxiter was breached. Are we over 50 iterations?: */
				if(workspaceparams->maxiter[step]>50){
					_printf_("%s\n","      convergence failed. getting out!");
					reloop=0;
				}
				else{
					for(i=step;i<workspaceparams->nsteps;i++){
						workspaceparams->maxiter[i]+=5;
					}
					_printf_("%s%g\n","      optimization failed. relooping with maxiter changed to: ",workspaceparams->maxiter[step]);
					reloop=1;
				}
			}
		}
	}
	return reloop;
}


void GradJCheckLocalCleanup(void){
	return;
}
#endif //#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)

