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