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

void read_yagi_data(char *one_line, char *input_filename, double *frequency, double *min_frequency, double *max_frequency, double *step_frequency, int driven , double **d, int parasitic, double **p, double *angular_step)
{
	FILE *ifp;
	char *null, *tmp;
	int i;

	null=string(0L,MAX_LINE);

	tmp=string(0L,MAX_LINE);
	ifp=fopen(input_filename, "rt");
	if(ifp == NULL)
	{
		fprintf(stderr,"Sorry, cant find file:  %s\n", input_filename);
		exit(2);
	}
	/* Read one_line by one_line, looking for data on the elements */
	while(!feof(ifp))
	{
		fgets(one_line, MAX_LINE-1, ifp);

		if(strncmp(one_line,"STEP_FREQUENCY",14) == 0)  
		{
			sscanf(one_line,"%s %lf", null, step_frequency);
			*step_frequency*=1e6;
		}
		if(strncmp(one_line,"MIN_FREQUENCY",13) == 0)  
		{
			sscanf(one_line,"%s %lf", null, min_frequency);
			*min_frequency*=1e6;
		}
		if(strncmp(one_line,"MAX_FREQUENCY",13) == 0)  
		{
			sscanf(one_line,"%s %lf", null, max_frequency);
			*max_frequency*=1e6;
		}
		if(strncmp(one_line,"ANGULAR_STEP",12) == 0)  
		{
			sscanf(one_line,"%s %lf", null, angular_step);
		}
		if(strncmp(one_line,"FREQUENCY",9) == 0)  
		{
			sscanf(one_line,"%s %lf", null, frequency);
			*frequency*=1e6;
		}
		if(strncmp(one_line,"DATA_PARASITIC",14) == 0)  
		{
			one_line+=14;
			for(i=1;i<=parasitic; ++i)
			{
				fgets(one_line, MAX_LINE-1, ifp);
				sscanf(one_line,"\n%lf %lf %lf %lf",&p[i][X], &p[i][Y], &p[i][LENGTH], &p[i][DIAMETER] );
			}
		}
		if(strncmp(one_line,"DATA_DRIVEN",11) == 0)  
		{
			one_line+=11; /* skip DATA_DRIVEN */
			for(i=1;i<=driven; ++i)
				sscanf(one_line, "%lf %lf %lf %lf %lf %lf\n", &d[i][X], &d[i][Y], &d[i][LENGTH], &d[i][DIAMETER], &d[i][VOLTAGE_R], &d[i][VOLTAGE_I]);
		}
	}
	fclose(ifp);
	if(*min_frequency > *max_frequency || *angular_step <= 0 || *step_frequency <=0.0 || *frequency <=0.0 )
	{
		fprintf(stderr,"Error in input file %s. Please check:\n", input_filename);
		fprintf(stderr,"FREQUENCY, MIN_FREQUENCY, MAX_FREQUENCY, STEP_FREQUENCY and ANGULAR_STEP\n");
		exit(1);
	}

	free_string(null,0L,MAX_LINE); 
	free_string(tmp,0L,MAX_LINE); 
}

