//#include <iostream>
#include <sys/time.h>
#include <stdlib.h>
//#include <stream.h>
//#include <iostream.h>
//#include <fstream>
#include <stdio.h>
//#include <string>
#define WS_2_TABLE_MAX_ELEM 873
#include <errno.h>




char ws_char[2]={'A','B'};
//clock_t tt;
long lsec;
struct timeval tv;        
struct timezone tz;
int step;

// 

int main(int argc, char *argv[])
{
  int sec,i,n,step,mins,real_step,j,current_time,time_hole,start_time;
  FILE *F;
  const char *fname_prefix=argv[1];
  const char *timesync=argv[2];
  static char fname[102];
  if (argc != 7)
    {
      printf("Mancano i parametri!: \n  fname_prefix timesync time_hole n-rows-in_table mins step\n");
      return 1;
    }
  
  time_hole=atoi(argv[3]);
  n   = atoi(argv[4]);
  if(n>WS_2_TABLE_MAX_ELEM) 
    {
      printf("n > %d\n",WS_2_TABLE_MAX_ELEM);;
      return 1;

    }

  mins = atoi(argv[5]);
  step = atoi(argv[6]);
  i = 0;
  if(step < mins)
    {
      printf("step < mins");
      return 5;
    }
  gettimeofday(&tv,&tz);
  srand(tv.tv_sec);
  current_time=atoi(timesync);
  for(i=0;i<16;i++) 
    {

      sprintf(fname,"%s%d.txt",fname_prefix,i);
      F=fopen(fname,"w+");
      if(!F) {
	printf("error %d creating file %s",errno,fname);
	return 4;
      }
      //      of.open(fname);
      start_time=current_time;
      fprintf(F,"%d\n%d\n",start_time,i);

      for(j=0;j<n;j++) 
	{
	  /*	  do  {

	    real_step = lsec % step;
	  } while(real_step <= mins);
	  */
	  real_step =  mins+(int) ((step-mins+1)*1.0*rand()/(RAND_MAX+1.0));
	  fprintf(F,"%c %d\n",ws_char[(real_step %2)],real_step);
	  current_time += real_step*8;
	}
      close(F);
      printf("txable: %d tsync: %d - stop at %d\n",i,start_time,current_time);
      current_time += time_hole;
    }
  return 0;
}
