/*
bintotxt src dest year
*/

#include <stdio.h>
#include <io.h>
#include <string.h>
#include <math.h>

#define conv_fact 0.787f

void decodeTime(unsigned char *RtcBuffer, unsigned char *year, unsigned char *month, unsigned char *day,
			unsigned char *hours, unsigned char *minutes, unsigned char *seconds, unsigned char *hundredths)
{
    *hours=10*(RtcBuffer[3] >> 4 & 0x3) + (RtcBuffer[3] & 0xf);
    *minutes=10*(RtcBuffer[2] >> 4) + (RtcBuffer[2] & 0xf);
    *seconds=10*(RtcBuffer[1] >> 4) + (RtcBuffer[1] & 0xf);
    *hundredths=10*(RtcBuffer[0] >> 4) + (RtcBuffer[0] & 0xf);
    *year=RtcBuffer[4]>>6;
    *month=10*(RtcBuffer[5] >> 4 & 0x1) + (RtcBuffer[5] & 0xf);
    *day=10*(RtcBuffer[4] >> 4 & 0x3) + (RtcBuffer[4] & 0xf);
}

struct csomag {
	unsigned short int sampling_period; // mintavételezés periódusideje ms-okban
	unsigned short int puffer_tele; // ennyi elemet gyujt a pufferbe	
	unsigned short int osszeg; // elemek összege
    unsigned short int atlag; // elemek átlaga
	unsigned short int szoras; // elemek szórása
	unsigned short int szorzo;	// ennyivel kell leosztani a minumumot, a maximumot, az átlagot és a szórást
	unsigned short int minv; // legkisebb érték
	unsigned short int maxv; // legnagyobb érték
} cs;

void conv(char *src, char *dst, char *ev)
{
  unsigned char RtcBuffer[6];
  unsigned char year, month, day, hours, minutes, seconds, hundredths;
  int i,emonth=1;
  float osszseb=0.0f,elsoseb;

  FILE *fbe = fopen(src,"rb");
  FILE *fki = fopen(dst,"wt");

  printf("%s --> %s\n",src,dst);

  fprintf(fki,"Datum\tIdo\tAtlag\tSzoras\tMin\tMax\tSebesseg(m/s)\n");

  i=0;
  while (!feof(fbe)) {
    float atlagf,szorasf;

    fread(RtcBuffer,1,6,fbe);
    fread(&cs,1,sizeof(cs),fbe);

    decodeTime(RtcBuffer,&year,&month,&day,&hours,&minutes,&seconds,&hundredths);

    if (month < emonth) ev[3]++;
    emonth = month;

	fprintf(fki,"%s-%d-%d\t%d:%d:%d\t",ev,month,day,hours,minutes,seconds);
//	fprintf(fki,"%d\t",cs.sampling_period);
//	fprintf(fki,"%d\t",cs.puffer_tele);
//	fprintf(fki,"%d\t",cs.osszeg);
//    atlagf = cs.osszeg/(float)cs.puffer_tele;
//    szorasf = (float)cs.szoras/(cs.szorzo*cs.puffer_tele);

	fprintf(fki,"%f\t",(float)cs.atlag/cs.szorzo);
	fprintf(fki,"%f\t",(float)cs.szoras/cs.puffer_tele/cs.szorzo);
	fprintf(fki,"%f\t",(float)cs.minv/cs.szorzo);
	fprintf(fki,"%f\t",(float)cs.maxv/cs.szorzo);
	fprintf(fki,"%f\n",(float)conv_fact*cs.atlag/cs.szorzo);	

  }
  fclose(fbe);
  fclose(fki);
}

int main(void) {
  struct _finddata_t find;
  int h = _findfirst ("*.*", &find);
  char ev[10];
  if (h != -1)
  printf("Year: "); scanf("%s",ev);
  do {
    if (strlen(find.name) == 11 && find.name[strlen(find.name)-3] == '.') {
       char ofn[128];
       strcpy(ofn,find.name);
       strcat(ofn,".txt");
       conv(strdup(find.name),ofn,ev);
    }

  } while (!_findnext (h, &find));
  _findclose(h);
  return 0;
}

