/* file pdiario.c
	Programa para promediar el valor del barometro mensual
*/

#include<stdio.h>
#include<time.h>
#include<dos.h>

int dias[32]={1,31,28,31,30,31,30,31,31,30,31,30,31};
FILE *hd1,*hd2;
char file_o1[40];
char file_o2[40];
char ch[2];
int i,j,anio,mes,dia;

struct time t;
struct date d;

//  §¦1!2"3ú4$5%6&7/8(9)0='?­¨‡€+*¤¥,;.:-_

main()
{       printf("\nIntroducir los 4 d¡gitos del a¤o: ");
	scanf("%d",&anio);
	printf("\nIntroducir el n£mero de mes que se desea generar: ");
	scanf("%d",&mes);

	gettime(&t);
	getdate(&d);

	if((anio%4)==0)dias[2]=29;
	else dias[2]=28;

	for(dia=1;dia<=dias[mes];dia++)
	{	sprintf(file_o1,"B%02d%02d%02d.asc",anio%100,mes,dia);
		if(promediar_y_actualizar_mes()==1)printf("X-%d ",dia);
		else printf("\nPromediado file %s",file_o1);
	}
	fcloseall();
}

promediar_y_actualizar_mes()
{
char btime[20],param[20],btimep[20];
char n[20];
float d1,d2;
int d3,k,kp,ko;
FILE *hd1,*hd2;
//	if(strcmp(file_o1,file_o2))return 0;
	hd1=fopen(file_o1,"r");
	if(hd1==NULL)return 1;
	sprintf(file_o2,"B%02d%02d.asc",anio%100,mes);	//d.da_year%100,d.da_mon);
	hd2=fopen(file_o2,"a");
	if(hd2==NULL)return 2;
	i=0;
	d1=0;
	j=1;
	kp=1;
	ko=0;	//Estado inicial
	do
	{	fscanf(hd1,"%s %f %s %s %s",btime,&d2,param,n,n);
		d3=atoi(&btime[10]);

		if(d3<20)k=1;
		else	if(d3<40)k=2;
			else	if(d3<60)k=3;

		if(ko==0){	kp=k;	ko=1;
				strcpy(btimep,btime);	//solo al principio
			 }

		if(kp==k){ d1=d1+d2; 	i++;}
		else
		{
			d1=d1/i;
			fprintf(hd2,"\n%s  %8.3f  %s",btimep,d1,param);
			d1=d2;
			i=1;
			kp=k;
			strcpy(btimep,btime);
		}
	}while(!feof(hd1));
		d1=d1/i;
		fprintf(hd2,"\n%s  %8.3f  %s",btimep,d1,param);

	fclose(hd1);
	fclose(hd2);
	strcpy(file_o2,file_o1);
}

