//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdlib.h>
#include <string.h>
#include "gps.h"

//n番目のフレームのポインタを返す
static char *skip(char *p, int n)
{
	while(n--)
	{
		while(',' != *p++);
	}
	return p;
}

int year, month, day, hour, min, sec;
int mday[] = {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};	//閏年の2月は28日だが省略
char gprmc[128];
char speed[32], latitude[32], longitude[32];

int gps_get_time(char *s)
{
	int res = 0;

	if((0 == strncmp(s, "$GPRMC", 6))
	|| (0 == strncmp(s, "$GNRMC", 6)))
	{
		if('A' == *skip(s, 2))
		{
			res = 1;
		}

		{
			int tmp;

			tmp = atoi(skip(s, 9));
			day = tmp / 10000;
			month = tmp % 10000 / 100;
			year = tmp % 100 + 2000;

			tmp = atoi(skip(s, 1));
			hour = tmp / 10000;
			min = tmp % 10000 / 100;
			sec = tmp % 100;

			//日本時間に補正
			hour += 9;
			if(23 < hour)
			{
				hour -= 24;

				if((2 == month)
				&& (28 == day))
				{
					if(((0 == year % 4) && (0 != year % 100))
					|| (0 == year % 400))
					{
						day = 29;
					}
					else
					{
						month = 3;
						day = 1;
					}
				}
				else
				{
					int days_of_month[] = {31,29,31,30,31,30,31,31,30,31,30,31};

					day += 1;
					if(days_of_month[month - 1] < day)
					{
						day = 1;
						month += 1;
						if(12 < month)
						{
							month = 1;
							year += 1;
						}
					}
				}
			}

			if((2012 < year && year < 9999)
			&& (0 < month && month < 13)
			&& (0 < day && day < mday[month] + 1)
			&& (0 <= hour && hour < 24)
			&& (0 <= min && min < 60)
			&& (0 <= sec && sec < 60))
			{
				;
			}
			else
			{
				res = 0;
			}
		}
	}
	return res;
}

int gps_get_speed(char *s, char *speed)
{
	int res = 0;
	char *p;

	if((0 == strncmp(s, "$GPVTG", 6))
	|| (0 == strncmp(s, "$GNVTG", 6)))
	{
		if('N' != *skip(s, 9))
		{
			for(p = skip(s, 7); ',' != *p; speed++, p++)
			{
				*speed = *p;
			}
			*speed = '\0';

			res = 1;
		}
	}
	return res;
}

int gps_get_position(char *s, char* latitude, char* longitude)
{
	int res = 0;
	char *p;

	if((0 == strncmp(s, "$GPRMC", 6))
	|| (0 == strncmp(s, "$GNRMC", 6)))
	{
		strcpy(gprmc, s);

		for(p = skip(s, 3); ',' != *p; latitude++, p++)
		{
			*latitude = *p;
		}
		*latitude = '\0';

		for(p = skip(s, 5); ',' != *p; longitude++, p++)
		{
			*longitude = *p;
		}
		*longitude = '\0';

		res = 1;
	}
	return res;
}
