

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#include "utility.h"
#include "station.h"

#define MAX_STATIONS 10000


station_type *stations;
unsigned int num_stations = 0;


int max_temp = -10000;
int min_temp = 100000;








void add_station(char *line)
{
    station_type t;

    t.data_valid = false;


    char tmp[400];
  
    sprintf(tmp, "Station line: (%s)", line);
   
 //   write_console(tmp);  
    
    
    int lat_deg, lat_min;
    int lon_deg, lon_min;        
    char lat_dir, lon_dir;

    
    sscanf(line+39,"%2d", &lat_deg);
    sscanf(line+42,"%2d", &lat_min);
    sscanf(line+44,"%c", &lat_dir);

    sscanf(line+47,"%3d", &lon_deg);
    sscanf(line+51,"%2d", &lon_min);
    sscanf(line+53,"%c", &lon_dir);
    
    memcpy(t.id, line+20, 4);
    t.id[4] = 0;
    
    if (t.id[0] == ' ') return;

//    console("(%s)\n", t.id);   
  
    
    t.pos.lat = ((float)lat_deg + (float)lat_min / 60.0);
    t.pos.lon = ((float)lon_deg + (float)lon_min / 60.0);
 
    if (lat_dir == 'S') t.pos.lat *= -1; 
    if (lon_dir == 'E') t.pos.lon  *= -1;
 
 
 
    t.pos.elv = 1;
  //  t.temp = (rand()%10000) / 100.0;
        
    
    sprintf(tmp,"Lat dir: (%c)  Lon dir: (%c) \n", lat_dir, lon_dir);
    
 //  write_console(tmp);     
     
     
    stations[num_stations++] = t;
}







void load_stations ( char *filename )
{
    num_stations = 0;    

    char tmp[400];
    
    console("Loading stations\n");
    
    
    FILE *f = fopen(filename, "rt");
        
    if (!f)
    {
        log("unable to load station file");
        return;
    }
        
     stations = (station_type *) malloc(MAX_STATIONS * sizeof(station_type));
    
    if (stations == NULL)
    {
      log("Unable to get station memory");
      return;  
        
    }
    
    bool done = false;



   int mode = 0;

    
    while (!done)
    {
        char line[256];
        const unsigned int max = 255;
       
        if (fgets(line, max, f) != NULL)
        {
            if (mode == 0)  // Comment mode
            {
                if (line[0] == '\n') // next will be a state
                    mode = 1;
            } else
            if (mode == 1)      // Read state
            {
                //write_console(line);
             
                mode =2 ;   
            } else
            if (mode == 2)   //  Read stations in state
            {
                if (line[0] == '\n')   // Done with stations 
                    mode = 1; else
                    // read station data
                 {

               // write_console(line);
                      add_station(line);  
               
                        
                }
            }
            
        }
        if (feof(f)) done = true;
        
    }
    
    fclose(f);

 
    
}




void free_stations( void )
{
    
 free(stations);   
    
    
    
}


/* Get text space delimited token from string */
int next_token(char * data, char *token, unsigned int &i)
{
    // No more data
    if (data[i] == '\0' || data[i] == '\n') return(0);
    
    unsigned int ti = 0;

    // Copy until space, newline or NULL
    while (data[i] != 0 && data[i] != '\n' && data[i] != ' ')
        token[ti++] = data[i++];

    token[ti] = 0;  // Add null to token
       
    if (data[i] == ' ') i++; // Eat space

    return(1);      // Data okay
}
/* End of next_token */





void data_line( char *line)
{   
//   unsigned int i = 0;
   
  //  log("Line: (%s) \n", line);

    char * token = strtok (line, " ");  // First get staion id
  
    station_data_type d;

   
     //  log ("Token: (%s)\n", token);
   
    if (token == NULL)
   {
    
        return;
        
    }
     
   
   
   
    char id[5];
  
    if (strlen(token) < 5) strcpy(id, token); else
    {
        log("Station name too long: %s\n", token);
        return;        
    }
    
    token = strtok (NULL, " "); // Get time
  
    if (strlen(token) < 10) strcpy(d.time, token); else
    {
        log("Station time too long: %s\n", token);
        return;        
    }
    
      
   // log("Station: %s\n", id);
   // log(" Time: %s\n", d.time);
      
    // Get station index
    

    unsigned int s_index = 0;
    
    for (s_index = 0; s_index < num_stations; s_index++)
    {
//        console("Source: %s  compare %s\n", id, stations[i].id);


        if(!strcmp(stations[s_index].id, id)) break;    
        
    }   
   
   if (s_index == num_stations)
   {
        log("Unable to find station (%s)\n", id);
        return;
    }


   
   
  
    // Get other data
    while (token = strtok (NULL, " "))
    {

        unsigned int i = 0;
        
        if ( strstr (token, "/"))
        {
            unsigned int t, r;
            unsigned int mod = 0;

            if (token[0] == 'M') mod = 1;

                r = sscanf(token + mod, "%d/", &t);

                 d.temp = t;
                  
                  if (mod) d.temp *= -1;
                  
            
        }
        
        
    }
   
   
   if (d.temp < 200)
   {
    stations[s_index].data = d;        
           
    stations[s_index].data_valid = true;

    if (d.temp > max_temp) max_temp = d.temp;
    if (d.temp < min_temp) min_temp = d.temp;
                      
       //console("temp : %d\n", d.temp); 
    }      
           
           

        
        
        
        

    
   
}











void load_data ( char *filename )
{

    log("Loading station data\n");


    FILE *f = fopen(filename, "rt");
               
        
    if (!f)
    {
        log("unable to load data file");
        return;
    }   


    bool done = false;


      while (!done)
    {
        char line[256];
        const unsigned int max = 255;
       
        if (fgets(line, max, f) != NULL)
        {  
            unsigned int l = strlen(line);
            
            if (l > 1)
            {
                line[l-2] = 0;   // Eat newline
                data_line(line);
            }
            
        }
        
        
        if (feof(f)) done = true;
    }        
    
    
    
   for (int i = 0; i < num_stations; i++)
    {
     // if (stations[i].data_valid)
//   log ("ID: (%s) temp: %d\n", stations[i].id, stations[i].data.temp);   
        
        
        
    }
    
    
    
    console("Min: %d  Max:  %d\n", min_temp, max_temp);
    
    
}










