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

#include "yagi.h"

extern int errno;
/* The function automatic_enhancement optimises only for the gain, by 
adjusting the length of the reflector (A=-1), the driven(A=0) the 
first director (A=1), second director (A=2 ) etc */

void automatic_enhancement(struct flags flag, double frequency, double **driven_data, double **parasitic_data, int driven, int parasites, struct FCOMPLEX *voltage, struct FCOMPLEX *current, struct FCOMPLEX *input_impedance, double *v, double **z,double **A, double *b, int *indx, struct element_data *coordinates)
{
	int elements,element;
	double pin,E_fwd=0,H_fwd,max_gain=0.0,old_max=0.0;
	elements=driven+parasites;
	element=flag.Aflg-1000;
	if(element > parasites-1)
	{
		fprintf(stderr,"You have set the option '-A%d', which will maximise gain using director number %d, but there are only %d directors\n", element,element, parasites-1);
		exit(1);
	}
	if(element>0) /* optimise gain by adjusting a director */
	{
			parasitic_data[element+1][LENGTH]*=0.90;
			max_gain=0.0;
			old_max=0.0;
			do{
				parasitic_data[element+1][LENGTH]*=1.001;
				solve_equations(frequency, driven, parasites, driven_data, parasitic_data, v, z, &pin, voltage, current, input_impedance, coordinates, A, b, indx);
				gain(90.0,0.0,pin,1.0,coordinates,current,elements,&E_fwd,&H_fwd,frequency,frequency);
				if(E_fwd>max_gain)
				{
					old_max=max_gain;
					max_gain=E_fwd;
				}
			} while(E_fwd>old_max);
	}
	else if(element==-1) /* Optimise gain by adjeucting reflector */
	{
		parasitic_data[1][LENGTH]*=0.90;
		max_gain=0.0;
		old_max=0.0;
		do{
			parasitic_data[1][LENGTH]*=1.001;
			solve_equations(frequency, driven, parasites, driven_data, parasitic_data, v, z, &pin, voltage, current, input_impedance, coordinates, A, b, indx);
			gain(90.0,0.0,pin,1.0,coordinates,current,elements,&E_fwd,&H_fwd,frequency,frequency);
			if(E_fwd>max_gain)
			{
				old_max=max_gain;
				max_gain=E_fwd;
			}
		} while(E_fwd>old_max);
	} 
	else if(element==0) /* Optimise gain by adjeucting driven-element */
	{
		driven_data[1][LENGTH]*=0.90;
		max_gain=0.0;
		old_max=0.0;
		do{
			driven_data[1][LENGTH]*=1.001;
			solve_equations(frequency, driven, parasites, driven_data, parasitic_data, v, z, &pin, voltage, current, input_impedance, coordinates, A, b, indx);
			gain(90.0,0.0,pin,1.0,coordinates,current,elements,&E_fwd,&H_fwd,frequency,frequency);
			if(E_fwd>max_gain)
			{
				old_max=max_gain;
				max_gain=E_fwd;
			}
		} while(E_fwd>old_max);
	} 
}
