#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 "gps.h"
#include "compute_globals.h"

void *compute_gps(void *threadid)
{
 int tid;
 struct gps_msgbuf gpsbuf;
 int msqid;
 key_t key;
 time_t delta_sec;
 suseconds_t delta_usec;
 
  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 gps_msgbuf *)&gpsbuf, sizeof(gpsbuf), GPS_MSGTYPE, 0);
     // if (msgrcv(msqid, (struct gps_msgbuf *)&sbuf, sizeof(gpsbuf), 1, 0) == -1) {
     //     perror("msgrcv");
     //     exit(1);
     // }
     pthread_mutex_lock(&gps_data_mutex); 
     delta_sec = (gpsbuf.time_sec-gps_data.time_sec);
     delta_usec = (gpsbuf.time_usec-gps_data.time_usec);
     gps_data.delta_t = (double) delta_sec + ((double) delta_usec)/1000000;
     gps_data.time_sec = gpsbuf.time_sec;
     gps_data.time_usec = gpsbuf.time_usec;
     gps_data.lat = gpsbuf.lat;
     gps_data.lon = gpsbuf.lon;
     gps_data.elev = gpsbuf.elev;
     gps_data.cog = gpsbuf.cog;
     gps_data.sog = gpsbuf.sog;
     gps_data.gps_time = gpsbuf.gps_time;

     pthread_mutex_unlock(&gps_data_mutex); 
     }
}
