// MMNmea.cpp: implementation of the MMNmea class.
//
//////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include "MMNmea.h"
#include "Math.h"
#include "Time.h"


#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

MMNmea::MMNmea(double latitude, double longitude /*, int seconds, int nanoseconds*/)
{
  double latDDMMss = 0.0, longDDMMss = 0.0;
  double latDD = 0.0, longDD = 0.0, latMM = 0.0, longMM = 0.0;
  
  latMM = 60.0 * modf( latitude, &latDD );
  longMM = 60.0 * modf( longitude, &longDD );
  
  latDDMMss = (100.0 * latDD) + latMM;
  longDDMMss = (100.0 * longDD) + longMM;
  
  // Time conversion		    
  
  char timeString[40];
  MMUtil::getHHMMss(timeString);
  
  sprintf(m_string,"$GPGLL,%.5lf,%c,%.5lf,%c,%s,A\r\n",
	  fabs(latDDMMss), (latDDMMss > 0.0) ? 'N':'S',
	  fabs(longDDMMss), (longDDMMss > 0.0) ? 'E':'W',
	  timeString
	  );
	/*
	sprintf(m_string,"$GPGGA,%s,%.5lf,%c,%.5lf,%c,\r\n",
	  timeString,
	  fabs(latDDMMss), (latDDMMss > 0.0) ? 'N':'S',
	  fabs(longDDMMss), (longDDMMss > 0.0) ? 'E':'W'
	  );
	*/
}


MMNmea::MMNmea(char* str) :
	MMString(str) {} 


MMNmea::MMNmea(const ModemMessage *pMM) 
{
	Assert(pMM);
	Assert(pMM->getType()==tGetMessageType());
	const char* pcEnd = pcRead(pMM->getBuffer());
	const char* temp = pMM->getBuffer();
	const char* temp2 = pMM->getBuffer()+pMM->getBufferSize();
	Assert(pcEnd==pMM->getBuffer()+pMM->getBufferSize());
}


MMNmea::parseNmea(double* latitude, double* longitude, int* seconds, int* nanoseconds)
{
  char hemisphere, eastwest;
  int success;
  float t;
  char la[16], lo[16], ti[16];
  float lat, lon;

  success = sscanf(m_string,"$GPGGA,%f,%f,%c,%f,%c",&t, &lat, &hemisphere, &lon, &eastwest);

  if (success < 5)
	success = sscanf(m_string,"$GPGLL,%f,%c,%f,%c,%f,", &lat, &hemisphere, &lon, &eastwest,&t);
	
  Assert(success == 5);
	
  sprintf(la,"%f",lat);
  if (lon < 10000) sprintf(lo,"0%f",lon);
  else sprintf(lo,"%f",lon);
  
  sprintf(ti,"%f",t);
  MMUtil::stringToSNS(ti,seconds,nanoseconds);

  *latitude=MMUtil::latitude(la);
  *longitude=MMUtil::longitude(lo);

  *latitude*=(hemisphere == 'N')?1:-1;
  *longitude*=(eastwest == 'E')?1:-1;

  return success;
}
