#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <pthread.h>
#include "speedo.h"
#include "compute_globals.h"

void *compute_speedo(void *threadid)
{
 int tid;
 struct speedo_msgbuf sbuf;
 int msqid;
 key_t key;
 struct tm *ts;
 char time_str[80];
long delta = 0,delta_bar = 0;
float alpha;
time_t delta_sec;
suseconds_t delta_usec;

alpha = .8;
 
  if ((key = ftok("compute.c", 'A')) == -1) { 
    perror("ftok");
    exit(1);
    }
  key = 1;
  if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */
      perror("msgget");
      exit(1);
      }
        
  for(;;) {
      msgrcv(msqid, (struct speedo_msgbuf *)&sbuf, sizeof(sbuf), SPEEDO_MSGTYPE, 0);
     // if (msgrcv(msqid, (struct speedo_msgbuf *)&sbuf, sizeof(sbuf), 1, 0) == -1) {
     //     perror("msgrcv");
     //     exit(1);
     // }
     pthread_mutex_lock(&speedo_data_mutex); 
     delta_sec = (sbuf.time_sec-speedo_data.time_sec);
     delta_usec = (sbuf.time_usec-speedo_data.time_usec);
     speedo_data.delta_t = (double) delta_sec + ((double) delta_usec)/1000000;
     speedo_data.time_sec = sbuf.time_sec;
     speedo_data.time_usec = sbuf.time_usec;
     speedo_data.speed = sbuf.speed;
     pthread_mutex_unlock(&speedo_data_mutex); 
     }
}
