#include <stdio.h>
#include <stdlib.h>
#include <geolib/cproj.h>
#include "mapview.h"
#include "mapgen.h"

static POINT *pts;
static int npts = 0;
static int penup = TRUE;

static EXTMAP *map;
static MAPREC *recs, *prevrec;


static void addrec(MGSEGDICT *sd)
{
   MAPREC *rec = (MAPREC *)malloc(sizeof(MAPREC));
   rec->pts = (POINT *)malloc(npts * sizeof(POINT));
   rec->npts = npts;
   rec->minlat = sd->minlat;
   rec->maxlat = sd->maxlat;
   rec->minlon = sd->minlon;
   rec->maxlon = sd->maxlon;
   rec->next = NULL;

   memcpy(rec->pts, pts, npts * sizeof(POINT));

   if (! recs)
       recs = rec;
   if (prevrec)
       prevrec->next = rec;
   prevrec = rec;
}

static void pendn(double lon, double lat, MGSEGDICT *sd)
{
   double xm, ym;

   if (penup) {
       if (npts)
           addrec(sd);
       sd->minlat = 1000000.; sd->maxlat = -1000000.;
       sd->minlon = 1000000.; sd->maxlon = -1000000.;
       npts = 0;
       penup = FALSE;
       return;
   }

   if (lat < sd->minlat)
       sd->minlat = lat;
   if (lat > sd->maxlat)
       sd->maxlat = lat;
   if (lon < sd->minlon)
       sd->minlon = lon;
   if (lon > sd->maxlon)
       sd->maxlon = lon;

   if (fortrans[PROJECT](lon * D2R, lat * D2R, &xm, &ym))
       exit(1);
   pts[npts].xm = (float)xm; pts[npts].ym = (float)ym;

   if (++npts == MAXPOINTS) {
       addrec(sd);
       sd->minlat = 1000000.; sd->maxlat = -1000000.;
       sd->minlon = 1000000.; sd->maxlon = -1000000.;
       npts = 0;
   }
}

EXTMAP *loadmapgen(char *name, unsigned long color, int width)
{
   FILE *f;
   char s[80];
   MGSEGDICT sd;
   double lastlon = 0.;
   double lon, lat;

   if (! (f = fopen(name, "r"))) {
       perror("fopen");
       exit(1);
   }

   pts = (POINT *)malloc(MAXPOINTS * sizeof(POINT));
   recs = prevrec = NULL;

   while (fgets(s, 80, f)) {
       if (*s == '*')
           continue;
       if (*s == '#') {
           penup = TRUE;
           pendn(lon, lat, &sd);
           continue;
       }
       sscanf(s, "%lf %lf", &lon, &lat);
       if (fabs(lastlon - lon) > 180.)
           penup = TRUE;
       pendn(lon, lat, &sd);
       lastlon = lon;
   }
   if (npts)
       addrec(&sd);

   free(pts);

   map = (EXTMAP *)malloc(sizeof(MAP));
   map->color = color;
   map->width = width;
   map->recs = recs;
   map->next = NULL;
   return map;
}