/**************************** gps-analyzer **********************************/
/* Tobias Weis, tobias.weis@gmx.de					    */
/*									    */
/* Analyzes NMEA-Logfiles and prints speed, average speed and km's          */
/* Dump the output to a file and gnuplot it!				    */
/*									    */
/* www.infolexikon.de/blog/jogging-gps-und-gnuplot/			    */
/* ------------------------------------------------------------------------ */
/* TODO									    */
/* - Minuten über die Stunden brechen, kein Bock jetzt			    */
/* - Vergleich von mehreren Dateien, Verbesserungen ausrechnen,		    */
/*   generell bessere Statistiken für Langzeitauswertung?		    */
/* - Glättung/Löschen von fehlerhaften Daten
/****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main(){
	string line, time, time_all;
	float time1_h = -1;
	float time1_m, time2_h,time2_m;
	int x = 0, y = 0, i = 0, count = 0;
	double zahl, speed_sum = 0, middle_speed = 0;

	fstream test("./test-data.nmea", ios::in);
	while(!test.eof()){
		getline(test, line, '\n');
			/* in der $GPVTG-Zeile stehen die km/h-Infos */
			if(line.find("GPVTG",0) == 1){
				x = line.find(",", 0);
				y = x;
				for(i=0;i<9;++i){
					x = line.find(",", x);
					if(x-y != 0 && i == 7){
						/* Umwandlung der km/h in Integer */
						stringstream sstr(line.substr(y+1, (x-y)-1));
						sstr >> zahl;
						/* Zu hohe (Fehler) Werte ignorieren */
						if(zahl >= 0 && zahl < 30){
							speed_sum += zahl;
							count++;
						}
						/* Durchschnittsgeschwindigkeit ausrechnen */
						middle_speed = speed_sum / count;
					}
					/* y ist erste Komma-Pos, x wird erhöht, wird zweite Komma-Post */
					y = x;
					x++;
				}
			}


			if(line.find("GPGGA",0) == 1){
				x = line.find(",", 0);
				y = x;
				for(i=0;i<14;++i){
					x = line.find(",", x);
					if(x-y != 0 && i == 1 && zahl>=0 && zahl < 30){
							time = line.substr(y+1, (x-y)-1);
							if(time.length() > 5){
								/* Umwandlung von h & m in Integer */
								stringstream sstr1(time.substr(0,2));
								stringstream sstr(time.substr(2,2));
								/* time1 ist Startzeit */
								if(time1_h == -1){
									sstr1 >> time1_h;
									sstr >> time1_m;
								}else{
								/* time2 ist Endzeit */
									sstr1 >> time2_h;
									sstr >> time2_m;
								}
								
								time = time.substr(0,2) + "." + time.substr(2,2) + time.substr(4,2);
								cout << time << "; " << zahl << "; " << fixed << middle_speed << "; " << middle_speed/(60/(time2_m - time1_m + 1)) << endl;
							}
					}
					/*if(i == 2){
						cout <<  "--> LÄNGENGRAD ==" << line.substr(y+1, (x-y)-1) << endl;
					}
					if(i == 4){
						cout << "--> BREITENGRAD ==" << line.substr(y+1, (x-y)-1) << endl;
					}
					*/
					y = x;
					x++;
				}
			}
	}
}
	

