#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include "yagi.h"
/* better.c This function compares new and old performance of a yagi to see if
its better. */ 

extern double vswr, Zo;
extern struct performance_data max;
extern int errno;
int is_it_better(int criteria,struct performance_data n, struct performance_data o) 
{
	double resistance_error;
	struct FCOMPLEX zi_new, zi_old;

	resistance_error=fabs(n.r - Zo) - fabs( o.r - Zo );
	zi_new.r=n.r;
	zi_old.r=o.r;
	zi_new.i=n.x;
	zi_old.i=o.x;
	/* printf("o=%.3lfdBi %.3f dB  %.4f:1\n", o.gain, o.fb, o.swr);
	printf("n=%.3lfdBi %.3f dB  %.4f:1\n\n", n.gain, n.fb, n.swr); */
	/* If the user add REASONABLE to the 'better' argument, the program
	will make some intelligent guesses about whats a reasonale antenna. This
	could for example avoid ignoring an antenna with 20dB gain but 1.02:1
	vswr, in favour of 15dB gain but 1.01 vswr. Usually we would consider
	(all other things equal) the former antenna better. Hence we wont 
	bother optimising beyond these */

	if( (criteria & REASONABLE) == REASONABLE)
	{
		if( (n.fb > max.fb) && (n.fb < o.fb))
			n.fb=o.fb; 

		if( (fabs(n.r-Zo) < max.r) && 
		( fabs(n.r-Zo) > fabs(o.r-Zo) ) )
		{
			n.r=o.r;
		}

		if( (n.swr < max.swr) && (n.swr > o.swr) )
			n.swr=o.swr;
		
		if( (fabs(n.x) < max.x) &&
		fabs(n.x) > fabs(o.x)  )
			n.x=o.x;

		if( (n.sidelobe > max.sidelobe) && (n.sidelobe < o.sidelobe) )
			n.sidelobe=o.sidelobe;
	}
	if( (criteria & GAIN) == GAIN)
	{
		if( n.gain < o.gain)
			return(FALSE);
	}
	if( (criteria & FB) == FB)
	{
		if( n.fb < o.fb)
			return(FALSE);
	}
	if( (criteria & RESISTANCE) == RESISTANCE)
	{
		resistance_error=fabs(n.r-Zo)-fabs(o.r-Zo);
		if(resistance_error > 0.0)
			return(FALSE);
	}
	if( (criteria & REACTANCE) == REACTANCE)
	{
		if(fabs(n.x) > fabs(o.x))
			return(FALSE);
	}
	if( (criteria & VSWR) == VSWR)
	{
		if( n.swr > o.swr)
			return(FALSE);
	}
	if((criteria & SIDE_LOBE_LEVEL) == SIDE_LOBE_LEVEL)
	{
		if(n.sidelobe < o.sidelobe)
			return(FALSE);
	}
#ifdef DEBUG
	if(errno)
	{
	fprintf(stderr,"Errno =%d in better.c\n", errno);
	exit(1);
	}
#endif
	return(TRUE);
}

