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