#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
/* This function solves all the simultaneous equatons and returns a
double which increases with a better antenna. */

#include <stdio.h>
#include <errno.h>

#include "yagi.h"

extern int errno;
extern struct performance_data max, weight;

double get_genetic_algorithm_fitness(struct flags flag, double frequency, int driven, int parasitic, double **driven_data, double **parasitic_data, double *v, double **z, double *pin, struct FCOMPLEX *voltage, struct FCOMPLEX *current, struct FCOMPLEX *input_impedance, struct element_data *coordinates, double **A, double  *b, int *indx, struct performance_data *data2) 
{
	double result, E_fwd, E_back, H_fwd,
	H_back; 
	double mag, phase;
	int elements;
	struct performance_data data,start;
	start.gain=0.0;
	elements=driven+parasitic;
	solve_equations(frequency, driven, parasitic, driven_data, parasitic_data, v, z, pin, voltage, current, input_impedance, coordinates, A, b, indx);
	/* compute gain at theta=90, phi=0 (forward direction) */
	gain(90,0,*pin,1.0,coordinates,current,elements,&E_fwd,&H_fwd,frequency,frequency);
	/* now compute gain in the reverse direction */
	gain(270,0,*pin,1.0,coordinates,current,elements,&E_back,&H_back,frequency,frequency);
	data.gain=E_fwd;            /* in dB */
	data.fb=E_fwd-E_back; /* gains are already in dB, so subtract */
	data.r=input_impedance->r;
	data.x=input_impedance->i;
	reflection_coefficient(*input_impedance, &mag, &phase);
	data.swr=calculate_vswr(mag);
	if((flag.gflg&SIDE_LOBE_LEVEL)==SIDE_LOBE_LEVEL)
		data.sidelobe=find_max_sidelobe_fast(E_fwd, *pin,coordinates, \
		current,elements,frequency,frequency);
	else
		data.sidelobe=0.0;
	*data2=data;
	result=performance(flag, data, max, weight, start);

#ifdef DEBUG
	if(errno)
	{
		fprintf(stderr,"Errno =%d in fitness.c\n", errno);
		exit(1);
	}
#endif
	return (result);
}
