/*!\file:  ThermalConstraintsState.cpp
 * \brief  melting rate constraints
 */ 

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

#include "./ConstraintsStateLocal.h"

void  ThermalConstraintsState(Loads* loads, int* pconverged, int* pnum_unstable_constraints,int configuration_type){

	int i;

	int unstable=0;
	int num_unstable_constraints=0;
	int converged=0;
	int sum_num_unstable_constraints=0;

	num_unstable_constraints=0;	

	/*Enforce constraints: */
	for(i=0;i<loads->Size();i++){
		Object* object=(Object*)loads->GetObjectByOffset(i);
		Load* load=(Load*)object;
		if(load->InAnalysis(configuration_type)){
			if(object->ObjectEnum()==PengridEnum){

				Pengrid* pengrid=(Pengrid*)object;
				pengrid->ConstraintActivate(&unstable);
				num_unstable_constraints+=unstable;
			}
		}
	}

	#ifdef _HAVE_MPI_
	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
	num_unstable_constraints=sum_num_unstable_constraints;
	#endif

	/*Have we converged? : */
	if (num_unstable_constraints==0) converged=1;
	else converged=0;

	/*Assign output pointers: */
	*pconverged=converged;
	*pnum_unstable_constraints=num_unstable_constraints;
}
