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