/*!\file ElementResponsex
 * \brief: compute element input  on one element only
 */

#include "./ElementResponsex.h"

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

void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
	

	extern int my_rank;
	int i;

	int found=0;
	int sumfound=0;
	int cpu_found=-1;
	int index;
	double response;
	Element* element=NULL;

	/*retrieve element we are interested in: */
	parameters->FindParam(&index,IndexEnum);

	/*now, go through our elements, and retrieve the one with this id: index: */
	for(i=0;i<elements->Size();i++){
		element=(Element*)elements->GetObjectByOffset(i);
		if (element->Id()==index){
			found=1;
			cpu_found=my_rank;
			break;
		}
	}

	/*Broadcast whether we found the element: */
	#ifdef _HAVE_MPI_
	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
	if(!sumfound)_error2_("could not find material with id" << index << " to compute ElementResponse");
	#endif

	/*Ok, we found the element, compute responseocity: */
	if(my_rank==cpu_found){
		element->ElementResponse(&response,response_enum,IuToExtEnum);
	}

	/*Broadcast and plug into response: */
	#ifdef _HAVE_MPI_
	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
	MPI_Bcast(&response,1,MPI_DOUBLE,cpu_found,MPI_COMM_WORLD); 
	#endif

	*presponse=response;
}
