/**** GPS skrysohledac ****/
#define ID "$Id: gps.c 984 2008-01-06 23:41:31Z kakl $"

#include "gpsrl.h"

#include <math.h>
#include <stdlib.h>
#include <stdlibm.h>

#define  SCINTILAK   1           //kanal adc pro scintilacni detektor NB3201
#define  RANGE       PIN_A4      // vystup detektoru urcujici rozsah mereni.


#define  LCD_RS         PIN_B1      // LCD control
#define  LCD_E          PIN_B2      // LCD enable
#define  LCD_DATA_LSB   PIN_B4      // LSB data bit LCD
#include "MYLCD.C"

#define  TL1   PIN_C0
#define  TL2   PIN_C1
#define  TL3   PIN_C2

// NMEA
#define  TIME           6           // For NMEA parsing
#define  TIME_LEN       10
#define  LATDEG         19
#define  LATMIN         21
#define  LONDEG         32
#define  LONMIN         34
#define  SAT            36
#define  DEG_LEN        2
#define  MIN_LEN        7
#define  AZIMUTH        46
#define  NMEA_LINESIZE  79

//$GPRMC,105815.503,V,4915.5877,N,01442.3896,E,0.0,0.00,060108,,,N*44

void main()
{

   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_INTERNAL);
   setup_spi(FALSE);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(VREF_LOW|-2);
   lcd_init();

   delay_ms(100);
   lcd_gotoxy(5,1);
   printf(lcd_putc,"GPSRL01B \n");
   printf(lcd_putc,"(c) Kaklik 2008");
   delay_ms(300);
   printf(lcd_putc,"\f");
   
   set_adc_channel(SCINTILAK);

   while(TRUE)
   {

   auto char line[NMEA_LINESIZE];
   char item[16];
   char *ptr;
   int8  n;
   char  c;


//      line=malloc(NMEA_LINESIZE);        // Space for one line
//      if (line==NULL) {printf(lcd_putc,"Error"); sleep();};
      line[NMEA_LINESIZE-1]=0;

      while(fgetc(NMEA)!='$');            // Waiting for start character
      for(n=0;n<(NMEA_LINESIZE-1);n++)    // Read line up to checksum
      {
         c=fgetc(NMEA);
         if(c=='*')
         {
            line[n]=0;
            break;
         };
         line[n]=c;
      };

   printf(lcd_putc,"\f");

if(!input(TL1))
{
    lcd_gotoxy(1,1);
      strncpy(item,&line[LATDEG],DEG_LEN+MIN_LEN); item[DEG_LEN+MIN_LEN]=0;
      printf(lcd_putc,"%s \n",item);

      strncpy(item,&line[LONDEG],DEG_LEN+MIN_LEN); item[DEG_LEN+MIN_LEN]=0;
      printf(lcd_putc,"%s",item);

}
else
{
    lcd_gotoxy(1,1);
    printf(lcd_putc,"Time %06.0g \n",strtod(&line[TIME],&ptr));
    printf(lcd_putc,"sats %06.0g ",strtod(&line[SAT],&ptr));
}

puts(line,PC);

//     free(line);
   }
}