]> git.street.me.uk Git - andy/viking.git/blob - src/gpx.c
Enforce memory free
[andy/viking.git] / src / gpx.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  *
6  * Some of the code adapted from GPSBabel 1.2.7
7  * http://gpsbabel.sf.net/
8  * Copyright (C) 2002, 2003, 2004, 2005 Robert Lipe, robertlipe@usa.net
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  */
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #define _XOPEN_SOURCE /* glibc2 needs this */
30
31 #include "gpx.h"
32 #include "viking.h"
33 #include <expat.h>
34 #ifdef HAVE_STRING_H
35 #include <string.h>
36 #endif
37 #include <glib.h>
38 #ifdef HAVE_MATH_H
39 #include <math.h>
40 #endif
41 #include <time.h>
42
43 typedef enum {
44         tt_unknown = 0,
45
46         tt_gpx,
47
48         tt_wpt,
49         tt_wpt_desc,
50         tt_wpt_name,
51         tt_wpt_ele,
52         tt_wpt_sym,
53         tt_wpt_link,            /* New in GPX 1.1 */
54
55         tt_trk,
56         tt_trk_desc,
57         tt_trk_name,
58
59         tt_trk_trkseg,
60         tt_trk_trkseg_trkpt,
61         tt_trk_trkseg_trkpt_ele,
62         tt_trk_trkseg_trkpt_time,
63         /* extended */
64         tt_trk_trkseg_trkpt_course,
65         tt_trk_trkseg_trkpt_speed,
66         tt_trk_trkseg_trkpt_fix,
67         tt_trk_trkseg_trkpt_sat,
68
69         tt_waypoint,
70         tt_waypoint_coord,
71         tt_waypoint_name,
72 } tag_type;
73
74 typedef struct tag_mapping {
75         tag_type tag_type;              /* enum from above for this tag */
76         const char *tag_name;           /* xpath-ish tag name */
77 } tag_mapping;
78
79 typedef struct {
80         GpxWritingOptions *options;
81         FILE *file;
82 } GpxWritingContext;
83
84 /*
85  * xpath(ish) mappings between full tag paths and internal identifers.
86  * These appear in the order they appear in the GPX specification.
87  * If it's not a tag we explictly handle, it doesn't go here.
88  */
89
90 tag_mapping tag_path_map[] = {
91
92         { tt_wpt, "/gpx/wpt" },
93
94         { tt_waypoint, "/loc/waypoint" },
95         { tt_waypoint_coord, "/loc/waypoint/coord" },
96         { tt_waypoint_name, "/loc/waypoint/name" },
97
98         { tt_wpt_ele, "/gpx/wpt/ele" },
99         { tt_wpt_name, "/gpx/wpt/name" },
100         { tt_wpt_desc, "/gpx/wpt/desc" },
101         { tt_wpt_sym, "/gpx/wpt/sym" },
102         { tt_wpt_sym, "/loc/waypoint/type" },
103         { tt_wpt_link, "/gpx/wpt/link" },                    /* GPX 1.1 */
104
105         { tt_trk, "/gpx/trk" },
106         { tt_trk, "/gpx/rte" },
107         { tt_trk_name, "/gpx/trk/name" },
108         { tt_trk_desc, "/gpx/trk/desc" },
109         { tt_trk_trkseg, "/gpx/trk/trkseg" },
110         { tt_trk_trkseg_trkpt, "/gpx/trk/trkseg/trkpt" },
111         { tt_trk_trkseg_trkpt, "/gpx/rte/rtept" },
112         { tt_trk_trkseg_trkpt_ele, "/gpx/trk/trkseg/trkpt/ele" },
113         { tt_trk_trkseg_trkpt_time, "/gpx/trk/trkseg/trkpt/time" },
114         /* extended */
115         { tt_trk_trkseg_trkpt_course, "/gpx/trk/trkseg/trkpt/course" },
116         { tt_trk_trkseg_trkpt_speed, "/gpx/trk/trkseg/trkpt/speed" },
117         { tt_trk_trkseg_trkpt_fix, "/gpx/trk/trkseg/trkpt/fix" },
118         { tt_trk_trkseg_trkpt_sat, "/gpx/trk/trkseg/trkpt/sat" },
119
120         {0}
121 };
122
123 static tag_type get_tag(const char *t)
124 {
125         tag_mapping *tm;
126         for (tm = tag_path_map; tm->tag_type != 0; tm++)
127                 if (0 == strcmp(tm->tag_name, t))
128                         return tm->tag_type;
129         return tt_unknown;
130 }
131
132 /******************************************/
133
134 tag_type current_tag = tt_unknown;
135 GString *xpath = NULL;
136 GString *c_cdata = NULL;
137
138 /* current ("c_") objects */
139 VikTrackpoint *c_tp = NULL;
140 VikWaypoint *c_wp = NULL;
141 VikTrack *c_tr = NULL;
142
143 gchar *c_wp_name = NULL;
144 gchar *c_tr_name = NULL;
145
146 /* temporary things so we don't have to create them lots of times */
147 const gchar *c_slat, *c_slon;
148 struct LatLon c_ll;
149
150 /* specialty flags / etc */
151 gboolean f_tr_newseg;
152 guint unnamed_waypoints = 0;
153 guint unnamed_tracks = 0;
154
155
156 static const char *get_attr ( const char **attr, const char *key )
157 {
158   while ( *attr ) {
159     if ( strcmp(*attr,key) == 0 )
160       return *(attr + 1);
161     attr += 2;
162   }
163   return NULL;
164 }
165
166 static gboolean set_c_ll ( const char **attr )
167 {
168   if ( (c_slat = get_attr ( attr, "lat" )) && (c_slon = get_attr ( attr, "lon" )) ) {
169     c_ll.lat = g_strtod(c_slat, NULL);
170     c_ll.lon = g_strtod(c_slon, NULL);
171     return TRUE;
172   }
173   return FALSE;
174 }
175
176 static void gpx_start(VikTrwLayer *vtl, const char *el, const char **attr)
177 {
178   static const gchar *tmp;
179
180   g_string_append_c ( xpath, '/' );
181   g_string_append ( xpath, el );
182   current_tag = get_tag ( xpath->str );
183
184   switch ( current_tag ) {
185
186      case tt_wpt:
187        if ( set_c_ll( attr ) ) {
188          c_wp = vik_waypoint_new ();
189          c_wp->altitude = VIK_DEFAULT_ALTITUDE;
190          if ( ! get_attr ( attr, "hidden" ) )
191            c_wp->visible = TRUE;
192
193          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
194        }
195        break;
196
197      case tt_trk:
198        c_tr = vik_track_new ();
199        if ( ! get_attr ( attr, "hidden" ) )
200          c_tr->visible = TRUE;
201        break;
202
203      case tt_trk_trkseg:
204        f_tr_newseg = TRUE;
205        break;
206
207      case tt_trk_trkseg_trkpt:
208        if ( set_c_ll( attr ) ) {
209          c_tp = vik_trackpoint_new ();
210          c_tp->altitude = VIK_DEFAULT_ALTITUDE;
211          vik_coord_load_from_latlon ( &(c_tp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
212          if ( f_tr_newseg ) {
213            c_tp->newsegment = TRUE;
214            f_tr_newseg = FALSE;
215          }
216          c_tr->trackpoints = g_list_append ( c_tr->trackpoints, c_tp );
217        }
218        break;
219
220      case tt_trk_trkseg_trkpt_ele:
221      case tt_trk_trkseg_trkpt_time:
222      case tt_wpt_desc:
223      case tt_wpt_name:
224      case tt_wpt_ele:
225      case tt_wpt_link:
226      case tt_trk_desc:
227      case tt_trk_name:
228        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer */
229        break;
230
231      case tt_waypoint:
232        c_wp = vik_waypoint_new ();
233        c_wp->altitude = VIK_DEFAULT_ALTITUDE;
234        c_wp->visible = TRUE;
235        break;
236
237      case tt_waypoint_coord:
238        if ( set_c_ll( attr ) )
239          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
240        break;
241
242      case tt_waypoint_name:
243        if ( ( tmp = get_attr(attr, "id") ) ) {
244          if ( c_wp_name )
245            g_free ( c_wp_name );
246          c_wp_name = g_strdup ( tmp );
247        }
248        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer for description */
249        break;
250         
251      default: break;
252   }
253 }
254
255 static void gpx_end(VikTrwLayer *vtl, const char *el)
256 {
257   static GTimeVal tp_time;
258
259   g_string_truncate ( xpath, xpath->len - strlen(el) - 1 );
260
261   switch ( current_tag ) {
262
263      case tt_waypoint:
264      case tt_wpt:
265        if ( ! c_wp_name )
266          c_wp_name = g_strdup_printf("VIKING_WP%d", unnamed_waypoints++);
267        vik_trw_layer_filein_add_waypoint ( vtl, c_wp_name, c_wp );
268        g_free ( c_wp_name );
269        c_wp = NULL;
270        c_wp_name = NULL;
271        break;
272
273      case tt_trk:
274        if ( ! c_tr_name )
275          c_tr_name = g_strdup_printf("VIKING_TR%d", unnamed_waypoints++);
276        vik_trw_layer_filein_add_track ( vtl, c_tr_name, c_tr );
277        g_free ( c_tr_name );
278        c_tr = NULL;
279        c_tr_name = NULL;
280        break;
281
282      case tt_wpt_name:
283        if ( c_wp_name )
284          g_free ( c_wp_name );
285        c_wp_name = g_strdup ( c_cdata->str );
286        g_string_erase ( c_cdata, 0, -1 );
287        break;
288
289      case tt_trk_name:
290        if ( c_tr_name )
291          g_free ( c_tr_name );
292        c_tr_name = g_strdup ( c_cdata->str );
293        g_string_erase ( c_cdata, 0, -1 );
294        break;
295
296      case tt_wpt_ele:
297        c_wp->altitude = g_strtod ( c_cdata->str, NULL );
298        g_string_erase ( c_cdata, 0, -1 );
299        break;
300
301      case tt_trk_trkseg_trkpt_ele:
302        c_tp->altitude = g_strtod ( c_cdata->str, NULL );
303        g_string_erase ( c_cdata, 0, -1 );
304        break;
305
306      case tt_waypoint_name: /* .loc name is really description. */
307      case tt_wpt_desc:
308        vik_waypoint_set_comment ( c_wp, c_cdata->str );
309        g_string_erase ( c_cdata, 0, -1 );
310        break;
311
312      case tt_wpt_link:
313        vik_waypoint_set_image ( c_wp, c_cdata->str );
314        g_string_erase ( c_cdata, 0, -1 );
315        break;
316
317      case tt_wpt_sym: {
318        gchar *tmp_lower = g_utf8_strdown(c_cdata->str, -1); /* for things like <type>Geocache</type> */
319        vik_waypoint_set_symbol ( c_wp, tmp_lower );
320        g_free ( tmp_lower );
321        g_string_erase ( c_cdata, 0, -1 );
322        break;
323        }
324
325      case tt_trk_desc:
326        vik_track_set_comment ( c_tr, c_cdata->str );
327        g_string_erase ( c_cdata, 0, -1 );
328        break;
329
330      case tt_trk_trkseg_trkpt_time:
331        if ( g_time_val_from_iso8601(c_cdata->str, &tp_time) ) {
332          c_tp->timestamp = tp_time.tv_sec;
333          c_tp->has_timestamp = TRUE;
334        }
335        g_string_erase ( c_cdata, 0, -1 );
336        break;
337
338      case tt_trk_trkseg_trkpt_course:
339        c_tp->extended = TRUE;
340        c_tp->course = g_strtod ( c_cdata->str, NULL );
341        g_string_erase ( c_cdata, 0, -1 );
342        break;
343
344      case tt_trk_trkseg_trkpt_speed:
345        c_tp->extended = TRUE;
346        c_tp->speed = g_strtod ( c_cdata->str, NULL );
347        g_string_erase ( c_cdata, 0, -1 );
348        break;
349
350      case tt_trk_trkseg_trkpt_fix:
351        c_tp->extended = TRUE;
352        if (!strcmp("2d", c_cdata->str))
353          c_tp->fix_mode = VIK_GPS_MODE_2D;
354        else if (!strcmp("3d", c_cdata->str))
355          c_tp->fix_mode = VIK_GPS_MODE_3D;
356        else  /* TODO: more fix modes here */
357          c_tp->fix_mode = VIK_GPS_MODE_NOT_SEEN;
358        g_string_erase ( c_cdata, 0, -1 );
359        break;
360
361      case tt_trk_trkseg_trkpt_sat:
362        c_tp->extended = TRUE;
363        c_tp->nsats = atoi ( c_cdata->str );
364        g_string_erase ( c_cdata, 0, -1 );
365        break;
366
367      default: break;
368   }
369
370   current_tag = get_tag ( xpath->str );
371 }
372
373 static void gpx_cdata(void *dta, const XML_Char *s, int len)
374 {
375   switch ( current_tag ) {
376     case tt_wpt_name:
377     case tt_trk_name:
378     case tt_wpt_ele:
379     case tt_trk_trkseg_trkpt_ele:
380     case tt_wpt_desc:
381     case tt_wpt_sym:
382     case tt_wpt_link:
383     case tt_trk_desc:
384     case tt_trk_trkseg_trkpt_time:
385     case tt_trk_trkseg_trkpt_course:
386     case tt_trk_trkseg_trkpt_speed:
387     case tt_trk_trkseg_trkpt_fix:
388     case tt_trk_trkseg_trkpt_sat:
389     case tt_waypoint_name: /* .loc name is really description. */
390       g_string_append_len ( c_cdata, s, len );
391       break;
392
393     default: break;  /* ignore cdata from other things */
394   }
395 }
396
397 // make like a "stack" of tag names
398 // like gpspoint's separated like /gpx/wpt/whatever
399
400 void a_gpx_read_file( VikTrwLayer *vtl, FILE *f ) {
401   XML_Parser parser = XML_ParserCreate(NULL);
402   int done=0, len;
403
404   XML_SetElementHandler(parser, (XML_StartElementHandler) gpx_start, (XML_EndElementHandler) gpx_end);
405   XML_SetUserData(parser, vtl); /* in the future we could remove all global variables */
406   XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler) gpx_cdata);
407
408   gchar buf[4096];
409
410   g_assert ( f != NULL && vtl != NULL );
411
412   xpath = g_string_new ( "" );
413   c_cdata = g_string_new ( "" );
414
415   unnamed_waypoints = 0;
416   unnamed_tracks = 0;
417
418   while (!done) {
419     len = fread(buf, 1, sizeof(buf)-7, f);
420     done = feof(f) || !len;
421     XML_Parse(parser, buf, len, done);
422   }
423  
424   XML_ParserFree (parser);
425   g_string_free ( xpath, TRUE );
426   g_string_free ( c_cdata, TRUE );
427 }
428
429 /**** entitize from GPSBabel ****/
430 typedef struct {
431         const char * text;
432         const char * entity;
433         int  not_html;
434 } entity_types;
435
436 static
437 entity_types stdentities[] =  {
438         { "&",  "&amp;", 0 },
439         { "'",  "&apos;", 1 },
440         { "<",  "&lt;", 0 },
441         { ">",  "&gt;", 0 },
442         { "\"", "&quot;", 0 },
443         { NULL, NULL, 0 }
444 };
445
446 void utf8_to_int( const char *cp, int *bytes, int *value )
447 {
448         if ( (*cp & 0xe0) == 0xc0 ) {
449                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
450                 *bytes = 2;
451                 *value = ((*cp & 0x1f) << 6) |
452                         (*(cp+1) & 0x3f);
453         }
454         else if ( (*cp & 0xf0) == 0xe0 ) {
455                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
456                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
457                 *bytes = 3;
458                 *value = ((*cp & 0x0f) << 12) |
459                         ((*(cp+1) & 0x3f) << 6) |
460                         (*(cp+2) & 0x3f);
461         }
462         else if ( (*cp & 0xf8) == 0xf0 ) {
463                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
464                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
465                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
466                 *bytes = 4;
467                 *value = ((*cp & 0x07) << 18) |
468                         ((*(cp+1) & 0x3f) << 12) |
469                         ((*(cp+2) & 0x3f) << 6) |
470                         (*(cp+3) & 0x3f);
471         }
472         else if ( (*cp & 0xfc) == 0xf8 ) {
473                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
474                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
475                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
476                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
477                 *bytes = 5;
478                 *value = ((*cp & 0x03) << 24) |
479                         ((*(cp+1) & 0x3f) << 18) |
480                         ((*(cp+2) & 0x3f) << 12) |
481                         ((*(cp+3) & 0x3f) << 6) |
482                         (*(cp+4) & 0x3f);
483         }
484         else if ( (*cp & 0xfe) == 0xfc ) {
485                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
486                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
487                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
488                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
489                 if ( (*(cp+5) & 0xc0) != 0x80 ) goto dodefault;
490                 *bytes = 6;
491                 *value = ((*cp & 0x01) << 30) |
492                         ((*(cp+1) & 0x3f) << 24) |
493                         ((*(cp+2) & 0x3f) << 18) |
494                         ((*(cp+3) & 0x3f) << 12) |
495                         ((*(cp+4) & 0x3f) << 6) |
496                         (*(cp+5) & 0x3f);
497         }
498         else {
499 dodefault:
500                 *bytes = 1;
501                 *value = (unsigned char)*cp;
502         }
503 }
504
505 static
506 char *
507 entitize(const char * str)
508 {
509         int elen, ecount, nsecount;
510         entity_types *ep;
511         const char * cp;
512         char * p, * tmp, * xstr;
513
514         char tmpsub[20];
515         int bytes = 0;
516         int value = 0;
517         ep = stdentities;
518         elen = ecount = nsecount = 0;
519
520         /* figure # of entity replacements and additional size. */
521         while (ep->text) {
522                 cp = str;
523                 while ((cp = strstr(cp, ep->text)) != NULL) {
524                         elen += strlen(ep->entity) - strlen(ep->text);
525                         ecount++;
526                         cp += strlen(ep->text);
527                 }
528                 ep++;
529         }
530
531         /* figure the same for other than standard entities (i.e. anything
532          * that isn't in the range U+0000 to U+007F */
533         for ( cp = str; *cp; cp++ ) {
534                 if ( *cp & 0x80 ) {
535
536                         utf8_to_int( cp, &bytes, &value );
537                         cp += bytes-1;
538                         elen += sprintf( tmpsub, "&#x%x;", value ) - bytes;
539                         nsecount++;
540                 }
541         }
542
543         /* enough space for the whole string plus entity replacements, if any */
544         tmp = g_malloc((strlen(str) + elen + 1));
545         strcpy(tmp, str);
546
547         /* no entity replacements */
548         if (ecount == 0 && nsecount == 0)
549                 return (tmp);
550
551         if ( ecount != 0 ) {
552                 for (ep = stdentities; ep->text; ep++) {
553                         p = tmp;
554                         while ((p = strstr(p, ep->text)) != NULL) {
555                                 elen = strlen(ep->entity);
556
557                                 xstr = g_strdup(p + strlen(ep->text));
558
559                                 strcpy(p, ep->entity);
560                                 strcpy(p + elen, xstr);
561
562                                 g_free(xstr);
563
564                                 p += elen;
565                         }
566                 }
567         }
568
569         if ( nsecount != 0 ) {
570                 p = tmp;
571                 while (*p) {
572                         if ( *p & 0x80 ) {
573                                 utf8_to_int( p, &bytes, &value );
574                                 if ( p[bytes] ) {
575                                         xstr = g_strdup( p + bytes );
576                                 }
577                                 else {
578                                         xstr = NULL;
579                                 }
580                                 sprintf( p, "&#x%x;", value );
581                                 p = p+strlen(p);
582                                 if ( xstr ) {
583                                         strcpy( p, xstr );
584                                         g_free(xstr);
585                                 }
586                         }
587                         else {
588                                 p++;
589                         }
590                 }
591         }
592         return (tmp);
593 }
594 /**** end GPSBabel code ****/
595
596 /* export GPX */
597
598 static void gpx_write_waypoint ( const gchar *name, VikWaypoint *wp, GpxWritingContext *context ) 
599 {
600   FILE *f = context->file;
601   static struct LatLon ll;
602   gchar *s_lat,*s_lon;
603   gchar *tmp;
604   vik_coord_to_latlon ( &(wp->coord), &ll );
605   s_lat = a_coords_dtostr( ll.lat );
606   s_lon = a_coords_dtostr( ll.lon );
607   fprintf ( f, "<wpt lat=\"%s\" lon=\"%s\"%s>\n",
608                s_lat, s_lon, wp->visible ? "" : " hidden=\"hidden\"" );
609   g_free ( s_lat );
610   g_free ( s_lon );
611
612   tmp = entitize ( name );
613   fprintf ( f, "  <name>%s</name>\n", tmp );
614   g_free ( tmp);
615
616   if ( wp->altitude != VIK_DEFAULT_ALTITUDE )
617   {
618     tmp = a_coords_dtostr ( wp->altitude );
619     fprintf ( f, "  <ele>%s</ele>\n", tmp );
620     g_free ( tmp );
621   }
622   if ( wp->comment )
623   {
624     tmp = entitize(wp->comment);
625     fprintf ( f, "  <desc>%s</desc>\n", tmp );
626     g_free ( tmp );
627   }
628   if ( wp->image )
629   {
630     tmp = entitize(wp->image);
631     fprintf ( f, "  <link>%s</link>\n", tmp );
632     g_free ( tmp );
633   }
634   if ( wp->symbol ) 
635   {
636     tmp = entitize(wp->symbol);
637     fprintf ( f, "  <sym>%s</sym>\n", tmp);
638     g_free ( tmp );
639   }
640
641   fprintf ( f, "</wpt>\n" );
642 }
643
644 static void gpx_write_trackpoint ( VikTrackpoint *tp, GpxWritingContext *context )
645 {
646   FILE *f = context->file;
647   static struct LatLon ll;
648   gchar *s_lat,*s_lon, *s_alt;
649   gchar *time_iso8601;
650   vik_coord_to_latlon ( &(tp->coord), &ll );
651
652   if ( tp->newsegment )
653     fprintf ( f, "  </trkseg>\n  <trkseg>\n" );
654
655   s_lat = a_coords_dtostr( ll.lat );
656   s_lon = a_coords_dtostr( ll.lon );
657   fprintf ( f, "  <trkpt lat=\"%s\" lon=\"%s\">\n", s_lat, s_lon );
658   g_free ( s_lat ); s_lat = NULL;
659   g_free ( s_lon ); s_lon = NULL;
660
661   s_alt = NULL;
662   if ( tp->altitude != VIK_DEFAULT_ALTITUDE )
663   {
664     s_alt = a_coords_dtostr ( tp->altitude );
665   }
666   else if ( context->options != NULL && context->options->force_ele )
667   {
668     s_alt = a_coords_dtostr ( 0 );
669   }
670   if (s_alt != NULL)
671     fprintf ( f, "    <ele>%s</ele>\n", s_alt );
672   g_free ( s_alt ); s_alt = NULL;
673   
674   time_iso8601 = NULL;
675   if ( tp->has_timestamp ) {
676     GTimeVal timestamp;
677     timestamp.tv_sec = tp->timestamp;
678     timestamp.tv_usec = 0;
679   
680     time_iso8601 = g_time_val_to_iso8601 ( &timestamp );
681   }
682   else if ( context->options != NULL && context->options->force_time )
683   {
684     GTimeVal current;
685     g_get_current_time ( &current );
686   
687     time_iso8601 = g_time_val_to_iso8601 ( &current );
688   }
689   if ( time_iso8601 != NULL )
690     fprintf ( f, "    <time>%s</time>\n", time_iso8601 );
691   g_free(time_iso8601);
692   time_iso8601 = NULL;
693   
694   if (tp->extended && (tp->fix_mode >= VIK_GPS_MODE_2D)) {
695     if (!isnan(tp->course)) {
696       gchar *s_course = a_coords_dtostr(tp->course);
697       fprintf ( f, "    <course>%s</course>\n", s_course );
698       g_free(s_course);
699     }
700     if (!isnan(tp->speed)) {
701       gchar *s_speed = a_coords_dtostr(tp->speed);
702       fprintf ( f, "    <speed>%s</speed>\n", s_speed );
703       g_free(s_speed);
704     }
705     if (tp->fix_mode == VIK_GPS_MODE_2D)
706       fprintf ( f, "    <fix>2d</fix>\n");
707     if (tp->fix_mode == VIK_GPS_MODE_3D)
708       fprintf ( f, "    <fix>3d</fix>\n");
709     if (tp->nsats > 0)
710       fprintf ( f, "    <sat>%d</sat>\n", tp->nsats );
711   }
712
713   fprintf ( f, "  </trkpt>\n" );
714 }
715
716
717 static void gpx_write_track ( const gchar *name, VikTrack *t, GpxWritingContext *context )
718 {
719   FILE *f = context->file;
720   gchar *tmp;
721   gboolean first_tp_is_newsegment = FALSE; /* must temporarily make it not so, but we want to restore state. not that it matters. */
722
723   tmp = entitize ( name );
724   fprintf ( f, "<trk%s>\n  <name>%s</name>\n", t->visible ? "" : " hidden=\"hidden\"", tmp );
725   g_free ( tmp );
726
727   if ( t->comment )
728   {
729     tmp = entitize ( t->comment );
730     fprintf ( f, "  <desc>%s</desc>\n", tmp );
731     g_free ( tmp );
732   }
733
734   fprintf ( f, "  <trkseg>\n" );
735
736   if ( t->trackpoints && t->trackpoints->data ) {
737     first_tp_is_newsegment = VIK_TRACKPOINT(t->trackpoints->data)->newsegment;
738     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = FALSE; /* so we won't write </trkseg><trkseg> already */
739     g_list_foreach ( t->trackpoints, (GFunc) gpx_write_trackpoint, context );
740     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = first_tp_is_newsegment; /* restore state */
741   }
742
743   fprintf ( f, "</trkseg>\n</trk>\n" );
744 }
745
746 static void gpx_write_header( FILE *f )
747 {
748   fprintf(f, "<?xml version=\"1.0\"?>\n"
749           "<gpx version=\"1.0\" creator=\"Viking -- http://viking.sf.net/\"\n"
750           "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
751           "xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
752           "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n");
753 }
754
755 static void gpx_write_footer( FILE *f )
756 {
757   fprintf(f, "</gpx>\n");
758 }
759
760
761
762 typedef struct {
763   VikWaypoint *wp;
764   const gchar *name;
765 } gpx_waypoint_and_name;
766
767 typedef struct {
768   gpx_waypoint_and_name *wps;
769   guint i;
770   guint n_wps;
771 } gpx_gather_waypoints_passalong_t;
772
773 /* Type to hold name of track and timestamp of first trackpoint */
774 typedef struct {
775   time_t first_timestamp;
776   const gchar *name;
777 } gpx_track_and_timestamp;
778
779 typedef struct {
780   gpx_track_and_timestamp *trks;
781   guint i;
782   guint n_trks;
783 } gpx_gather_tracks_passalong_t;
784
785 static void gpx_collect_waypoint ( const gchar *name, VikWaypoint *wp, gpx_gather_waypoints_passalong_t *passalong )
786 {
787   if ( passalong->i < passalong->n_wps ) {
788     passalong->wps[passalong->i].name = name;
789     passalong->wps[passalong->i].wp = wp;
790     passalong->i++;
791   }
792 }
793
794 /* Function to collect a track and the first timestamp in the list */
795 static void gpx_collect_track (const gchar *name, VikTrack *track, gpx_gather_tracks_passalong_t *passalong)
796 {
797   if (passalong->i < passalong->n_trks)
798   {
799     VikTrackpoint *first_point = (VikTrackpoint *)track->trackpoints->data;
800     passalong->trks[passalong->i].name = name;
801     passalong->trks[passalong->i].first_timestamp = first_point->timestamp;
802     passalong->i++;
803   }
804 }
805
806 static int gpx_waypoint_and_name_compar(const void *x, const void *y)
807 {
808   gpx_waypoint_and_name *a = (gpx_waypoint_and_name *)x;
809   gpx_waypoint_and_name *b = (gpx_waypoint_and_name *)y;
810   return strcmp(a->name,b->name);
811 }
812
813 /* Function to compare two tracks by their first timestamp */
814 static int gpx_track_and_timestamp_compar(const void *x, const void *y)
815 {
816   gpx_track_and_timestamp *a = (gpx_track_and_timestamp *)x;
817   gpx_track_and_timestamp *b = (gpx_track_and_timestamp *)y;
818   if (a->first_timestamp < b->first_timestamp)
819   {
820     return -1;
821   }
822   if (a->first_timestamp > b->first_timestamp)
823   {
824     return 1;
825   }
826   return 0;
827 }
828
829 void a_gpx_write_file( VikTrwLayer *vtl, FILE *f )
830 {
831         a_gpx_write_file_options(NULL, vtl, f);
832 }
833
834 void a_gpx_write_file_options ( GpxWritingOptions *options, VikTrwLayer *vtl, FILE *f )
835 {
836   GpxWritingContext context = { options, f };
837   int i;
838
839   gpx_write_header ( f );
840
841
842   gpx_gather_waypoints_passalong_t passalong;
843   passalong.n_wps = g_hash_table_size ( vik_trw_layer_get_waypoints ( vtl ) );
844   passalong.i = 0;
845   passalong.wps = g_new(gpx_waypoint_and_name,passalong.n_wps);
846   g_hash_table_foreach ( vik_trw_layer_get_waypoints ( vtl ), (GHFunc) gpx_collect_waypoint, &passalong );
847   /* gather waypoints in a list, then sort */
848   qsort(passalong.wps, passalong.n_wps, sizeof(gpx_waypoint_and_name), gpx_waypoint_and_name_compar);
849   for ( i = 0; i < passalong.n_wps; i++ )
850     gpx_write_waypoint ( passalong.wps[i].name, passalong.wps[i].wp, &context);
851   g_free ( passalong.wps );
852
853   gpx_gather_tracks_passalong_t passalong_tracks;
854   passalong_tracks.n_trks = g_hash_table_size ( vik_trw_layer_get_tracks (vtl) );
855   passalong_tracks.i = 0;
856   passalong_tracks.trks = g_new(gpx_track_and_timestamp,passalong_tracks.n_trks);
857   g_hash_table_foreach (vik_trw_layer_get_tracks(vtl), (GHFunc) gpx_collect_track, &passalong_tracks);
858   /* Sort by timestamp */
859   qsort(passalong_tracks.trks, passalong_tracks.n_trks, sizeof(gpx_track_and_timestamp), gpx_track_and_timestamp_compar);
860   for (i=0;i<passalong_tracks.n_trks; i++)
861   {
862     gpx_write_track(passalong_tracks.trks[i].name, (VikTrack *)g_hash_table_lookup(vik_trw_layer_get_tracks(vtl), passalong_tracks.trks[i].name), &context);
863   }
864   g_free ( passalong_tracks.trks );
865   gpx_write_footer ( f );
866 }
867
868 void a_gpx_write_track_file ( const gchar *name, VikTrack *t, FILE *f )
869 {
870   a_gpx_write_track_file_options ( NULL, name, t, f );
871 }
872
873 void a_gpx_write_track_file_options ( GpxWritingOptions *options, const gchar *name, VikTrack *t, FILE *f )
874 {
875   GpxWritingContext context = {options, f};
876   gpx_write_header ( f );
877   gpx_write_track ( name, t, &context );
878   gpx_write_footer ( f );
879 }