/*!\file MinVelx
 * \brief: compute misfit between observations and model
 */

#include "./MinVelx.h"

#include "../../shared/shared.h"
#include "../../include/include.h"
#include "../../toolkits/toolkits.h"
#include "../../EnumDefinitions/EnumDefinitions.h"

void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
	
	int i;
	double minvel;
	double node_minvel;
	double element_minvel;

	/*Go through elements, and request velocity: */
	for(i=0;i<elements->Size();i++){
		Element* element=(Element*)elements->GetObjectByOffset(i);
		element->MinVel(&element_minvel,process_units); //go pick up the minimum velocity in the inputs
	
		if(i==0)minvel=element_minvel; //initialize minvel
		else{
			if(element_minvel<minvel)minvel=element_minvel;
		}
	}
	/*A safeguard in case: */
	if(elements->Size()==0){
		minvel=INFINITY;
	}

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

	/*Assign output pointers:*/
	*pminvel=minvel;
}
