/*!\file TimeAdaptx
*\brief: update time steps to respect CFL condition
 */

#include "./TimeAdaptx.h"
#include "../modules.h"
#include "../../include/include.h"
#include "../../toolkits/toolkits.h"
#include "../../EnumDefinitions/EnumDefinitions.h"
#include "../../Container/Container.h"

void TimeAdaptx(IssmDouble* pdt, Elements* elements, Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters){

	int      i;

	/*output: */
	IssmDouble   dt;

	/*intermediary: */
	Element *element     = NULL;
	IssmDouble   min_dt      = 0;
	IssmDouble   node_min_dt = 0;

	/*Go through elements, and figure out the minimum of the time steps for each element (using CFL criterion): */
	element=(Element*)elements->GetObjectByOffset(0); min_dt=element->TimeAdapt();
	
	for (i=1;i<elements->Size();i++){
		element=(Element*)elements->GetObjectByOffset(i);
		dt=element->TimeAdapt();
		if(dt<min_dt)min_dt=dt;
	}

	/*Figure out minimum across the cluster: */
	#ifdef _HAVE_MPI_
	MPI_Reduce (&min_dt,&node_min_dt,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
	MPI_Bcast(&node_min_dt,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
	min_dt=node_min_dt;
	#endif

	/*Assign output pointers:*/
	*pdt=min_dt;
}
