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