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