]> git.street.me.uk Git - andy/viking.git/blob - src/viktrack.c
Support GPX src field on Waypoints, Tracks and Routes.
[andy/viking.git] / src / viktrack.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (c) 2012, Rob Norris <rw_norris@hotmail.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <glib.h>
27 #include <time.h>
28 #include <stdlib.h>
29 #ifdef HAVE_STRING_H
30 #include <string.h>
31 #endif
32 #ifdef HAVE_MATH_H
33 #include <math.h>
34 #endif
35
36 #include "coords.h"
37 #include "vikcoord.h"
38 #include "viktrack.h"
39 #include "globals.h"
40 #include "dems.h"
41 #include "settings.h"
42
43 VikTrack *vik_track_new()
44 {
45   VikTrack *tr = g_malloc0 ( sizeof ( VikTrack ) );
46   tr->ref_count = 1;
47   return tr;
48 }
49
50 #define VIK_SETTINGS_TRACK_NAME_MODE "track_draw_name_mode"
51 #define VIK_SETTINGS_TRACK_NUM_DIST_LABELS "track_number_dist_labels"
52
53 /**
54  * vik_track_set_defaults:
55  *
56  * Set some default values for a track.
57  * ATM This uses the 'settings' method to get values,
58  *  so there is no GUI way to control these yet...
59  */
60 void vik_track_set_defaults(VikTrack *tr)
61 {
62   gint tmp;
63   if ( a_settings_get_integer ( VIK_SETTINGS_TRACK_NAME_MODE, &tmp ) )
64     tr->draw_name_mode = tmp;
65
66   if ( a_settings_get_integer ( VIK_SETTINGS_TRACK_NUM_DIST_LABELS, &tmp ) )
67     tr->max_number_dist_labels = tmp;
68 }
69
70 void vik_track_set_comment_no_copy(VikTrack *tr, gchar *comment)
71 {
72   if ( tr->comment )
73     g_free ( tr->comment );
74   tr->comment = comment;
75 }
76
77
78 void vik_track_set_name(VikTrack *tr, const gchar *name)
79 {
80   if ( tr->name )
81     g_free ( tr->name );
82
83   tr->name = g_strdup(name);
84 }
85
86 void vik_track_set_comment(VikTrack *tr, const gchar *comment)
87 {
88   if ( tr->comment )
89     g_free ( tr->comment );
90
91   if ( comment && comment[0] != '\0' )
92     tr->comment = g_strdup(comment);
93   else
94     tr->comment = NULL;
95 }
96
97 void vik_track_set_description(VikTrack *tr, const gchar *description)
98 {
99   if ( tr->description )
100     g_free ( tr->description );
101
102   if ( description && description[0] != '\0' )
103     tr->description = g_strdup(description);
104   else
105     tr->description = NULL;
106 }
107
108 void vik_track_set_source(VikTrack *tr, const gchar *source)
109 {
110   if ( tr->source )
111     g_free ( tr->source );
112
113   if ( source && source[0] != '\0' )
114     tr->source = g_strdup(source);
115   else
116     tr->source = NULL;
117 }
118
119 void vik_track_ref(VikTrack *tr)
120 {
121   tr->ref_count++;
122 }
123
124 void vik_track_set_property_dialog(VikTrack *tr, GtkWidget *dialog)
125 {
126   /* Warning: does not check for existing dialog */
127   tr->property_dialog = dialog;
128 }
129
130 void vik_track_clear_property_dialog(VikTrack *tr)
131 {
132   tr->property_dialog = NULL;
133 }
134
135 void vik_track_free(VikTrack *tr)
136 {
137   if ( tr->ref_count-- > 1 )
138     return;
139
140   if ( tr->name )
141     g_free ( tr->name );
142   if ( tr->comment )
143     g_free ( tr->comment );
144   if ( tr->description )
145     g_free ( tr->description );
146   if ( tr->source )
147     g_free ( tr->source );
148   g_list_foreach ( tr->trackpoints, (GFunc) vik_trackpoint_free, NULL );
149   g_list_free( tr->trackpoints );
150   if (tr->property_dialog)
151     if ( GTK_IS_WIDGET(tr->property_dialog) )
152       gtk_widget_destroy ( GTK_WIDGET(tr->property_dialog) );
153   g_free ( tr );
154 }
155
156 /**
157  * vik_track_copy:
158  * @tr: The Track to copy
159  * @copy_points: Whether to copy the track points or not
160  *
161  * Normally for copying the track it's best to copy all the trackpoints
162  * However for some operations such as splitting tracks the trackpoints will be managed separately, so no need to copy them.
163  *
164  * Returns: the copied VikTrack
165  */
166 VikTrack *vik_track_copy ( const VikTrack *tr, gboolean copy_points )
167 {
168   VikTrack *new_tr = vik_track_new();
169   new_tr->name = g_strdup(tr->name);
170   new_tr->visible = tr->visible;
171   new_tr->is_route = tr->is_route;
172   new_tr->draw_name_mode = tr->draw_name_mode;
173   new_tr->max_number_dist_labels = tr->max_number_dist_labels;
174   new_tr->has_color = tr->has_color;
175   new_tr->color = tr->color;
176   new_tr->bbox = tr->bbox;
177   new_tr->trackpoints = NULL;
178   if ( copy_points )
179   {
180     GList *tp_iter = tr->trackpoints;
181     while ( tp_iter )
182     {
183       VikTrackpoint *new_tp = vik_trackpoint_copy ( (VikTrackpoint*)(tp_iter->data) );
184       new_tr->trackpoints = g_list_prepend ( new_tr->trackpoints, new_tp );
185       tp_iter = tp_iter->next;
186     }
187     if ( new_tr->trackpoints )
188       new_tr->trackpoints = g_list_reverse ( new_tr->trackpoints );
189   }
190   vik_track_set_name(new_tr,tr->name);
191   vik_track_set_comment(new_tr,tr->comment);
192   vik_track_set_description(new_tr,tr->description);
193   vik_track_set_source(new_tr,tr->source);
194   return new_tr;
195 }
196
197 VikTrackpoint *vik_trackpoint_new()
198 {
199   VikTrackpoint *tp = g_malloc0(sizeof(VikTrackpoint));
200   tp->speed = NAN;
201   tp->course = NAN;
202   tp->altitude = VIK_DEFAULT_ALTITUDE;
203   tp->hdop = VIK_DEFAULT_DOP;
204   tp->vdop = VIK_DEFAULT_DOP;
205   tp->pdop = VIK_DEFAULT_DOP;
206   return tp;
207 }
208
209 void vik_trackpoint_free(VikTrackpoint *tp)
210 {
211   g_free(tp->name);
212   g_free(tp);
213 }
214
215 void vik_trackpoint_set_name(VikTrackpoint *tp, const gchar *name)
216 {
217   if ( tp->name )
218     g_free ( tp->name );
219
220   // If the name is blank then completely remove it
221   if ( name && name[0] == '\0' )
222     tp->name = NULL;
223   else if ( name )
224     tp->name = g_strdup(name);
225   else
226     tp->name = NULL;
227 }
228
229 VikTrackpoint *vik_trackpoint_copy(VikTrackpoint *tp)
230 {
231   VikTrackpoint *new_tp = vik_trackpoint_new();
232   memcpy ( new_tp, tp, sizeof(VikTrackpoint) );
233   if ( tp->name )
234     new_tp->name = g_strdup (tp->name);
235   return new_tp;
236 }
237
238 /**
239  * track_recalculate_bounds_last_tp:
240  * @trk:   The track to consider the recalculation on
241  *
242  * A faster bounds check, since it only considers the last track point
243  */
244 static void track_recalculate_bounds_last_tp ( VikTrack *trk )
245 {
246   GList *tpl = g_list_last ( trk->trackpoints );
247
248   if ( tpl ) {
249     struct LatLon ll;
250     // See if this trackpoint increases the track bounds and update if so
251     vik_coord_to_latlon ( &(VIK_TRACKPOINT(tpl->data)->coord), &ll );
252     if ( ll.lat > trk->bbox.north )
253       trk->bbox.north = ll.lat;
254     if ( ll.lon < trk->bbox.west )
255       trk->bbox.west = ll.lon;
256     if ( ll.lat < trk->bbox.south )
257       trk->bbox.south = ll.lat;
258     if ( ll.lon > trk->bbox.east )
259       trk->bbox.east = ll.lon;
260   }
261 }
262
263 /**
264  * vik_track_add_trackpoint:
265  * @tr:          The track to which the trackpoint will be added
266  * @tp:          The trackpoint to add
267  * @recalculate: Whether to perform any associated properties recalculations
268  *               Generally one should avoid recalculation via this method if adding lots of points
269  *               (But ensure calculate_bounds() is called after adding all points!!)
270  *
271  * The trackpoint is added to the end of the existing trackpoint list
272  */
273 void vik_track_add_trackpoint ( VikTrack *tr, VikTrackpoint *tp, gboolean recalculate )
274 {
275   // When it's the first trackpoint need to ensure the bounding box is initialized correctly
276   gboolean adding_first_point = tr->trackpoints ? FALSE : TRUE;
277   tr->trackpoints = g_list_append ( tr->trackpoints, tp );
278   if ( adding_first_point )
279     vik_track_calculate_bounds ( tr );
280   else if ( recalculate )
281     track_recalculate_bounds_last_tp ( tr );
282 }
283
284 /**
285  * vik_track_get_length_to_trackpoint:
286  *
287  */
288 gdouble vik_track_get_length_to_trackpoint (const VikTrack *tr, const VikTrackpoint *tp)
289 {
290   gdouble len = 0.0;
291   if ( tr->trackpoints )
292   {
293     // Is it the very first track point?
294     if ( VIK_TRACKPOINT(tr->trackpoints->data) == tp )
295       return len;
296
297     GList *iter = tr->trackpoints->next;
298     while (iter)
299     {
300       VikTrackpoint *tp1 = VIK_TRACKPOINT(iter->data);
301       if ( ! tp1->newsegment )
302         len += vik_coord_diff ( &(tp1->coord),
303                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
304
305       // Exit when we reach the desired point
306       if ( tp1 == tp )
307         break;
308
309       iter = iter->next;
310     }
311   }
312   return len;
313 }
314
315 gdouble vik_track_get_length(const VikTrack *tr)
316 {
317   gdouble len = 0.0;
318   if ( tr->trackpoints )
319   {
320     GList *iter = tr->trackpoints->next;
321     while (iter)
322     {
323       if ( ! VIK_TRACKPOINT(iter->data)->newsegment )
324         len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
325                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
326       iter = iter->next;
327     }
328   }
329   return len;
330 }
331
332 gdouble vik_track_get_length_including_gaps(const VikTrack *tr)
333 {
334   gdouble len = 0.0;
335   if ( tr->trackpoints )
336   {
337     GList *iter = tr->trackpoints->next;
338     while (iter)
339     {
340       len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
341                               &(VIK_TRACKPOINT(iter->prev->data)->coord) );
342       iter = iter->next;
343     }
344   }
345   return len;
346 }
347
348 gulong vik_track_get_tp_count(const VikTrack *tr)
349 {
350   return g_list_length(tr->trackpoints);
351 }
352
353 gulong vik_track_get_dup_point_count ( const VikTrack *tr )
354 {
355   gulong num = 0;
356   GList *iter = tr->trackpoints;
357   while ( iter )
358   {
359     if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
360                        &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
361       num++;
362     iter = iter->next;
363   }
364   return num;
365 }
366
367 /*
368  * Deletes adjacent points that have the same position
369  * Returns the number of points that were deleted
370  */
371 gulong vik_track_remove_dup_points ( VikTrack *tr )
372 {
373   gulong num = 0;
374   GList *iter = tr->trackpoints;
375   while ( iter )
376   {
377     if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
378                        &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
379     {
380       num++;
381       // Maintain track segments
382       if ( VIK_TRACKPOINT(iter->next->data)->newsegment && (iter->next)->next )
383         VIK_TRACKPOINT(((iter->next)->next)->data)->newsegment = TRUE;
384
385       vik_trackpoint_free ( iter->next->data );
386       tr->trackpoints = g_list_delete_link ( tr->trackpoints, iter->next );
387     }
388     else
389       iter = iter->next;
390   }
391
392   // NB isn't really be necessary as removing duplicate points shouldn't alter the bounds!
393   vik_track_calculate_bounds ( tr );
394
395   return num;
396 }
397
398 /*
399  * Get a count of trackpoints with the same defined timestamp
400  * Note is using timestamps with a resolution with 1 second
401  */
402 gulong vik_track_get_same_time_point_count ( const VikTrack *tr )
403 {
404   gulong num = 0;
405   GList *iter = tr->trackpoints;
406   while ( iter ) {
407     if ( iter->next &&
408          ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
409            VIK_TRACKPOINT(iter->next->data)->has_timestamp ) &&
410          ( VIK_TRACKPOINT(iter->data)->timestamp ==
411            VIK_TRACKPOINT(iter->next->data)->timestamp) )
412       num++;
413     iter = iter->next;
414   }
415   return num;
416 }
417
418 /*
419  * Deletes adjacent points that have the same defined timestamp
420  * Returns the number of points that were deleted
421  */
422 gulong vik_track_remove_same_time_points ( VikTrack *tr )
423 {
424   gulong num = 0;
425   GList *iter = tr->trackpoints;
426   while ( iter ) {
427     if ( iter->next &&
428          ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
429            VIK_TRACKPOINT(iter->next->data)->has_timestamp ) &&
430          ( VIK_TRACKPOINT(iter->data)->timestamp ==
431            VIK_TRACKPOINT(iter->next->data)->timestamp) ) {
432
433       num++;
434       
435       // Maintain track segments
436       if ( VIK_TRACKPOINT(iter->next->data)->newsegment && (iter->next)->next )
437         VIK_TRACKPOINT(((iter->next)->next)->data)->newsegment = TRUE;
438
439       vik_trackpoint_free ( iter->next->data );
440       tr->trackpoints = g_list_delete_link ( tr->trackpoints, iter->next );
441     }
442     else
443       iter = iter->next;
444   }
445
446   vik_track_calculate_bounds ( tr );
447
448   return num;
449 }
450
451 /*
452  * Deletes all 'extra' trackpoint information
453  *  such as time stamps, speed, course etc...
454  */
455 void vik_track_to_routepoints ( VikTrack *tr )
456 {
457   GList *iter = tr->trackpoints;
458   while ( iter ) {
459
460     // c.f. with vik_trackpoint_new()
461
462     VIK_TRACKPOINT(iter->data)->has_timestamp = FALSE;
463     VIK_TRACKPOINT(iter->data)->timestamp = 0;
464     VIK_TRACKPOINT(iter->data)->speed = NAN;
465     VIK_TRACKPOINT(iter->data)->course = NAN;
466     VIK_TRACKPOINT(iter->data)->hdop = VIK_DEFAULT_DOP;
467     VIK_TRACKPOINT(iter->data)->vdop = VIK_DEFAULT_DOP;
468     VIK_TRACKPOINT(iter->data)->pdop = VIK_DEFAULT_DOP;
469     VIK_TRACKPOINT(iter->data)->nsats = 0;
470     VIK_TRACKPOINT(iter->data)->fix_mode = VIK_GPS_MODE_NOT_SEEN;
471
472     iter = iter->next;
473   }
474 }
475
476 guint vik_track_get_segment_count(const VikTrack *tr)
477 {
478   guint num = 1;
479   GList *iter = tr->trackpoints;
480   if ( !iter )
481     return 0;
482   while ( (iter = iter->next) )
483   {
484     if ( VIK_TRACKPOINT(iter->data)->newsegment )
485       num++;
486   }
487   return num;
488 }
489
490 VikTrack **vik_track_split_into_segments(VikTrack *t, guint *ret_len)
491 {
492   VikTrack **rv;
493   VikTrack *tr;
494   guint i;
495   guint segs = vik_track_get_segment_count(t);
496   GList *iter;
497
498   if ( segs < 2 )
499   {
500     *ret_len = 0;
501     return NULL;
502   }
503
504   rv = g_malloc ( segs * sizeof(VikTrack *) );
505   tr = vik_track_copy ( t, TRUE );
506   rv[0] = tr;
507   iter = tr->trackpoints;
508
509   i = 1;
510   while ( (iter = iter->next) )
511   {
512     if ( VIK_TRACKPOINT(iter->data)->newsegment )
513     {
514       iter->prev->next = NULL;
515       iter->prev = NULL;
516       rv[i] = vik_track_copy ( tr, FALSE );
517       rv[i]->trackpoints = iter;
518
519       vik_track_calculate_bounds ( rv[i] );
520
521       i++;
522     }
523   }
524   *ret_len = segs;
525   return rv;
526 }
527
528 /*
529  * Simply remove any subsequent segment markers in a track to form one continuous track
530  * Return the number of segments merged
531  */
532 guint vik_track_merge_segments(VikTrack *tr)
533 {
534   guint num = 0;
535   GList *iter = tr->trackpoints;
536   if ( !iter )
537     return num;
538
539   // Always skip the first point as this should be the first segment
540   iter = iter->next;
541
542   while ( (iter = iter->next) )
543   {
544     if ( VIK_TRACKPOINT(iter->data)->newsegment ) {
545       VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
546       num++;
547     }
548   }
549   return num;
550 }
551
552 void vik_track_reverse ( VikTrack *tr )
553 {
554   if ( ! tr->trackpoints )
555     return;
556
557   tr->trackpoints = g_list_reverse(tr->trackpoints);
558
559   /* fix 'newsegment' */
560   GList *iter = g_list_last ( tr->trackpoints );
561   while ( iter )
562   {
563     if ( ! iter->next ) /* last segment, was first, cancel newsegment. */
564       VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
565     if ( ! iter->prev ) /* first segment by convention has newsegment flag. */
566       VIK_TRACKPOINT(iter->data)->newsegment = TRUE;
567     else if ( VIK_TRACKPOINT(iter->data)->newsegment && iter->next )
568     {
569       VIK_TRACKPOINT(iter->next->data)->newsegment = TRUE;
570       VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
571     }
572     iter = iter->prev;
573   }
574 }
575
576 /**
577  * vik_track_get_duration:
578  * @trk: The track
579  * @segment_gaps: Whether the duration should include gaps between segments
580  *
581  * Returns: The time in seconds
582  *  NB this may be negative particularly if the track has been reversed
583  */
584 time_t vik_track_get_duration(const VikTrack *trk, gboolean segment_gaps)
585 {
586   time_t duration = 0;
587   if ( trk->trackpoints ) {
588     // Ensure times are available
589     if ( vik_track_get_tp_first(trk)->has_timestamp ) {
590       // Get trkpt only once - as using vik_track_get_tp_last() iterates whole track each time
591       if (segment_gaps) {
592         // Simple duration
593         VikTrackpoint *trkpt_last = vik_track_get_tp_last(trk);
594         if ( trkpt_last->has_timestamp ) {
595           time_t t1 = vik_track_get_tp_first(trk)->timestamp;
596           time_t t2 = trkpt_last->timestamp;
597           duration = t2 - t1;
598         }
599       }
600       else {
601         // Total within segments
602         GList *iter = trk->trackpoints->next;
603         while (iter) {
604           if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
605                VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
606               (!VIK_TRACKPOINT(iter->data)->newsegment) ) {
607             duration += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
608           }
609           iter = iter->next;
610         }
611       }
612     }
613   }
614   return duration;
615 }
616
617 gdouble vik_track_get_average_speed(const VikTrack *tr)
618 {
619   gdouble len = 0.0;
620   guint32 time = 0;
621   if ( tr->trackpoints )
622   {
623     GList *iter = tr->trackpoints->next;
624     while (iter)
625     {
626       if ( VIK_TRACKPOINT(iter->data)->has_timestamp && 
627           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
628           (! VIK_TRACKPOINT(iter->data)->newsegment) )
629       {
630         len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
631                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
632         time += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
633       }
634       iter = iter->next;
635     }
636   }
637   return (time == 0) ? 0 : ABS(len/time);
638 }
639
640 /**
641  * Based on a simple average speed, but with a twist - to give a moving average.
642  *  . GPSs often report a moving average in their statistics output
643  *  . bicycle speedos often don't factor in time when stopped - hence reporting a moving average for speed
644  *
645  * Often GPS track will record every second but not when stationary
646  * This method doesn't use samples that differ over the specified time limit - effectively skipping that time chunk from the total time
647  *
648  * Suggest to use 60 seconds as the stop length (as the default used in the TrackWaypoint draw stops factor)
649  */
650 gdouble vik_track_get_average_speed_moving (const VikTrack *tr, int stop_length_seconds)
651 {
652   gdouble len = 0.0;
653   guint32 time = 0;
654   if ( tr->trackpoints )
655   {
656     GList *iter = tr->trackpoints->next;
657     while (iter)
658     {
659       if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
660           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
661           (! VIK_TRACKPOINT(iter->data)->newsegment) )
662       {
663         if ( ( VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp ) < stop_length_seconds ) {
664           len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
665                                   &(VIK_TRACKPOINT(iter->prev->data)->coord) );
666         
667           time += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
668         }
669       }
670       iter = iter->next;
671     }
672   }
673   return (time == 0) ? 0 : ABS(len/time);
674 }
675
676 gdouble vik_track_get_max_speed(const VikTrack *tr)
677 {
678   gdouble maxspeed = 0.0, speed = 0.0;
679   if ( tr->trackpoints )
680   {
681     GList *iter = tr->trackpoints->next;
682     while (iter)
683     {
684       if ( VIK_TRACKPOINT(iter->data)->has_timestamp && 
685           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
686           (! VIK_TRACKPOINT(iter->data)->newsegment) )
687       {
688         speed =  vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) )
689                  / ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
690         if ( speed > maxspeed )
691           maxspeed = speed;
692       }
693       iter = iter->next;
694     }
695   }
696   return maxspeed;
697 }
698
699 void vik_track_convert ( VikTrack *tr, VikCoordMode dest_mode )
700 {
701   GList *iter = tr->trackpoints;
702   while (iter)
703   {
704     vik_coord_convert ( &(VIK_TRACKPOINT(iter->data)->coord), dest_mode );
705     iter = iter->next;
706   }
707 }
708
709 /* I understood this when I wrote it ... maybe ... Basically it eats up the
710  * proper amounts of length on the track and averages elevation over that. */
711 gdouble *vik_track_make_elevation_map ( const VikTrack *tr, guint16 num_chunks )
712 {
713   gdouble *pts;
714   gdouble total_length, chunk_length, current_dist, current_area_under_curve, current_seg_length, dist_along_seg = 0.0;
715   gdouble altitude1, altitude2;
716   guint16 current_chunk;
717   gboolean ignore_it = FALSE;
718
719   GList *iter = tr->trackpoints;
720
721   if (!iter || !iter->next) /* zero- or one-point track */
722           return NULL;
723
724   { /* test if there's anything worth calculating */
725     gboolean okay = FALSE;
726     while ( iter )
727     {
728       // Sometimes a GPS device (or indeed any random file) can have stupid numbers for elevations
729       // Since when is 9.9999e+24 a valid elevation!!
730       // This can happen when a track (with no elevations) is uploaded to a GPS device and then redownloaded (e.g. using a Garmin Legend EtrexHCx)
731       // Some protection against trying to work with crazily massive numbers (otherwise get SIGFPE, Arithmetic exception)
732       if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE &&
733            VIK_TRACKPOINT(iter->data)->altitude < 1E9 ) {
734         okay = TRUE; break;
735       }
736       iter = iter->next;
737     }
738     if ( ! okay )
739       return NULL;
740   }
741
742   iter = tr->trackpoints;
743
744   g_assert ( num_chunks < 16000 );
745
746   pts = g_malloc ( sizeof(gdouble) * num_chunks );
747
748   total_length = vik_track_get_length_including_gaps ( tr );
749   chunk_length = total_length / num_chunks;
750
751   /* Zero chunk_length (eg, track of 2 tp with the same loc) will cause crash */
752   if (chunk_length <= 0) {
753     g_free(pts);
754     return NULL;
755   }
756
757   current_dist = 0.0;
758   current_area_under_curve = 0;
759   current_chunk = 0;
760   current_seg_length = 0;
761
762   current_seg_length = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
763       &(VIK_TRACKPOINT(iter->next->data)->coord) );
764   altitude1 = VIK_TRACKPOINT(iter->data)->altitude;
765   altitude2 = VIK_TRACKPOINT(iter->next->data)->altitude;
766   dist_along_seg = 0;
767
768   while ( current_chunk < num_chunks ) {
769
770     /* go along current seg */
771     if ( current_seg_length && (current_seg_length - dist_along_seg) > chunk_length ) {
772       dist_along_seg += chunk_length;
773
774       /*        /
775        *   pt2 *
776        *      /x       altitude = alt_at_pt_1 + alt_at_pt_2 / 2 = altitude1 + slope * dist_value_of_pt_inbetween_pt1_and_pt2
777        *     /xx   avg altitude = area under curve / chunk len
778        *pt1 *xxx   avg altitude = altitude1 + (altitude2-altitude1)/(current_seg_length)*(dist_along_seg + (chunk_len/2))
779        *   / xxx
780        *  /  xxx
781        **/
782
783       if ( ignore_it )
784         // Seemly can't determine average for this section - so use last known good value (much better than just sticking in zero)
785         pts[current_chunk] = altitude1;
786       else
787         pts[current_chunk] = altitude1 + (altitude2-altitude1)*((dist_along_seg - (chunk_length/2))/current_seg_length);
788
789       current_chunk++;
790     } else {
791       /* finish current seg */
792       if ( current_seg_length ) {
793         gdouble altitude_at_dist_along_seg = altitude1 + (altitude2-altitude1)/(current_seg_length)*dist_along_seg;
794         current_dist = current_seg_length - dist_along_seg;
795         current_area_under_curve = current_dist*(altitude_at_dist_along_seg + altitude2)*0.5;
796       } else { current_dist = current_area_under_curve = 0; } /* should only happen if first current_seg_length == 0 */
797
798       /* get intervening segs */
799       iter = iter->next;
800       while ( iter && iter->next ) {
801         current_seg_length = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
802             &(VIK_TRACKPOINT(iter->next->data)->coord) );
803         altitude1 = VIK_TRACKPOINT(iter->data)->altitude;
804         altitude2 = VIK_TRACKPOINT(iter->next->data)->altitude;
805         ignore_it = VIK_TRACKPOINT(iter->next->data)->newsegment;
806
807         if ( chunk_length - current_dist >= current_seg_length ) {
808           current_dist += current_seg_length;
809           current_area_under_curve += current_seg_length * (altitude1+altitude2) * 0.5;
810           iter = iter->next;
811         } else {
812           break;
813         }
814       }
815
816       /* final seg */
817       dist_along_seg = chunk_length - current_dist;
818       if ( ignore_it || ( iter && !iter->next ) ) {
819         pts[current_chunk] = current_area_under_curve / current_dist;
820         if (!iter->next) {
821           int i;
822           for (i = current_chunk + 1; i < num_chunks; i++)
823             pts[i] = pts[current_chunk];
824           break;
825         }
826       } 
827       else {
828         current_area_under_curve += dist_along_seg * (altitude1 + (altitude2 - altitude1)*dist_along_seg/current_seg_length);
829         pts[current_chunk] = current_area_under_curve / chunk_length;
830       }
831
832       current_dist = 0;
833       current_chunk++;
834     }
835   }
836
837   return pts;
838 }
839
840
841 void vik_track_get_total_elevation_gain(const VikTrack *tr, gdouble *up, gdouble *down)
842 {
843   gdouble diff;
844   *up = *down = 0;
845   if ( tr->trackpoints && VIK_TRACKPOINT(tr->trackpoints->data)->altitude != VIK_DEFAULT_ALTITUDE )
846   {
847     GList *iter = tr->trackpoints->next;
848     while (iter)
849     {
850       diff = VIK_TRACKPOINT(iter->data)->altitude - VIK_TRACKPOINT(iter->prev->data)->altitude;
851       if ( diff > 0 )
852         *up += diff;
853       else
854         *down -= diff;
855       iter = iter->next;
856     }
857   } else
858     *up = *down = VIK_DEFAULT_ALTITUDE;
859 }
860
861 gdouble *vik_track_make_gradient_map ( const VikTrack *tr, guint16 num_chunks )
862 {
863   gdouble *pts;
864   gdouble *altitudes;
865   gdouble total_length, chunk_length, current_gradient;
866   gdouble altitude1, altitude2;
867   guint16 current_chunk;
868
869   g_assert ( num_chunks < 16000 );
870
871   total_length = vik_track_get_length_including_gaps ( tr );
872   chunk_length = total_length / num_chunks;
873
874   /* Zero chunk_length (eg, track of 2 tp with the same loc) will cause crash */
875   if (chunk_length <= 0) {
876     return NULL;
877   }
878
879   altitudes = vik_track_make_elevation_map (tr, num_chunks);
880   if (altitudes == NULL) {
881     return NULL;
882   }
883
884   current_gradient = 0.0;
885   pts = g_malloc ( sizeof(gdouble) * num_chunks );
886   for (current_chunk = 0; current_chunk < (num_chunks - 1); current_chunk++) {
887     altitude1 = altitudes[current_chunk];
888     altitude2 = altitudes[current_chunk + 1];
889     current_gradient = 100.0 * (altitude2 - altitude1) / chunk_length;
890
891     pts[current_chunk] = current_gradient;
892   }
893
894   pts[current_chunk] = current_gradient;
895
896   g_free ( altitudes );
897
898   return pts;
899 }
900
901 /* by Alex Foobarian */
902 gdouble *vik_track_make_speed_map ( const VikTrack *tr, guint16 num_chunks )
903 {
904   gdouble *v, *s, *t;
905   gdouble duration, chunk_dur;
906   time_t t1, t2;
907   int i, pt_count, numpts, index;
908   GList *iter;
909
910   if ( ! tr->trackpoints )
911     return NULL;
912
913   g_assert ( num_chunks < 16000 );
914
915   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
916   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
917   duration = t2 - t1;
918
919   if ( !t1 || !t2 || !duration )
920     return NULL;
921
922   if (duration < 0) {
923     g_warning("negative duration: unsorted trackpoint timestamps?");
924     return NULL;
925   }
926   pt_count = vik_track_get_tp_count(tr);
927
928   v = g_malloc ( sizeof(gdouble) * num_chunks );
929   chunk_dur = duration / num_chunks;
930
931   s = g_malloc(sizeof(double) * pt_count);
932   t = g_malloc(sizeof(double) * pt_count);
933
934   iter = tr->trackpoints->next;
935   numpts = 0;
936   s[0] = 0;
937   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
938   numpts++;
939   while (iter) {
940     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
941     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
942     numpts++;
943     iter = iter->next;
944   }
945
946   /* In the following computation, we iterate through periods of time of duration chunk_dur.
947    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
948    */
949   index = 0; /* index of the current trackpoint. */
950   for (i = 0; i < num_chunks; i++) {
951     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
952      * find the first trackpoint outside the current interval, averaging the speeds between intermediate trackpoints.
953      */
954     if (t[0] + i*chunk_dur >= t[index]) {
955       gdouble acc_t = 0, acc_s = 0;
956       while (t[0] + i*chunk_dur >= t[index]) {
957         acc_s += (s[index+1]-s[index]);
958         acc_t += (t[index+1]-t[index]);
959         index++;
960       }
961       v[i] = acc_s/acc_t;
962     } 
963     else if (i) {
964       v[i] = v[i-1];
965     }
966     else {
967       v[i] = 0;
968     }
969   }
970   g_free(s);
971   g_free(t);
972   return v;
973 }
974
975 /**
976  * Make a distance/time map, heavily based on the vik_track_make_speed_map method
977  */
978 gdouble *vik_track_make_distance_map ( const VikTrack *tr, guint16 num_chunks )
979 {
980   gdouble *v, *s, *t;
981   gdouble duration, chunk_dur;
982   time_t t1, t2;
983   int i, pt_count, numpts, index;
984   GList *iter;
985
986   if ( ! tr->trackpoints )
987     return NULL;
988
989   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
990   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
991   duration = t2 - t1;
992
993   if ( !t1 || !t2 || !duration )
994     return NULL;
995
996   if (duration < 0) {
997     g_warning("negative duration: unsorted trackpoint timestamps?");
998     return NULL;
999   }
1000   pt_count = vik_track_get_tp_count(tr);
1001
1002   v = g_malloc ( sizeof(gdouble) * num_chunks );
1003   chunk_dur = duration / num_chunks;
1004
1005   s = g_malloc(sizeof(double) * pt_count);
1006   t = g_malloc(sizeof(double) * pt_count);
1007
1008   iter = tr->trackpoints->next;
1009   numpts = 0;
1010   s[0] = 0;
1011   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1012   numpts++;
1013   while (iter) {
1014     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
1015     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
1016     numpts++;
1017     iter = iter->next;
1018   }
1019
1020   /* In the following computation, we iterate through periods of time of duration chunk_dur.
1021    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
1022    */
1023   index = 0; /* index of the current trackpoint. */
1024   for (i = 0; i < num_chunks; i++) {
1025     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
1026      * find the first trackpoint outside the current interval, averaging the distance between intermediate trackpoints.
1027      */
1028     if (t[0] + i*chunk_dur >= t[index]) {
1029       gdouble acc_s = 0; // No need for acc_t
1030       while (t[0] + i*chunk_dur >= t[index]) {
1031         acc_s += (s[index+1]-s[index]);
1032         index++;
1033       }
1034       // The only bit that's really different from the speed map - just keep an accululative record distance
1035       v[i] = i ? v[i-1]+acc_s : acc_s;
1036     }
1037     else if (i) {
1038       v[i] = v[i-1];
1039     }
1040     else {
1041       v[i] = 0;
1042     }
1043   }
1044   g_free(s);
1045   g_free(t);
1046   return v;
1047 }
1048
1049 /**
1050  * This uses the 'time' based method to make the graph, (which is a simpler compared to the elevation/distance)
1051  * This results in a slightly blocky graph when it does not have many trackpoints: <60
1052  * NB Somehow the elevation/distance applies some kind of smoothing algorithm,
1053  *   but I don't think any one understands it any more (I certainly don't ATM)
1054  */
1055 gdouble *vik_track_make_elevation_time_map ( const VikTrack *tr, guint16 num_chunks )
1056 {
1057   time_t t1, t2;
1058   gdouble duration, chunk_dur;
1059   GList *iter = tr->trackpoints;
1060
1061   if (!iter || !iter->next) /* zero- or one-point track */
1062     return NULL;
1063
1064   /* test if there's anything worth calculating */
1065   gboolean okay = FALSE;
1066   while ( iter ) {
1067     if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE ) {
1068       okay = TRUE;
1069       break;
1070     }
1071     iter = iter->next;
1072   }
1073   if ( ! okay )
1074     return NULL;
1075
1076   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1077   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
1078   duration = t2 - t1;
1079
1080   if ( !t1 || !t2 || !duration )
1081     return NULL;
1082
1083   if (duration < 0) {
1084     g_warning("negative duration: unsorted trackpoint timestamps?");
1085     return NULL;
1086   }
1087   gint pt_count = vik_track_get_tp_count(tr);
1088
1089   // Reset iterator back to the beginning
1090   iter = tr->trackpoints;
1091
1092   gdouble *pts = g_malloc ( sizeof(gdouble) * num_chunks ); // The return altitude values
1093   gdouble *s = g_malloc(sizeof(double) * pt_count); // calculation altitudes
1094   gdouble *t = g_malloc(sizeof(double) * pt_count); // calculation times
1095
1096   chunk_dur = duration / num_chunks;
1097
1098   s[0] = VIK_TRACKPOINT(iter->data)->altitude;
1099   t[0] = VIK_TRACKPOINT(iter->data)->timestamp;
1100   iter = tr->trackpoints->next;
1101   gint numpts = 1;
1102   while (iter) {
1103     s[numpts] = VIK_TRACKPOINT(iter->data)->altitude;
1104     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
1105     numpts++;
1106     iter = iter->next;
1107   }
1108
1109  /* In the following computation, we iterate through periods of time of duration chunk_dur.
1110    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
1111    */
1112   gint index = 0; /* index of the current trackpoint. */
1113   gint i;
1114   for (i = 0; i < num_chunks; i++) {
1115     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
1116      * find the first trackpoint outside the current interval, averaging the heights between intermediate trackpoints.
1117      */
1118     if (t[0] + i*chunk_dur >= t[index]) {
1119       gdouble acc_s = s[index]; // initialise to first point
1120       while (t[0] + i*chunk_dur >= t[index]) {
1121         acc_s += (s[index+1]-s[index]);
1122         index++;
1123       }
1124       pts[i] = acc_s;
1125     }
1126     else if (i) {
1127       pts[i] = pts[i-1];
1128     }
1129     else {
1130       pts[i] = 0;
1131     }
1132   }
1133   g_free(s);
1134   g_free(t);
1135
1136   return pts;
1137 }
1138
1139 /**
1140  * Make a speed/distance map
1141  */
1142 gdouble *vik_track_make_speed_dist_map ( const VikTrack *tr, guint16 num_chunks )
1143 {
1144   gdouble *v, *s, *t;
1145   time_t t1, t2;
1146   gint i, pt_count, numpts, index;
1147   GList *iter;
1148   gdouble duration, total_length, chunk_length;
1149
1150   if ( ! tr->trackpoints )
1151     return NULL;
1152
1153   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1154   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
1155   duration = t2 - t1;
1156
1157   if ( !t1 || !t2 || !duration )
1158     return NULL;
1159
1160   if (duration < 0) {
1161     g_warning("negative duration: unsorted trackpoint timestamps?");
1162     return NULL;
1163   }
1164
1165   total_length = vik_track_get_length_including_gaps ( tr );
1166   chunk_length = total_length / num_chunks;
1167   pt_count = vik_track_get_tp_count(tr);
1168
1169   if (chunk_length <= 0) {
1170     return NULL;
1171   }
1172
1173   v = g_malloc ( sizeof(gdouble) * num_chunks );
1174   s = g_malloc ( sizeof(double) * pt_count );
1175   t = g_malloc ( sizeof(double) * pt_count );
1176
1177   // No special handling of segments ATM...
1178   iter = tr->trackpoints->next;
1179   numpts = 0;
1180   s[0] = 0;
1181   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1182   numpts++;
1183   while (iter) {
1184     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
1185     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
1186     numpts++;
1187     iter = iter->next;
1188   }
1189
1190   // Iterate through a portion of the track to get an average speed for that part
1191   // This will essentially interpolate between segments, which I think is right given the usage of 'get_length_including_gaps'
1192   index = 0; /* index of the current trackpoint. */
1193   for (i = 0; i < num_chunks; i++) {
1194     // Similar to the make_speed_map, but instead of using a time chunk, use a distance chunk
1195     if (s[0] + i*chunk_length >= s[index]) {
1196       gdouble acc_t = 0, acc_s = 0;
1197       while (s[0] + i*chunk_length >= s[index]) {
1198         acc_s += (s[index+1]-s[index]);
1199         acc_t += (t[index+1]-t[index]);
1200         index++;
1201       }
1202       v[i] = acc_s/acc_t;
1203     }
1204     else if (i) {
1205       v[i] = v[i-1];
1206     }
1207     else {
1208       v[i] = 0;
1209     }
1210   }
1211   g_free(s);
1212   g_free(t);
1213   return v;
1214 }
1215
1216 /**
1217  * vik_track_get_tp_by_dist:
1218  * @trk:                  The Track on which to find a Trackpoint
1219  * @meters_from_start:    The distance along a track that the trackpoint returned is near
1220  * @get_next_point:       Since there is a choice of trackpoints, this determines which one to return
1221  * @tp_metres_from_start: For the returned Trackpoint, returns the distance along the track
1222  *
1223  * TODO: Consider changing the boolean get_next_point into an enum with these options PREVIOUS, NEXT, NEAREST
1224  *
1225  * Returns: The #VikTrackpoint fitting the criteria or NULL
1226  */
1227 VikTrackpoint *vik_track_get_tp_by_dist ( VikTrack *trk, gdouble meters_from_start, gboolean get_next_point, gdouble *tp_metres_from_start )
1228 {
1229   gdouble current_dist = 0.0;
1230   gdouble current_inc = 0.0;
1231   if ( tp_metres_from_start )
1232     *tp_metres_from_start = 0.0;
1233
1234   if ( trk->trackpoints ) {
1235     GList *iter = g_list_next ( g_list_first ( trk->trackpoints ) );
1236     while (iter) {
1237       current_inc = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
1238                                      &(VIK_TRACKPOINT(iter->prev->data)->coord) );
1239       current_dist += current_inc;
1240       if ( current_dist >= meters_from_start )
1241         break;
1242       iter = g_list_next ( iter );
1243     }
1244     // passed the end of the track
1245     if ( !iter )
1246       return NULL;
1247
1248     if ( tp_metres_from_start )
1249       *tp_metres_from_start = current_dist;
1250
1251     // we've gone past the distance already, is the previous trackpoint wanted?
1252     if ( !get_next_point ) {
1253       if ( iter->prev ) {
1254         if ( tp_metres_from_start )
1255           *tp_metres_from_start = current_dist-current_inc;
1256         return VIK_TRACKPOINT(iter->prev->data);
1257       }
1258     }
1259     return VIK_TRACKPOINT(iter->data);
1260   }
1261
1262   return NULL;
1263 }
1264
1265 /* by Alex Foobarian */
1266 VikTrackpoint *vik_track_get_closest_tp_by_percentage_dist ( VikTrack *tr, gdouble reldist, gdouble *meters_from_start )
1267 {
1268   gdouble dist = vik_track_get_length_including_gaps(tr) * reldist;
1269   gdouble current_dist = 0.0;
1270   gdouble current_inc = 0.0;
1271   if ( tr->trackpoints )
1272   {
1273     GList *iter = tr->trackpoints->next;
1274     GList *last_iter = NULL;
1275     gdouble last_dist = 0.0;
1276     while (iter)
1277     {
1278       current_inc = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
1279                                      &(VIK_TRACKPOINT(iter->prev->data)->coord) );
1280       last_dist = current_dist;
1281       current_dist += current_inc;
1282       if ( current_dist >= dist )
1283         break;
1284       last_iter = iter;
1285       iter = iter->next;
1286     }
1287     if (!iter) { /* passing the end the track */
1288       if (last_iter) {
1289         if (meters_from_start)
1290           *meters_from_start = last_dist;
1291         return(VIK_TRACKPOINT(last_iter->data));
1292       }
1293       else
1294         return NULL;
1295     }
1296     /* we've gone past the dist already, was prev trackpoint closer? */
1297     /* should do a vik_coord_average_weighted() thingy. */
1298     if ( iter->prev && fabs(current_dist-current_inc-dist) < fabs(current_dist-dist) ) {
1299       if (meters_from_start)
1300         *meters_from_start = last_dist;
1301       iter = iter->prev;
1302     }
1303     else
1304       if (meters_from_start)
1305         *meters_from_start = current_dist;
1306
1307     return VIK_TRACKPOINT(iter->data);
1308
1309   }
1310   return NULL;
1311 }
1312
1313 VikTrackpoint *vik_track_get_closest_tp_by_percentage_time ( VikTrack *tr, gdouble reltime, time_t *seconds_from_start )
1314 {
1315   if ( !tr->trackpoints )
1316     return NULL;
1317
1318   time_t t_pos, t_start, t_end, t_total;
1319   t_start = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1320   t_end = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
1321   t_total = t_end - t_start;
1322
1323   t_pos = t_start + t_total * reltime;
1324
1325   GList *iter = tr->trackpoints;
1326
1327   while (iter) {
1328     if (VIK_TRACKPOINT(iter->data)->timestamp == t_pos)
1329       break;
1330     if (VIK_TRACKPOINT(iter->data)->timestamp > t_pos) {
1331       if (iter->prev == NULL)  /* first trackpoint */
1332         break;
1333       time_t t_before = t_pos - VIK_TRACKPOINT(iter->prev->data)->timestamp;
1334       time_t t_after = VIK_TRACKPOINT(iter->data)->timestamp - t_pos;
1335       if (t_before <= t_after)
1336         iter = iter->prev;
1337       break;
1338     }
1339     else if ((iter->next == NULL) && (t_pos < (VIK_TRACKPOINT(iter->data)->timestamp + 3))) /* last trackpoint: accommodate for round-off */
1340       break;
1341     iter = iter->next;
1342   }
1343
1344   if (!iter)
1345     return NULL;
1346   if (seconds_from_start)
1347     *seconds_from_start = VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1348   return VIK_TRACKPOINT(iter->data);
1349 }
1350
1351 VikTrackpoint* vik_track_get_tp_by_max_speed ( const VikTrack *tr )
1352 {
1353   gdouble maxspeed = 0.0, speed = 0.0;
1354
1355   if ( !tr->trackpoints )
1356     return NULL;
1357
1358   GList *iter = tr->trackpoints;
1359   VikTrackpoint *max_speed_tp = NULL;
1360
1361   while (iter) {
1362     if (iter->prev) {
1363       if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
1364            VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
1365            (! VIK_TRACKPOINT(iter->data)->newsegment) ) {
1366         speed =  vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) )
1367           / ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
1368         if ( speed > maxspeed ) {
1369           maxspeed = speed;
1370           max_speed_tp = VIK_TRACKPOINT(iter->data);
1371         }
1372       }
1373     }
1374     iter = iter->next;
1375   }
1376   
1377   if (!max_speed_tp)
1378     return NULL;
1379
1380   return max_speed_tp;
1381 }
1382
1383 VikTrackpoint* vik_track_get_tp_by_max_alt ( const VikTrack *tr )
1384 {
1385   gdouble maxalt = -5000.0;
1386   if ( !tr->trackpoints )
1387     return NULL;
1388
1389   GList *iter = tr->trackpoints;
1390   VikTrackpoint *max_alt_tp = NULL;
1391
1392   while (iter) {
1393     if ( VIK_TRACKPOINT(iter->data)->altitude > maxalt ) {
1394       maxalt = VIK_TRACKPOINT(iter->data)->altitude;
1395       max_alt_tp = VIK_TRACKPOINT(iter->data);
1396     }
1397     iter = iter->next;
1398   }
1399
1400   if (!max_alt_tp)
1401     return NULL;
1402
1403   return max_alt_tp;
1404 }
1405
1406 VikTrackpoint* vik_track_get_tp_by_min_alt ( const VikTrack *tr )
1407 {
1408   gdouble minalt = 25000.0;
1409   if ( !tr->trackpoints )
1410     return NULL;
1411
1412   GList *iter = tr->trackpoints;
1413   VikTrackpoint *min_alt_tp = NULL;
1414
1415   while (iter) {
1416     if ( VIK_TRACKPOINT(iter->data)->altitude < minalt ) {
1417       minalt = VIK_TRACKPOINT(iter->data)->altitude;
1418       min_alt_tp = VIK_TRACKPOINT(iter->data);
1419     }
1420     iter = iter->next;
1421   }
1422
1423   if (!min_alt_tp)
1424     return NULL;
1425
1426   return min_alt_tp;
1427 }
1428
1429 VikTrackpoint *vik_track_get_tp_first( const VikTrack *tr )
1430 {
1431   if ( !tr->trackpoints )
1432     return NULL;
1433
1434   return (VikTrackpoint*)g_list_first(tr->trackpoints)->data;
1435 }
1436
1437 VikTrackpoint *vik_track_get_tp_last ( const VikTrack *tr )
1438 {
1439   if ( !tr->trackpoints )
1440     return NULL;
1441
1442   return (VikTrackpoint*)g_list_last(tr->trackpoints)->data;
1443 }
1444
1445 VikTrackpoint *vik_track_get_tp_prev ( const VikTrack *tr, VikTrackpoint *tp )
1446 {
1447   if ( !tr->trackpoints )
1448     return NULL;
1449
1450   GList *iter = tr->trackpoints;
1451   VikTrackpoint *tp_prev = NULL;
1452
1453   while (iter) {
1454     if (iter->prev) {
1455       if ( VIK_TRACKPOINT(iter->data) == tp ) {
1456         tp_prev = VIK_TRACKPOINT(iter->prev->data);
1457         break;
1458       }
1459     }
1460     iter = iter->next;
1461   }
1462
1463   return tp_prev;
1464 }
1465
1466 gboolean vik_track_get_minmax_alt ( const VikTrack *tr, gdouble *min_alt, gdouble *max_alt )
1467 {
1468   *min_alt = 25000;
1469   *max_alt = -5000;
1470   if ( tr && tr->trackpoints && tr->trackpoints->data && (VIK_TRACKPOINT(tr->trackpoints->data)->altitude != VIK_DEFAULT_ALTITUDE) ) {
1471     GList *iter = tr->trackpoints->next;
1472     gdouble tmp_alt;
1473     while (iter)
1474     {
1475       tmp_alt = VIK_TRACKPOINT(iter->data)->altitude;
1476       if ( tmp_alt > *max_alt )
1477         *max_alt = tmp_alt;
1478       if ( tmp_alt < *min_alt )
1479         *min_alt = tmp_alt;
1480       iter = iter->next;
1481     }
1482     return TRUE;
1483   }
1484   return FALSE;
1485 }
1486
1487 void vik_track_marshall ( VikTrack *tr, guint8 **data, guint *datalen)
1488 {
1489   GList *tps;
1490   GByteArray *b = g_byte_array_new();
1491   guint len;
1492   guint intp, ntp;
1493
1494   g_byte_array_append(b, (guint8 *)tr, sizeof(*tr));
1495
1496   /* we'll fill out number of trackpoints later */
1497   intp = b->len;
1498   g_byte_array_append(b, (guint8 *)&len, sizeof(len));
1499
1500   // This allocates space for variant sized strings
1501   //  and copies that amount of data from the track to byte array
1502 #define vtm_append(s) \
1503   len = (s) ? strlen(s)+1 : 0; \
1504   g_byte_array_append(b, (guint8 *)&len, sizeof(len)); \
1505   if (s) g_byte_array_append(b, (guint8 *)s, len);
1506
1507   tps = tr->trackpoints;
1508   ntp = 0;
1509   while (tps) {
1510     g_byte_array_append(b, (guint8 *)tps->data, sizeof(VikTrackpoint));
1511     vtm_append(VIK_TRACKPOINT(tps->data)->name);
1512     tps = tps->next;
1513     ntp++;
1514   }
1515   *(guint *)(b->data + intp) = ntp;
1516
1517   vtm_append(tr->name);
1518   vtm_append(tr->comment);
1519   vtm_append(tr->description);
1520   vtm_append(tr->source);
1521
1522   *data = b->data;
1523   *datalen = b->len;
1524   g_byte_array_free(b, FALSE);
1525 }
1526
1527 /*
1528  * Take a byte array and convert it into a Track
1529  */
1530 VikTrack *vik_track_unmarshall (guint8 *data, guint datalen)
1531 {
1532   guint len;
1533   VikTrack *new_tr = vik_track_new();
1534   VikTrackpoint *new_tp;
1535   guint ntp;
1536   gint i;
1537
1538   /* basic properties: */
1539   new_tr->visible = ((VikTrack *)data)->visible;
1540   new_tr->is_route = ((VikTrack *)data)->is_route;
1541   new_tr->draw_name_mode = ((VikTrack *)data)->draw_name_mode;
1542   new_tr->max_number_dist_labels = ((VikTrack *)data)->max_number_dist_labels;
1543   new_tr->has_color = ((VikTrack *)data)->has_color;
1544   new_tr->color = ((VikTrack *)data)->color;
1545   new_tr->bbox = ((VikTrack *)data)->bbox;
1546
1547   data += sizeof(*new_tr);
1548
1549   ntp = *(guint *)data;
1550   data += sizeof(ntp);
1551
1552 #define vtu_get(s) \
1553   len = *(guint *)data; \
1554   data += sizeof(len); \
1555   if (len) { \
1556     (s) = g_strdup((gchar *)data); \
1557   } else { \
1558     (s) = NULL; \
1559   } \
1560   data += len;
1561
1562   for (i=0; i<ntp; i++) {
1563     new_tp = vik_trackpoint_new();
1564     memcpy(new_tp, data, sizeof(*new_tp));
1565     data += sizeof(*new_tp);
1566     vtu_get(new_tp->name);
1567     new_tr->trackpoints = g_list_prepend(new_tr->trackpoints, new_tp);
1568   }
1569   if ( new_tr->trackpoints )
1570     new_tr->trackpoints = g_list_reverse(new_tr->trackpoints);
1571
1572   vtu_get(new_tr->name);
1573   vtu_get(new_tr->comment);
1574   vtu_get(new_tr->description);
1575   vtu_get(new_tr->source);
1576
1577   return new_tr;
1578 }
1579
1580 /**
1581  * (Re)Calculate the bounds of the given track,
1582  *  updating the track's bounds data.
1583  * This should be called whenever a track's trackpoints are changed
1584  */
1585 void vik_track_calculate_bounds ( VikTrack *trk )
1586 {
1587   GList *tp_iter;
1588   tp_iter = trk->trackpoints;
1589   
1590   struct LatLon topleft, bottomright, ll;
1591   
1592   // Set bounds to first point
1593   if ( tp_iter ) {
1594     vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &topleft );
1595     vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &bottomright );
1596   }
1597   while ( tp_iter ) {
1598
1599     // See if this trackpoint increases the track bounds.
1600    
1601     vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &ll );
1602   
1603     if ( ll.lat > topleft.lat) topleft.lat = ll.lat;
1604     if ( ll.lon < topleft.lon) topleft.lon = ll.lon;
1605     if ( ll.lat < bottomright.lat) bottomright.lat = ll.lat;
1606     if ( ll.lon > bottomright.lon) bottomright.lon = ll.lon;
1607     
1608     tp_iter = tp_iter->next;
1609   }
1610  
1611   g_debug ( "Bounds of track: '%s' is: %f,%f to: %f,%f", trk->name, topleft.lat, topleft.lon, bottomright.lat, bottomright.lon );
1612
1613   trk->bbox.north = topleft.lat;
1614   trk->bbox.east = bottomright.lon;
1615   trk->bbox.south = bottomright.lat;
1616   trk->bbox.west = topleft.lon;
1617 }
1618
1619 /**
1620  * vik_track_anonymize_times:
1621  *
1622  * Shift all timestamps to be relatively offset from 1901-01-01
1623  */
1624 void vik_track_anonymize_times ( VikTrack *tr )
1625 {
1626   GTimeVal gtv;
1627   // Check result just to please Coverity - even though it shouldn't fail as it's a hard coded value here!
1628   if ( !g_time_val_from_iso8601 ( "1901-01-01T00:00:00Z", &gtv ) ) {
1629     g_critical ( "Calendar time value failure" );
1630     return;
1631   }
1632
1633   time_t anon_timestamp = gtv.tv_sec;
1634   time_t offset = 0;
1635
1636   GList *tp_iter;
1637   tp_iter = tr->trackpoints;
1638   while ( tp_iter ) {
1639     VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
1640     if ( tp->has_timestamp ) {
1641       // Calculate an offset in time using the first available timestamp
1642       if ( offset == 0 )
1643         offset = tp->timestamp - anon_timestamp;
1644
1645       // Apply this offset to shift all timestamps towards 1901 & hence anonymising the time
1646       // Note that the relative difference between timestamps is kept - thus calculating speeds will still work
1647       tp->timestamp = tp->timestamp - offset;
1648     }
1649     tp_iter = tp_iter->next;
1650   }
1651 }
1652
1653 /**
1654  * vik_track_interpolate_times:
1655  *
1656  * Interpolate the timestamps between first and last trackpoint,
1657  * so that the track is driven at equal speed, regardless of the
1658  * distance between individual trackpoints.
1659  *
1660  * NB This will overwrite any existing trackpoint timestamps
1661  */
1662 void vik_track_interpolate_times ( VikTrack *tr )
1663 {
1664   gdouble tr_dist, cur_dist;
1665   time_t tsdiff, tsfirst;
1666
1667   GList *iter;
1668   iter = tr->trackpoints;
1669
1670   VikTrackpoint *tp = VIK_TRACKPOINT(iter->data);
1671   if ( tp->has_timestamp ) {
1672     tsfirst = tp->timestamp;
1673
1674     // Find the end of the track and the last timestamp
1675     while ( iter->next ) {
1676       iter = iter->next;
1677     }
1678     tp = VIK_TRACKPOINT(iter->data);
1679     if ( tp->has_timestamp ) {
1680       tsdiff = tp->timestamp - tsfirst;
1681
1682       tr_dist = vik_track_get_length_including_gaps ( tr );
1683       cur_dist = 0.0;
1684
1685       if ( tr_dist > 0 ) {
1686         iter = tr->trackpoints;
1687         // Apply the calculated timestamp to all trackpoints except the first and last ones
1688         while ( iter->next && iter->next->next ) {
1689           iter = iter->next;
1690           tp = VIK_TRACKPOINT(iter->data);
1691           cur_dist += vik_coord_diff ( &(tp->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) );
1692
1693           tp->timestamp = (cur_dist / tr_dist) * tsdiff + tsfirst;
1694           tp->has_timestamp = TRUE;
1695         }
1696         // Some points may now have the same time so remove them.
1697         vik_track_remove_same_time_points ( tr );
1698       }
1699     }
1700   }
1701 }
1702
1703 /**
1704  * vik_track_apply_dem_data:
1705  * @skip_existing: When TRUE, don't change the elevation if the trackpoint already has a value
1706  *
1707  * Set elevation data for a track using any available DEM information
1708  */
1709 gulong vik_track_apply_dem_data ( VikTrack *tr, gboolean skip_existing )
1710 {
1711   gulong num = 0;
1712   GList *tp_iter;
1713   gint16 elev;
1714   tp_iter = tr->trackpoints;
1715   while ( tp_iter ) {
1716     // Don't apply if the point already has a value and the overwrite is off
1717     if ( !(skip_existing && VIK_TRACKPOINT(tp_iter->data)->altitude != VIK_DEFAULT_ALTITUDE) ) {
1718       /* TODO: of the 4 possible choices we have for choosing an elevation
1719        * (trackpoint in between samples), choose the one with the least elevation change
1720        * as the last */
1721       elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(tp_iter->data)->coord), VIK_DEM_INTERPOL_BEST );
1722
1723       if ( elev != VIK_DEM_INVALID_ELEVATION ) {
1724         VIK_TRACKPOINT(tp_iter->data)->altitude = elev;
1725         num++;
1726       }
1727     }
1728     tp_iter = tp_iter->next;
1729   }
1730   return num;
1731 }
1732
1733 /**
1734  * vik_track_apply_dem_data_last_trackpoint:
1735  * Apply DEM data (if available) - to only the last trackpoint
1736  */
1737 void vik_track_apply_dem_data_last_trackpoint ( VikTrack *tr )
1738 {
1739   gint16 elev;
1740   if ( tr->trackpoints ) {
1741     /* As in vik_track_apply_dem_data above - use 'best' interpolation method */
1742     elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->coord), VIK_DEM_INTERPOL_BEST );
1743     if ( elev != VIK_DEM_INVALID_ELEVATION )
1744       VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->altitude = elev;
1745   }
1746 }
1747
1748
1749 /**
1750  * smoothie:
1751  *
1752  * Apply elevation smoothing over range of trackpoints between the list start and end points
1753  */
1754 static void smoothie ( GList *tp1, GList *tp2, gdouble elev1, gdouble elev2, guint points )
1755 {
1756   // If was really clever could try and weigh interpolation according to the distance between trackpoints somehow
1757   // Instead a simple average interpolation for the number of points given.
1758   gdouble change = (elev2 - elev1)/(points+1);
1759   gint count = 1;
1760   GList *tp_iter = tp1;
1761   while ( tp_iter != tp2 && tp_iter ) {
1762     VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
1763
1764     tp->altitude = elev1 + (change*count);
1765
1766     count++;
1767     tp_iter = tp_iter->next;
1768   }
1769 }
1770
1771 /**
1772  * vik_track_smooth_missing_elevation_data:
1773  * @flat: Specify how the missing elevations will be set.
1774  *        When TRUE it uses a simple flat method, using the last known elevation
1775  *        When FALSE is uses an interpolation method to the next known elevation
1776  *
1777  * For each point with a missing elevation, set it to use the last known available elevation value.
1778  * Primarily of use for smallish DEM holes where it is missing elevation data.
1779  * Eg see Austria: around N47.3 & E13.8
1780  *
1781  * Returns: The number of points that were adjusted
1782  */
1783 gulong vik_track_smooth_missing_elevation_data ( VikTrack *tr, gboolean flat )
1784 {
1785   gulong num = 0;
1786
1787   GList *tp_iter;
1788   gdouble elev = VIK_DEFAULT_ALTITUDE;
1789
1790   VikTrackpoint *tp_missing = NULL;
1791   GList *iter_first = NULL;
1792   guint points = 0;
1793
1794   tp_iter = tr->trackpoints;
1795   while ( tp_iter ) {
1796     VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
1797
1798     if ( VIK_DEFAULT_ALTITUDE == tp->altitude ) {
1799       if ( flat ) {
1800         // Simply assign to last known value
1801         if ( elev != VIK_DEFAULT_ALTITUDE ) {
1802           tp->altitude = elev;
1803           num++;
1804         }
1805       }
1806       else {
1807         if ( !tp_missing ) {
1808           // Remember the first trackpoint (and the list pointer to it) of a section of no altitudes
1809           tp_missing = tp;
1810           iter_first = tp_iter;
1811           points = 1;
1812         }
1813         else {
1814           // More missing altitudes
1815           points++;
1816         }
1817       }
1818     }
1819     else {
1820       // Altitude available (maybe again!)
1821       // If this marks the end of a section of altitude-less points
1822       //  then apply smoothing for that section of points
1823       if ( points > 0 && elev != VIK_DEFAULT_ALTITUDE )
1824         if ( !flat ) {
1825           smoothie ( iter_first, tp_iter, elev, tp->altitude, points );
1826           num = num + points;
1827         }
1828
1829       // reset
1830       points = 0;
1831       tp_missing = NULL;
1832
1833       // Store for reuse as the last known good value
1834       elev = tp->altitude;
1835     }
1836
1837     tp_iter = tp_iter->next;
1838   }
1839
1840   return num;
1841 }
1842
1843 /**
1844  * vik_track_steal_and_append_trackpoints:
1845  * 
1846  * appends t2 to t1, leaving t2 with no trackpoints
1847  */
1848 void vik_track_steal_and_append_trackpoints ( VikTrack *t1, VikTrack *t2 )
1849 {
1850   if ( t1->trackpoints ) {
1851     t1->trackpoints = g_list_concat ( t1->trackpoints, t2->trackpoints );
1852   } else
1853     t1->trackpoints = t2->trackpoints;
1854   t2->trackpoints = NULL;
1855
1856   // Trackpoints updated - so update the bounds
1857   vik_track_calculate_bounds ( t1 );
1858 }
1859
1860 /**
1861  * vik_track_cut_back_to_double_point:
1862  * 
1863  * starting at the end, looks backwards for the last "double point", a duplicate trackpoint.
1864  * If there is no double point, deletes all the trackpoints.
1865  * 
1866  * Returns: the new end of the track (or the start if there are no double points)
1867  */
1868 VikCoord *vik_track_cut_back_to_double_point ( VikTrack *tr )
1869 {
1870   GList *iter = tr->trackpoints;
1871   VikCoord *rv;
1872
1873   if ( !iter )
1874     return NULL;
1875   while ( iter->next )
1876     iter = iter->next;
1877
1878
1879   while ( iter->prev ) {
1880     VikCoord *cur_coord = &((VikTrackpoint*)iter->data)->coord;
1881     VikCoord *prev_coord = &((VikTrackpoint*)iter->prev->data)->coord;
1882     if ( vik_coord_equals(cur_coord, prev_coord) ) {
1883       GList *prev = iter->prev;
1884
1885       rv = g_malloc(sizeof(VikCoord));
1886       *rv = *cur_coord;
1887
1888       /* truncate trackpoint list */
1889       iter->prev = NULL; /* pretend it's the end */
1890       g_list_foreach ( iter, (GFunc) g_free, NULL );
1891       g_list_free( iter );
1892
1893       prev->next = NULL;
1894
1895       return rv;
1896     }
1897     iter = iter->prev;
1898   }
1899
1900   /* no double point found! */
1901   rv = g_malloc(sizeof(VikCoord));
1902   *rv = ((VikTrackpoint*) tr->trackpoints->data)->coord;
1903   g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
1904   g_list_free( tr->trackpoints );
1905   tr->trackpoints = NULL;
1906   return rv;
1907 }
1908
1909 /**
1910  * Function to compare two tracks by their first timestamp
1911  **/
1912 int vik_track_compare_timestamp (const void *x, const void *y)
1913 {
1914   VikTrack *a = (VikTrack *)x;
1915   VikTrack *b = (VikTrack *)y;
1916
1917   VikTrackpoint *tpa = NULL;
1918   VikTrackpoint *tpb = NULL;
1919
1920   if ( a->trackpoints )
1921     tpa = VIK_TRACKPOINT(g_list_first(a->trackpoints)->data);
1922
1923   if ( b->trackpoints )
1924     tpb = VIK_TRACKPOINT(g_list_first(b->trackpoints)->data);
1925
1926   if ( tpa && tpb ) {
1927     if ( tpa->timestamp < tpb->timestamp )
1928       return -1;
1929     if ( tpa->timestamp > tpb->timestamp )
1930       return 1;
1931   }
1932
1933   if ( tpa && !tpb )
1934     return 1;
1935
1936   if ( !tpa && tpb )
1937     return -1;
1938
1939   return 0;
1940 }