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