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