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

#include "./SurfaceAverageVelMisfitx.h"

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

void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel){

	/*Intermediary*/
	Element* element=NULL;

	/*output: */
	IssmDouble J = 0.;
	IssmDouble J_sum;

	/*Compute surface area and add to elements inputs */
	SurfaceAreax(NULL,femmodel);

	/*Compute Misfit: */
	for(int i=0;i<femmodel->elements->Size();i++){
		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
		J+=element->SurfaceAverageVelMisfit();
	}

	/*Sum all J from all cpus of the cluster:*/
	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
	J=J_sum;

	/*Assign output pointers: */
	*pJ=J;
}
