#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <rtl_time.h>
#include <signal.h> 


#define EXEC 11
#define ACTI 22

typedef struct {
  int tipo;
  int id;
  hrtime_t in,out;
} Eventos;

Eventos EV1,EV_resto;

#define N_EVENTS  400
#define FACTOR   1000
Eventos buffer[N_EVENTS];
  int nucleo;

static void cleanup(int signo)
{
    fprintf(stderr, "tracer cleanup (signal %d)\n", signo);
    close(nucleo);
    exit(0);
}

int main()
{
  int i;

  if (signal(SIGSEGV, SIG_IGN) != SIG_IGN) {
      signal(SIGSEGV, cleanup);
  }
  if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
      signal(SIGINT, cleanup);
  }
  if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
      signal(SIGTERM, cleanup);
  }
  if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
      signal(SIGHUP, cleanup);
  }

 /* Print the header neede by the "crono" program the chronogram*/
  printf("TASK 2 \"DOS\"\nTASK 3 \"TRES\"\nTASK 4 \"CUATRO\"\nTASK 5 \"CINCO\"\nTASK 6 \"SEIS\"\nTASK 7 \"SIETE\"\nTASK 8 \"OCHO\"\nTASK 1 \"LINUX\"\n:BODY\n");
  if ( (nucleo = open ("/dev/rtf0",O_RDONLY)) < 0  ) {
      fprintf(stderr, "Error: Can not open /dev/rtf0");
      exit(-1);
  }

  for (i=0; i<N_EVENTS ; i++)  {
          read( nucleo, (char *) &buffer[i], sizeof(Eventos));
  }
  
  for (i=0; i<N_EVENTS ; i++)
          {
                  EV_resto=buffer[i];
                  if (i==0)
                          EV1 = EV_resto;
                  
                  switch (EV_resto.tipo){
                  case EXEC:
                  case ACTI:
                          printf("%s %d %lld %lld\n",
                                 (EV_resto.tipo== EXEC) ? "EXEC": "ACTI",
                                 EV_resto.id+1,
                                 ((EV_resto.in - EV1.in)/ FACTOR),
                                 ((EV_resto.out - EV1.in)/ FACTOR));
                          break;
			  //fflush(stdout);
		  }                 
          }
  
  close(nucleo);
  return 0;
}

