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