#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
#include <signal.h>
#include <stdbool.h>


#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <math.h>

#include <gps.h>


void sigchld_handler(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0);
}


int main(int argc, char *argv[])
{
int n;
int fd_max;
///struct gps_data_t gpsNMEAData;
struct gps_data_t gpsJSONData;
char *buf;
///char nmea_msg[255];
char json_buf[1024];
char cmd[255];
int ret;
fd_set rfds;
struct timeval tv;  //Time value for select timeout.


///int sockfd;
///struct sockaddr_in their_addr; // connector's address information
///struct hostent *he;
///int numbytes;
///int broadcast = 1;
///int nbytes;
int date_set = 0;


double seconds_since;

          // Set up gpsd reading
            ///ret = gps_open("127.0.0.1","2947",&gpsNMEAData);
            ///printf("gps_open returns %d\n",ret);
            ret = gps_open("127.0.0.1","2947",&gpsJSONData);
            printf("gps_open returns %d\n",ret);

            (void) gps_stream(&gpsJSONData, WATCH_ENABLE | WATCH_JSON, NULL);

            while(!date_set)
            {
            FD_ZERO(&rfds);  // Clear file descriptor set.
            FD_SET(gpsJSONData.gps_fd, &rfds);  //Add this file descriptor to set
            errno = 0; 
            tv.tv_sec = 1;
            tv.tv_usec = 0;
            fd_max = gpsJSONData.gps_fd;
            printf("about to select: fd_max = %d\n",fd_max);
            ret = select(fd_max+1,&rfds,NULL,NULL,&tv);
	    printf("back from select\n");

            
            gpsJSONData.set = 0;  //Clear this to see most recently set flags.
            if(FD_ISSET(gpsJSONData.gps_fd,&rfds))
              {
                 
                 errno = 0;
               
                 //nbytes = read(gpsJSONData.gps_fd,json_buf,1024);
	         //printf("JSONRAW2: %d %s\n",nbytes,json_buf);
		 //memset(json_buf, 0, 512);

                 if(gps_read(&gpsJSONData) == -1)
                   { 
                   printf("gps_read returns -1\n");
                   } 
 		 else
	 	   { 


	           buf = gps_data(&gpsJSONData);
                   printf("JSON2: gps_data returns: %s\n",buf);

                   if(gpsJSONData.set & SPEED_SET) //New TPV data available (indicated by SPEED_SET bit set)
	             {

		     sprintf(cmd,"date -s @%d'",(int) gpsJSONData.fix.time);
		     ret = system(cmd);
	             printf("%s command returns %d\n",cmd,ret);
		     date_set = 1;

                     }

                   }
               
             }

	 }
	
	
}

