/***
gps_test.c
Z-World, 2001

Sample program using GPS.LIB to retreive time and position from a GPS
receiver.

A GPS receiver operating in standard NMEA-1803 mode (4800 baud, 8N1) must be
connected to serial port C.

The program will first demonstrate use of the gps_ground_distance() function
by calculating between San Francisco and Los Angeles using known coordinates
for those cities.
The program will then start to listen for GPS data on port C. Any sentences
received will be parsed with both gps_get_position() and gps_get_utc().
When either of these functions parses valid data, the results are printed
to the STDIO window.

****/
#class auto

#use "gps.lib"

#define CINBUFSIZE 127
#define COUTBUFSIZE 127

#define MAX_SENTENCE 100

// names of days of week
const char dayname[7][4] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
const char monthname[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

GPSPosition current_pos;
struct tm current_time;

void main()
{
	char sentence[MAX_SENTENCE];
	int input_char;
	int string_pos;
	char dir_string[2];


	//calculate distance from known coordinates
	GPSPosition la_loc, sf_loc;

	la_loc.lat_degrees = 34;
	la_loc.lat_minutes = 00.0;
	la_loc.lat_direction = 'N';
	la_loc.lon_degrees = 118;
	la_loc.lon_minutes = 15.0;
	la_loc.lon_direction = 'W';

	sf_loc.lat_degrees = 37;
	sf_loc.lat_minutes = 45.0;
	sf_loc.lat_direction = 'N';
	sf_loc.lon_degrees = 122;
	sf_loc.lon_minutes = 27.0;
	sf_loc.lon_direction = 'W';
			
	serCopen(4800);	
	string_pos = 0;
	dir_string[1] = 0;

	printf("SF to LA:%f km\n", gps_ground_distance(&sf_loc, &la_loc));
	
	//receive and parse GPS data
	while(1)
	{
		input_char = serCgetc();
		if(input_char == '\r' || input_char == '\n')
		{
			sentence[string_pos] = 0; //add null
			//printf("%s\n", sentence);
			if(gps_get_position(&current_pos, sentence) == 0)
			{
				dir_string[0] = current_pos.lat_direction;
				printf("Latitude: %d %f' %s\n",
					current_pos.lat_degrees, current_pos.lat_minutes,
					dir_string);
				dir_string[0] = current_pos.lon_direction;
				printf("Longitude: %d %f' %s\n",
					current_pos.lon_degrees, current_pos.lon_minutes,
					dir_string);
	
			}
			if(gps_get_utc(&current_time, sentence) == 0)
			{
				printf("UTC: %s %d-%s-%d %02d:%02d:%02d\n",
					dayname[current_time.tm_wday],
					current_time.tm_mday,
					monthname[current_time.tm_mon - 1],
					1900 + current_time.tm_year,
					current_time.tm_hour,
					current_time.tm_min,
					current_time.tm_sec );
			}
			string_pos = 0;
		}
		else if(input_char > 0)
		{
			sentence[string_pos] = input_char;
			string_pos++;
			if(string_pos == MAX_SENTENCE)
				string_pos = 0;	//reset string if too large
		}
	}
		
}
