/*!\file ControlInputScaleGradientx
 * \brief retrieve gradient from inputs in elements
 */

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

void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* norm_list,int step){

	/*Intermediaries*/
	int     i,j,num_controls;
	int    *control_type = NULL;
	IssmDouble *scalar_list = NULL;
	IssmDouble  scalar;

	/*Retrieve some parameters*/
	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
	parameters->FindParam(&scalar_list,NULL,NULL,InversionGradientScalingEnum);

	/*Compute scaling factor*/
	scalar=scalar_list[0]/norm_list[0];
	for(i=0;i<num_controls;i++){
		scalar=min(scalar,scalar_list[num_controls*step+i]/norm_list[i]);
	}

	for(i=0;i<num_controls;i++){
		for(j=0;j<elements->Size();j++){
			Element* element=(Element*)elements->GetObjectByOffset(j);
			element->ControlInputScaleGradient(control_type[i],scalar);
		}
	}

	/*Clean up and return*/
	xDelete<int>(control_type);
	xDelete<IssmDouble>(scalar_list);
}
