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