#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h>
#include <math.h>
#include "yagi.h"

/* This function attemnts to optimise by setting the currents of the last N
(user specifies N) directios to have the same magnitude of cureent. We do this
by computing the currents in the last N directors, then finding the sd from the
mean. Then we optimise to reduce the sd. We take as one argument the 'old_sd'
. If we manage to reduce it, we change this value. */

int linear_current_optimisation_test(struct FCOMPLEX *cur, double *old_sd, int elements, int parasites, struct flags flag) 
{
	double mean, SD, current_on_this_element, sum_of_squares=0.0, total_I=0.0;
	int total_elements_tested,k;
	total_elements_tested=flag.Cflg; /* The user wants to test this number */
	if(total_elements_tested > elements -1)
	{
		printf("We can only try to get the currents similar on the %d elements, and we dont have the %d elements that you requsted via the -C option\n", elements-1, flag.Cflg);
		exit(1);
	}
	for(k=elements; k>elements-total_elements_tested; k--)
	{
		current_on_this_element=sqrt(cur[k].r*cur[k].r+cur[k].i*cur[k].i);
		total_I+=current_on_this_element;
	}
	/* find the mean element current */
	mean=total_I/(double)(total_elements_tested);
	/* now find sum of the squares of the deviations form the mean */
	for(k=elements; k>=elements-total_elements_tested; k--)
	{
		sum_of_squares+=pow(sqrt(cur[k].r*cur[k].r+cur[k].i*cur[k].i)-mean,2.0);
	}
	SD=sum_of_squares/(double) (elements-1);
	if(SD <  *old_sd)
	{
		*old_sd=SD;
		return(TRUE); /* currents are closer to being equal */
	}
	else
		return(FALSE);
}
