]> git.street.me.uk Git - andy/viking.git/blob - src/viktrack.c
Add some protection against crazy elevation numbers that cause viewing a track's...
[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  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <glib.h>
26 #include <time.h>
27 #include <stdlib.h>
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #ifdef HAVE_MATH_H
32 #include <math.h>
33 #endif
34
35 #include "coords.h"
36 #include "vikcoord.h"
37 #include "viktrack.h"
38 #include "globals.h"
39 #include "dems.h"
40
41 VikTrack *vik_track_new()
42 {
43   VikTrack *tr = g_malloc0 ( sizeof ( VikTrack ) );
44   tr->ref_count = 1;
45   return tr;
46 }
47
48 void vik_track_set_comment_no_copy(VikTrack *tr, gchar *comment)
49 {
50   if ( tr->comment )
51     g_free ( tr->comment );
52   tr->comment = comment;
53 }
54
55
56 void vik_track_set_name(VikTrack *tr, const gchar *name)
57 {
58   if ( tr->name )
59     g_free ( tr->name );
60
61   if ( name && name[0] != '\0' )
62     tr->name = g_strdup(name);
63   else
64     tr->name = NULL;
65 }
66
67 void vik_track_set_comment(VikTrack *tr, const gchar *comment)
68 {
69   if ( tr->comment )
70     g_free ( tr->comment );
71
72   if ( comment && comment[0] != '\0' )
73     tr->comment = g_strdup(comment);
74   else
75     tr->comment = NULL;
76 }
77
78 void vik_track_ref(VikTrack *tr)
79 {
80   tr->ref_count++;
81 }
82
83 void vik_track_set_property_dialog(VikTrack *tr, GtkWidget *dialog)
84 {
85   /* Warning: does not check for existing dialog */
86   tr->property_dialog = dialog;
87 }
88
89 void vik_track_clear_property_dialog(VikTrack *tr)
90 {
91   tr->property_dialog = NULL;
92 }
93
94 void vik_track_free(VikTrack *tr)
95 {
96   if ( tr->ref_count-- > 1 )
97     return;
98
99   if ( tr->name )
100     g_free ( tr->name );
101   if ( tr->comment )
102     g_free ( tr->comment );
103   g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
104   g_list_free( tr->trackpoints );
105   if (tr->property_dialog)
106     if ( GTK_IS_WIDGET(tr->property_dialog) )
107       gtk_widget_destroy ( GTK_WIDGET(tr->property_dialog) );
108   g_free ( tr );
109 }
110
111 VikTrack *vik_track_copy ( const VikTrack *tr )
112 {
113   VikTrack *new_tr = vik_track_new();
114   VikTrackpoint *new_tp;
115   GList *tp_iter = tr->trackpoints;
116   new_tr->visible = tr->visible;
117   new_tr->trackpoints = NULL;
118   while ( tp_iter )
119   {
120     new_tp = g_malloc ( sizeof ( VikTrackpoint ) );
121     *new_tp = *((VikTrackpoint *)(tp_iter->data));
122     new_tr->trackpoints = g_list_append ( new_tr->trackpoints, new_tp );
123     tp_iter = tp_iter->next;
124   }
125   vik_track_set_name(new_tr,tr->name);
126   vik_track_set_comment(new_tr,tr->comment);
127   return new_tr;
128 }
129
130 VikTrackpoint *vik_trackpoint_new()
131 {
132   VikTrackpoint *tp = g_malloc0(sizeof(VikTrackpoint));
133   tp->speed = NAN;
134   tp->course = NAN;
135   tp->altitude = VIK_DEFAULT_ALTITUDE;
136   tp->hdop = VIK_DEFAULT_DOP;
137   tp->vdop = VIK_DEFAULT_DOP;
138   tp->pdop = VIK_DEFAULT_DOP;
139   return tp;
140 }
141
142 void vik_trackpoint_free(VikTrackpoint *tp)
143 {
144   g_free(tp);
145 }
146
147 VikTrackpoint *vik_trackpoint_copy(VikTrackpoint *tp)
148 {
149   VikTrackpoint *rv = vik_trackpoint_new();
150   *rv = *tp;
151   return rv;
152 }
153
154 gdouble vik_track_get_length(const VikTrack *tr)
155 {
156   gdouble len = 0.0;
157   if ( tr->trackpoints )
158   {
159     GList *iter = tr->trackpoints->next;
160     while (iter)
161     {
162       if ( ! VIK_TRACKPOINT(iter->data)->newsegment )
163         len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
164                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
165       iter = iter->next;
166     }
167   }
168   return len;
169 }
170
171 gdouble vik_track_get_length_including_gaps(const VikTrack *tr)
172 {
173   gdouble len = 0.0;
174   if ( tr->trackpoints )
175   {
176     GList *iter = tr->trackpoints->next;
177     while (iter)
178     {
179       len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
180                               &(VIK_TRACKPOINT(iter->prev->data)->coord) );
181       iter = iter->next;
182     }
183   }
184   return len;
185 }
186
187 gulong vik_track_get_tp_count(const VikTrack *tr)
188 {
189   gulong num = 0;
190   GList *iter = tr->trackpoints;
191   while ( iter )
192   {
193     num++;
194     iter = iter->next;
195   }
196   return num;
197 }
198
199 gulong vik_track_get_dup_point_count ( const VikTrack *tr )
200 {
201   gulong num = 0;
202   GList *iter = tr->trackpoints;
203   while ( iter )
204   {
205     if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
206                        &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
207       num++;
208     iter = iter->next;
209   }
210   return num;
211 }
212
213 void vik_track_remove_dup_points ( VikTrack *tr )
214 {
215   GList *iter = tr->trackpoints;
216   while ( iter )
217   {
218     if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
219                        &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
220     {
221       g_free ( iter->next->data );
222       tr->trackpoints = g_list_delete_link ( tr->trackpoints, iter->next );
223     }
224     else
225       iter = iter->next;
226   }
227 }
228
229 guint vik_track_get_segment_count(const VikTrack *tr)
230 {
231   guint num = 1;
232   GList *iter = tr->trackpoints;
233   if ( !iter )
234     return 0;
235   while ( (iter = iter->next) )
236   {
237     if ( VIK_TRACKPOINT(iter->data)->newsegment )
238       num++;
239   }
240   return num;
241 }
242
243 VikTrack **vik_track_split_into_segments(VikTrack *t, guint *ret_len)
244 {
245   VikTrack **rv;
246   VikTrack *tr;
247   guint i;
248   guint segs = vik_track_get_segment_count(t);
249   GList *iter;
250
251   if ( segs < 2 )
252   {
253     *ret_len = 0;
254     return NULL;
255   }
256
257   rv = g_malloc ( segs * sizeof(VikTrack *) );
258   tr = vik_track_copy ( t );
259   rv[0] = tr;
260   iter = tr->trackpoints;
261
262   i = 1;
263   while ( (iter = iter->next) )
264   {
265     if ( VIK_TRACKPOINT(iter->data)->newsegment )
266     {
267       iter->prev->next = NULL;
268       iter->prev = NULL;
269       rv[i] = vik_track_new();
270       // TODO: consider new naming strategy here
271       if ( tr->name )
272         vik_track_set_name ( rv[i], tr->name );
273       if ( tr->comment )
274         vik_track_set_comment ( rv[i], tr->comment );
275       rv[i]->visible = tr->visible;
276       rv[i]->trackpoints = iter;
277       i++;
278     }
279   }
280   *ret_len = segs;
281   return rv;
282 }
283
284 void vik_track_reverse ( VikTrack *tr )
285 {
286   GList *iter;
287   tr->trackpoints = g_list_reverse(tr->trackpoints);
288
289   /* fix 'newsegment' */
290   iter = g_list_last ( tr->trackpoints );
291   while ( iter )
292   {
293     if ( ! iter->next ) /* last segment, was first, cancel newsegment. */
294       VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
295     if ( ! iter->prev ) /* first segment by convention has newsegment flag. */
296       VIK_TRACKPOINT(iter->data)->newsegment = TRUE;
297     else if ( VIK_TRACKPOINT(iter->data)->newsegment && iter->next )
298     {
299       VIK_TRACKPOINT(iter->next->data)->newsegment = TRUE;
300       VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
301     }
302     iter = iter->prev;
303   }
304 }
305
306 gdouble vik_track_get_average_speed(const VikTrack *tr)
307 {
308   gdouble len = 0.0;
309   guint32 time = 0;
310   if ( tr->trackpoints )
311   {
312     GList *iter = tr->trackpoints->next;
313     while (iter)
314     {
315       if ( VIK_TRACKPOINT(iter->data)->has_timestamp && 
316           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
317           (! VIK_TRACKPOINT(iter->data)->newsegment) )
318       {
319         len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
320                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
321         time += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
322       }
323       iter = iter->next;
324     }
325   }
326   return (time == 0) ? 0 : ABS(len/time);
327 }
328
329 /**
330  * Based on a simple average speed, but with a twist - to give a moving average.
331  *  . GPSs often report a moving average in their statistics output
332  *  . bicycle speedos often don't factor in time when stopped - hence reporting a moving average for speed
333  *
334  * Often GPS track will record every second but not when stationary
335  * This method doesn't use samples that differ over the specified time limit - effectively skipping that time chunk from the total time
336  *
337  * Suggest to use 60 seconds as the stop length (as the default used in the TrackWaypoint draw stops factor)
338  */
339 gdouble vik_track_get_average_speed_moving (const VikTrack *tr, int stop_length_seconds)
340 {
341   gdouble len = 0.0;
342   guint32 time = 0;
343   if ( tr->trackpoints )
344   {
345     GList *iter = tr->trackpoints->next;
346     while (iter)
347     {
348       if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
349           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
350           (! VIK_TRACKPOINT(iter->data)->newsegment) )
351       {
352         if ( ( VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp ) < stop_length_seconds ) {
353           len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
354                                   &(VIK_TRACKPOINT(iter->prev->data)->coord) );
355         
356           time += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
357         }
358       }
359       iter = iter->next;
360     }
361   }
362   return (time == 0) ? 0 : ABS(len/time);
363 }
364
365 gdouble vik_track_get_max_speed(const VikTrack *tr)
366 {
367   gdouble maxspeed = 0.0, speed = 0.0;
368   if ( tr->trackpoints )
369   {
370     GList *iter = tr->trackpoints->next;
371     while (iter)
372     {
373       if ( VIK_TRACKPOINT(iter->data)->has_timestamp && 
374           VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
375           (! VIK_TRACKPOINT(iter->data)->newsegment) )
376       {
377         speed =  vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) )
378                  / ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
379         if ( speed > maxspeed )
380           maxspeed = speed;
381       }
382       iter = iter->next;
383     }
384   }
385   return maxspeed;
386 }
387
388 void vik_track_convert ( VikTrack *tr, VikCoordMode dest_mode )
389 {
390   GList *iter = tr->trackpoints;
391   while (iter)
392   {
393     vik_coord_convert ( &(VIK_TRACKPOINT(iter->data)->coord), dest_mode );
394     iter = iter->next;
395   }
396 }
397
398 /* I understood this when I wrote it ... maybe ... Basically it eats up the
399  * proper amounts of length on the track and averages elevation over that. */
400 gdouble *vik_track_make_elevation_map ( const VikTrack *tr, guint16 num_chunks )
401 {
402   gdouble *pts;
403   gdouble total_length, chunk_length, current_dist, current_area_under_curve, current_seg_length, dist_along_seg = 0.0;
404   gdouble altitude1, altitude2;
405   guint16 current_chunk;
406   gboolean ignore_it = FALSE;
407
408   GList *iter = tr->trackpoints;
409
410   if (!iter || !iter->next) /* zero- or one-point track */
411           return NULL;
412
413   { /* test if there's anything worth calculating */
414     gboolean okay = FALSE;
415     while ( iter )
416     {
417       // Sometimes a GPS device (or indeed any random file) can have stupid numbers for elevations
418       // Since when is 9.9999e+24 a valid elevation!!
419       // 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)
420       // Some protection against trying to work with crazily massive numbers (otherwise get SIGFPE, Arithmetic exception)
421       if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE &&
422            VIK_TRACKPOINT(iter->data)->altitude < 1E9 ) {
423         okay = TRUE; break;
424       }
425       iter = iter->next;
426     }
427     if ( ! okay )
428       return NULL;
429   }
430
431   iter = tr->trackpoints;
432
433   g_assert ( num_chunks < 16000 );
434
435   pts = g_malloc ( sizeof(gdouble) * num_chunks );
436
437   total_length = vik_track_get_length_including_gaps ( tr );
438   chunk_length = total_length / num_chunks;
439
440   /* Zero chunk_length (eg, track of 2 tp with the same loc) will cause crash */
441   if (chunk_length <= 0) {
442     g_free(pts);
443     return NULL;
444   }
445
446   current_dist = 0.0;
447   current_area_under_curve = 0;
448   current_chunk = 0;
449   current_seg_length = 0;
450
451   current_seg_length = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
452       &(VIK_TRACKPOINT(iter->next->data)->coord) );
453   altitude1 = VIK_TRACKPOINT(iter->data)->altitude;
454   altitude2 = VIK_TRACKPOINT(iter->next->data)->altitude;
455   dist_along_seg = 0;
456
457   while ( current_chunk < num_chunks ) {
458
459     /* go along current seg */
460     if ( current_seg_length && (current_seg_length - dist_along_seg) > chunk_length ) {
461       dist_along_seg += chunk_length;
462
463       /*        /
464        *   pt2 *
465        *      /x       altitude = alt_at_pt_1 + alt_at_pt_2 / 2 = altitude1 + slope * dist_value_of_pt_inbetween_pt1_and_pt2
466        *     /xx   avg altitude = area under curve / chunk len
467        *pt1 *xxx   avg altitude = altitude1 + (altitude2-altitude1)/(current_seg_length)*(dist_along_seg + (chunk_len/2))
468        *   / xxx
469        *  /  xxx
470        **/
471
472       if ( ignore_it )
473         // Seemly can't determine average for this section - so use last known good value (much better than just sticking in zero)
474         pts[current_chunk] = altitude1;
475       else
476         pts[current_chunk] = altitude1 + (altitude2-altitude1)*((dist_along_seg - (chunk_length/2))/current_seg_length);
477
478       current_chunk++;
479     } else {
480       /* finish current seg */
481       if ( current_seg_length ) {
482         gdouble altitude_at_dist_along_seg = altitude1 + (altitude2-altitude1)/(current_seg_length)*dist_along_seg;
483         current_dist = current_seg_length - dist_along_seg;
484         current_area_under_curve = current_dist*(altitude_at_dist_along_seg + altitude2)*0.5;
485       } else { current_dist = current_area_under_curve = 0; } /* should only happen if first current_seg_length == 0 */
486
487       /* get intervening segs */
488       iter = iter->next;
489       while ( iter && iter->next ) {
490         current_seg_length = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
491             &(VIK_TRACKPOINT(iter->next->data)->coord) );
492         altitude1 = VIK_TRACKPOINT(iter->data)->altitude;
493         altitude2 = VIK_TRACKPOINT(iter->next->data)->altitude;
494         ignore_it = VIK_TRACKPOINT(iter->next->data)->newsegment;
495
496         if ( chunk_length - current_dist >= current_seg_length ) {
497           current_dist += current_seg_length;
498           current_area_under_curve += current_seg_length * (altitude1+altitude2) * 0.5;
499           iter = iter->next;
500         } else {
501           break;
502         }
503       }
504
505       /* final seg */
506       dist_along_seg = chunk_length - current_dist;
507       if ( ignore_it || ( iter && !iter->next ) ) {
508         pts[current_chunk] = current_area_under_curve / current_dist;
509         if (!iter->next) {
510           int i;
511           for (i = current_chunk + 1; i < num_chunks; i++)
512             pts[i] = pts[current_chunk];
513           break;
514         }
515       } 
516       else {
517         current_area_under_curve += dist_along_seg * (altitude1 + (altitude2 - altitude1)*dist_along_seg/current_seg_length);
518         pts[current_chunk] = current_area_under_curve / chunk_length;
519       }
520
521       current_dist = 0;
522       current_chunk++;
523     }
524   }
525
526   return pts;
527 }
528
529
530 void vik_track_get_total_elevation_gain(const VikTrack *tr, gdouble *up, gdouble *down)
531 {
532   gdouble diff;
533   *up = *down = 0;
534   if ( tr->trackpoints && VIK_TRACKPOINT(tr->trackpoints->data)->altitude != VIK_DEFAULT_ALTITUDE )
535   {
536     GList *iter = tr->trackpoints->next;
537     while (iter)
538     {
539       diff = VIK_TRACKPOINT(iter->data)->altitude - VIK_TRACKPOINT(iter->prev->data)->altitude;
540       if ( diff > 0 )
541         *up += diff;
542       else
543         *down -= diff;
544       iter = iter->next;
545     }
546   } else
547     *up = *down = VIK_DEFAULT_ALTITUDE;
548 }
549
550 gdouble *vik_track_make_gradient_map ( const VikTrack *tr, guint16 num_chunks )
551 {
552   gdouble *pts;
553   gdouble *altitudes;
554   gdouble total_length, chunk_length, current_gradient;
555   gdouble altitude1, altitude2;
556   guint16 current_chunk;
557
558   g_assert ( num_chunks < 16000 );
559
560   total_length = vik_track_get_length_including_gaps ( tr );
561   chunk_length = total_length / num_chunks;
562
563   /* Zero chunk_length (eg, track of 2 tp with the same loc) will cause crash */
564   if (chunk_length <= 0) {
565     return NULL;
566   }
567
568   altitudes = vik_track_make_elevation_map (tr, num_chunks);
569   if (altitudes == NULL) {
570     return NULL;
571   }
572
573   current_gradient = 0.0;
574   pts = g_malloc ( sizeof(gdouble) * num_chunks );
575   for (current_chunk = 0; current_chunk < (num_chunks - 1); current_chunk++) {
576     altitude1 = altitudes[current_chunk];
577     altitude2 = altitudes[current_chunk + 1];
578     current_gradient = 100.0 * (altitude2 - altitude1) / chunk_length;
579
580     pts[current_chunk] = current_gradient;
581   }
582
583   pts[current_chunk] = current_gradient;
584
585   return pts;
586 }
587
588 /* by Alex Foobarian */
589 gdouble *vik_track_make_speed_map ( const VikTrack *tr, guint16 num_chunks )
590 {
591   gdouble *v, *s, *t;
592   gdouble duration, chunk_dur;
593   time_t t1, t2;
594   int i, pt_count, numpts, index;
595   GList *iter;
596
597   if ( ! tr->trackpoints )
598     return NULL;
599
600   g_assert ( num_chunks < 16000 );
601
602   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
603   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
604   duration = t2 - t1;
605
606   if ( !t1 || !t2 || !duration )
607     return NULL;
608
609   if (duration < 0) {
610     g_warning("negative duration: unsorted trackpoint timestamps?");
611     return NULL;
612   }
613   pt_count = vik_track_get_tp_count(tr);
614
615   v = g_malloc ( sizeof(gdouble) * num_chunks );
616   chunk_dur = duration / num_chunks;
617
618   s = g_malloc(sizeof(double) * pt_count);
619   t = g_malloc(sizeof(double) * pt_count);
620
621   iter = tr->trackpoints->next;
622   numpts = 0;
623   s[0] = 0;
624   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
625   numpts++;
626   while (iter) {
627     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
628     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
629     numpts++;
630     iter = iter->next;
631   }
632
633   /* In the following computation, we iterate through periods of time of duration chunk_dur.
634    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
635    */
636   index = 0; /* index of the current trackpoint. */
637   for (i = 0; i < num_chunks; i++) {
638     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
639      * find the first trackpoint outside the current interval, averaging the speeds between intermediate trackpoints.
640      */
641     if (t[0] + i*chunk_dur >= t[index]) {
642       gdouble acc_t = 0, acc_s = 0;
643       while (t[0] + i*chunk_dur >= t[index]) {
644         acc_s += (s[index+1]-s[index]);
645         acc_t += (t[index+1]-t[index]);
646         index++;
647       }
648       v[i] = acc_s/acc_t;
649     } 
650     else if (i) {
651       v[i] = v[i-1];
652     }
653     else {
654       v[i] = 0;
655     }
656   }
657   g_free(s);
658   g_free(t);
659   return v;
660 }
661
662 /**
663  * Make a distance/time map, heavily based on the vik_track_make_speed_map method
664  */
665 gdouble *vik_track_make_distance_map ( const VikTrack *tr, guint16 num_chunks )
666 {
667   gdouble *v, *s, *t;
668   gdouble duration, chunk_dur;
669   time_t t1, t2;
670   int i, pt_count, numpts, index;
671   GList *iter;
672
673   if ( ! tr->trackpoints )
674     return NULL;
675
676   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
677   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
678   duration = t2 - t1;
679
680   if ( !t1 || !t2 || !duration )
681     return NULL;
682
683   if (duration < 0) {
684     g_warning("negative duration: unsorted trackpoint timestamps?");
685     return NULL;
686   }
687   pt_count = vik_track_get_tp_count(tr);
688
689   v = g_malloc ( sizeof(gdouble) * num_chunks );
690   chunk_dur = duration / num_chunks;
691
692   s = g_malloc(sizeof(double) * pt_count);
693   t = g_malloc(sizeof(double) * pt_count);
694
695   iter = tr->trackpoints->next;
696   numpts = 0;
697   s[0] = 0;
698   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
699   numpts++;
700   while (iter) {
701     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
702     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
703     numpts++;
704     iter = iter->next;
705   }
706
707   /* In the following computation, we iterate through periods of time of duration chunk_dur.
708    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
709    */
710   index = 0; /* index of the current trackpoint. */
711   for (i = 0; i < num_chunks; i++) {
712     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
713      * find the first trackpoint outside the current interval, averaging the distance between intermediate trackpoints.
714      */
715     if (t[0] + i*chunk_dur >= t[index]) {
716       gdouble acc_s = 0; // No need for acc_t
717       while (t[0] + i*chunk_dur >= t[index]) {
718         acc_s += (s[index+1]-s[index]);
719         index++;
720       }
721       // The only bit that's really different from the speed map - just keep an accululative record distance
722       v[i] = i ? v[i-1]+acc_s : acc_s;
723     }
724     else if (i) {
725       v[i] = v[i-1];
726     }
727     else {
728       v[i] = 0;
729     }
730   }
731   g_free(s);
732   g_free(t);
733   return v;
734 }
735
736 /**
737  * This uses the 'time' based method to make the graph, (which is a simpler compared to the elevation/distance)
738  * This results in a slightly blocky graph when it does not have many trackpoints: <60
739  * NB Somehow the elevation/distance applies some kind of smoothing algorithm,
740  *   but I don't think any one understands it any more (I certainly don't ATM)
741  */
742 gdouble *vik_track_make_elevation_time_map ( const VikTrack *tr, guint16 num_chunks )
743 {
744   time_t t1, t2;
745   gdouble duration, chunk_dur;
746   GList *iter = tr->trackpoints;
747
748   if (!iter || !iter->next) /* zero- or one-point track */
749     return NULL;
750
751   /* test if there's anything worth calculating */
752   gboolean okay = FALSE;
753   while ( iter ) {
754     if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE ) {
755       okay = TRUE;
756       break;
757     }
758     iter = iter->next;
759   }
760   if ( ! okay )
761     return NULL;
762
763   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
764   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
765   duration = t2 - t1;
766
767   if ( !t1 || !t2 || !duration )
768     return NULL;
769
770   if (duration < 0) {
771     g_warning("negative duration: unsorted trackpoint timestamps?");
772     return NULL;
773   }
774   gint pt_count = vik_track_get_tp_count(tr);
775
776   // Reset iterator back to the beginning
777   iter = tr->trackpoints;
778
779   gdouble *pts = g_malloc ( sizeof(gdouble) * num_chunks ); // The return altitude values
780   gdouble *s = g_malloc(sizeof(double) * pt_count); // calculation altitudes
781   gdouble *t = g_malloc(sizeof(double) * pt_count); // calculation times
782
783   chunk_dur = duration / num_chunks;
784
785   s[0] = VIK_TRACKPOINT(iter->data)->altitude;
786   t[0] = VIK_TRACKPOINT(iter->data)->timestamp;
787   iter = tr->trackpoints->next;
788   gint numpts = 1;
789   while (iter) {
790     s[numpts] = VIK_TRACKPOINT(iter->data)->altitude;
791     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
792     numpts++;
793     iter = iter->next;
794   }
795
796  /* In the following computation, we iterate through periods of time of duration chunk_dur.
797    * The first period begins at the beginning of the track.  The last period ends at the end of the track.
798    */
799   gint index = 0; /* index of the current trackpoint. */
800   gint i;
801   for (i = 0; i < num_chunks; i++) {
802     /* we are now covering the interval from t[0] + i*chunk_dur to t[0] + (i+1)*chunk_dur.
803      * find the first trackpoint outside the current interval, averaging the heights between intermediate trackpoints.
804      */
805     if (t[0] + i*chunk_dur >= t[index]) {
806       gdouble acc_s = s[index]; // initialise to first point
807       while (t[0] + i*chunk_dur >= t[index]) {
808         acc_s += (s[index+1]-s[index]);
809         index++;
810       }
811       pts[i] = acc_s;
812     }
813     else if (i) {
814       pts[i] = pts[i-1];
815     }
816     else {
817       pts[i] = 0;
818     }
819   }
820   g_free(s);
821   g_free(t);
822
823   return pts;
824 }
825
826 /**
827  * Make a speed/distance map
828  */
829 gdouble *vik_track_make_speed_dist_map ( const VikTrack *tr, guint16 num_chunks )
830 {
831   gdouble *v, *s, *t;
832   time_t t1, t2;
833   gint i, pt_count, numpts, index;
834   GList *iter;
835   gdouble duration, total_length, chunk_length;
836
837   if ( ! tr->trackpoints )
838     return NULL;
839
840   t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
841   t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
842   duration = t2 - t1;
843
844   if ( !t1 || !t2 || !duration )
845     return NULL;
846
847   if (duration < 0) {
848     g_warning("negative duration: unsorted trackpoint timestamps?");
849     return NULL;
850   }
851
852   total_length = vik_track_get_length_including_gaps ( tr );
853   chunk_length = total_length / num_chunks;
854   pt_count = vik_track_get_tp_count(tr);
855
856   if (chunk_length <= 0) {
857     return NULL;
858   }
859
860   v = g_malloc ( sizeof(gdouble) * num_chunks );
861   s = g_malloc ( sizeof(double) * pt_count );
862   t = g_malloc ( sizeof(double) * pt_count );
863
864   // No special handling of segments ATM...
865   iter = tr->trackpoints->next;
866   numpts = 0;
867   s[0] = 0;
868   t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
869   numpts++;
870   while (iter) {
871     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
872     t[numpts] = VIK_TRACKPOINT(iter->data)->timestamp;
873     numpts++;
874     iter = iter->next;
875   }
876
877   // Iterate through a portion of the track to get an average speed for that part
878   // This will essentially interpolate between segments, which I think is right given the usage of 'get_length_including_gaps'
879   index = 0; /* index of the current trackpoint. */
880   for (i = 0; i < num_chunks; i++) {
881     // Similar to the make_speed_map, but instead of using a time chunk, use a distance chunk
882     if (s[0] + i*chunk_length >= s[index]) {
883       gdouble acc_t = 0, acc_s = 0;
884       while (s[0] + i*chunk_length >= s[index]) {
885         acc_s += (s[index+1]-s[index]);
886         acc_t += (t[index+1]-t[index]);
887         index++;
888       }
889       v[i] = acc_s/acc_t;
890     }
891     else if (i) {
892       v[i] = v[i-1];
893     }
894     else {
895       v[i] = 0;
896     }
897   }
898   g_free(s);
899   g_free(t);
900   return v;
901 }
902
903 /* by Alex Foobarian */
904 VikTrackpoint *vik_track_get_closest_tp_by_percentage_dist ( VikTrack *tr, gdouble reldist, gdouble *meters_from_start )
905 {
906   gdouble dist = vik_track_get_length_including_gaps(tr) * reldist;
907   gdouble current_dist = 0.0;
908   gdouble current_inc = 0.0;
909   if ( tr->trackpoints )
910   {
911     GList *iter = tr->trackpoints->next;
912     GList *last_iter = NULL;
913     gdouble last_dist = 0.0;
914     while (iter)
915     {
916       current_inc = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
917                                      &(VIK_TRACKPOINT(iter->prev->data)->coord) );
918       last_dist = current_dist;
919       current_dist += current_inc;
920       if ( current_dist >= dist )
921         break;
922       last_iter = iter;
923       iter = iter->next;
924     }
925     if (!iter) { /* passing the end the track */
926       if (last_iter) {
927         if (meters_from_start)
928           *meters_from_start = last_dist;
929         return(VIK_TRACKPOINT(last_iter->data));
930       }
931       else
932         return NULL;
933     }
934     /* we've gone past the dist already, was prev trackpoint closer? */
935     /* should do a vik_coord_average_weighted() thingy. */
936     if ( iter->prev && abs(current_dist-current_inc-dist) < abs(current_dist-dist) ) {
937       if (meters_from_start)
938         *meters_from_start = last_dist;
939       iter = iter->prev;
940     }
941     else
942       if (meters_from_start)
943         *meters_from_start = current_dist;
944
945     return VIK_TRACKPOINT(iter->data);
946
947   }
948   return NULL;
949 }
950
951 VikTrackpoint *vik_track_get_closest_tp_by_percentage_time ( VikTrack *tr, gdouble reltime, time_t *seconds_from_start )
952 {
953   time_t t_pos, t_start, t_end, t_total;
954   t_start = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
955   t_end = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
956   t_total = t_end - t_start;
957
958   t_pos = t_start + t_total * reltime;
959
960   if ( !tr->trackpoints )
961     return NULL;
962
963   GList *iter = tr->trackpoints;
964
965   while (iter) {
966     if (VIK_TRACKPOINT(iter->data)->timestamp == t_pos)
967       break;
968     if (VIK_TRACKPOINT(iter->data)->timestamp > t_pos) {
969       if (iter->prev == NULL)  /* first trackpoint */
970         break;
971       time_t t_before = t_pos - VIK_TRACKPOINT(iter->prev)->timestamp;
972       time_t t_after = VIK_TRACKPOINT(iter->data)->timestamp - t_pos;
973       if (t_before <= t_after)
974         iter = iter->prev;
975       break;
976     }
977     else if ((iter->next == NULL) && (t_pos < (VIK_TRACKPOINT(iter->data)->timestamp + 3))) /* last trackpoint: accommodate for round-off */
978       break;
979     iter = iter->next;
980   }
981
982   if (!iter)
983     return NULL;
984   if (seconds_from_start)
985     *seconds_from_start = VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
986   return VIK_TRACKPOINT(iter->data);
987 }
988
989 VikTrackpoint* vik_track_get_tp_by_max_speed ( const VikTrack *tr )
990 {
991   gdouble maxspeed = 0.0, speed = 0.0;
992
993   if ( !tr->trackpoints )
994     return NULL;
995
996   GList *iter = tr->trackpoints;
997   VikTrackpoint *max_speed_tp = NULL;
998
999   while (iter) {
1000     if (iter->prev) {
1001       if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
1002            VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
1003            (! VIK_TRACKPOINT(iter->data)->newsegment) ) {
1004         speed =  vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) )
1005           / ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
1006         if ( speed > maxspeed ) {
1007           maxspeed = speed;
1008           max_speed_tp = VIK_TRACKPOINT(iter->data);
1009         }
1010       }
1011     }
1012     iter = iter->next;
1013   }
1014   
1015   if (!max_speed_tp)
1016     return NULL;
1017
1018   return max_speed_tp;
1019 }
1020
1021 VikTrackpoint* vik_track_get_tp_by_max_alt ( const VikTrack *tr )
1022 {
1023   gdouble maxalt = -5000.0;
1024   if ( !tr->trackpoints )
1025     return NULL;
1026
1027   GList *iter = tr->trackpoints;
1028   VikTrackpoint *max_alt_tp = NULL;
1029
1030   while (iter) {
1031     if ( VIK_TRACKPOINT(iter->data)->altitude > maxalt ) {
1032       maxalt = VIK_TRACKPOINT(iter->data)->altitude;
1033       max_alt_tp = VIK_TRACKPOINT(iter->data);
1034     }
1035     iter = iter->next;
1036   }
1037
1038   if (!max_alt_tp)
1039     return NULL;
1040
1041   return max_alt_tp;
1042 }
1043
1044 VikTrackpoint* vik_track_get_tp_by_min_alt ( const VikTrack *tr )
1045 {
1046   gdouble minalt = 25000.0;
1047   if ( !tr->trackpoints )
1048     return NULL;
1049
1050   GList *iter = tr->trackpoints;
1051   VikTrackpoint *min_alt_tp = NULL;
1052
1053   while (iter) {
1054     if ( VIK_TRACKPOINT(iter->data)->altitude < minalt ) {
1055       minalt = VIK_TRACKPOINT(iter->data)->altitude;
1056       min_alt_tp = VIK_TRACKPOINT(iter->data);
1057     }
1058     iter = iter->next;
1059   }
1060
1061   if (!min_alt_tp)
1062     return NULL;
1063
1064   return min_alt_tp;
1065 }
1066
1067 gboolean vik_track_get_minmax_alt ( const VikTrack *tr, gdouble *min_alt, gdouble *max_alt )
1068 {
1069   *min_alt = 25000;
1070   *max_alt = -5000;
1071   if ( tr && tr->trackpoints && tr->trackpoints->data && (VIK_TRACKPOINT(tr->trackpoints->data)->altitude != VIK_DEFAULT_ALTITUDE) ) {
1072     GList *iter = tr->trackpoints->next;
1073     gdouble tmp_alt;
1074     while (iter)
1075     {
1076       tmp_alt = VIK_TRACKPOINT(iter->data)->altitude;
1077       if ( tmp_alt > *max_alt )
1078         *max_alt = tmp_alt;
1079       if ( tmp_alt < *min_alt )
1080         *min_alt = tmp_alt;
1081       iter = iter->next;
1082     }
1083     return TRUE;
1084   }
1085   return FALSE;
1086 }
1087
1088 void vik_track_marshall ( VikTrack *tr, guint8 **data, guint *datalen)
1089 {
1090   GList *tps;
1091   GByteArray *b = g_byte_array_new();
1092   guint len;
1093   guint intp, ntp;
1094
1095   g_byte_array_append(b, (guint8 *)tr, sizeof(*tr));
1096
1097   /* we'll fill out number of trackpoints later */
1098   intp = b->len;
1099   g_byte_array_append(b, (guint8 *)&len, sizeof(len));
1100
1101   tps = tr->trackpoints;
1102   ntp = 0;
1103   while (tps) {
1104     g_byte_array_append(b, (guint8 *)tps->data, sizeof(VikTrackpoint));
1105     tps = tps->next;
1106     ntp++;
1107   }
1108   *(guint *)(b->data + intp) = ntp;
1109
1110   len = (tr->name) ? strlen(tr->name)+1 : 0;
1111   g_byte_array_append(b, (guint8 *)&len, sizeof(len));
1112   if (tr->name) g_byte_array_append(b, (guint8 *)tr->name, len);
1113
1114   len = (tr->comment) ? strlen(tr->comment)+1 : 0; 
1115   g_byte_array_append(b, (guint8 *)&len, sizeof(len)); 
1116   if (tr->comment) g_byte_array_append(b, (guint8 *)tr->comment, len);
1117
1118   *data = b->data;
1119   *datalen = b->len;
1120   g_byte_array_free(b, FALSE);
1121 }
1122
1123 VikTrack *vik_track_unmarshall (guint8 *data, guint datalen)
1124 {
1125   guint len;
1126   VikTrack *new_tr = vik_track_new();
1127   VikTrackpoint *new_tp;
1128   guint ntp;
1129   gint i;
1130
1131   /* only the visibility is needed */
1132   new_tr->visible = ((VikTrack *)data)->visible;
1133   data += sizeof(*new_tr);
1134
1135   ntp = *(guint *)data;
1136   data += sizeof(ntp);
1137
1138   for (i=0; i<ntp; i++) {
1139     new_tp = vik_trackpoint_new();
1140     memcpy(new_tp, data, sizeof(*new_tp));
1141     data += sizeof(*new_tp);
1142     new_tr->trackpoints = g_list_append(new_tr->trackpoints, new_tp);
1143   }
1144
1145   len = *(guint *)data;
1146   data += sizeof(len);
1147   if (len) {
1148     new_tr->name = g_strdup((gchar *)data);
1149   }
1150   data += len;
1151
1152   len = *(guint *)data;
1153   data += sizeof(len);
1154   if (len) {
1155     new_tr->comment = g_strdup((gchar *)data);
1156   }
1157   return new_tr;
1158 }
1159
1160 void vik_track_apply_dem_data ( VikTrack *tr )
1161 {
1162   GList *tp_iter;
1163   gint16 elev;
1164   tp_iter = tr->trackpoints;
1165   while ( tp_iter ) {
1166     /* TODO: of the 4 possible choices we have for choosing an elevation
1167      * (trackpoint in between samples), choose the one with the least elevation change
1168      * as the last */
1169     elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(tp_iter->data)->coord), VIK_DEM_INTERPOL_BEST );
1170     if ( elev != VIK_DEM_INVALID_ELEVATION )
1171       VIK_TRACKPOINT(tp_iter->data)->altitude = elev;
1172     tp_iter = tp_iter->next;
1173   }
1174 }
1175
1176 /*
1177  * Apply DEM data (if available) - to only the last trackpoint
1178  */
1179 void vik_track_apply_dem_data_last_trackpoint ( VikTrack *tr )
1180 {
1181   gint16 elev;
1182   if ( tr->trackpoints ) {
1183     /* As in vik_track_apply_dem_data above - use 'best' interpolation method */
1184     elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->coord), VIK_DEM_INTERPOL_BEST );
1185     if ( elev != VIK_DEM_INVALID_ELEVATION )
1186       VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->altitude = elev;
1187   }
1188 }
1189
1190 /* appends t2 to t1, leaving t2 with no trackpoints */
1191 void vik_track_steal_and_append_trackpoints ( VikTrack *t1, VikTrack *t2 )
1192 {
1193   if ( t1->trackpoints ) {
1194     GList *tpiter = t1->trackpoints;
1195     while ( tpiter->next )
1196       tpiter = tpiter->next;
1197     tpiter->next = t2->trackpoints;
1198     t2->trackpoints->prev = tpiter;
1199   } else
1200     t1->trackpoints = t2->trackpoints;
1201   t2->trackpoints = NULL;
1202 }
1203
1204 /* starting at the end, looks backwards for the last "double point", a duplicate trackpoint.
1205  * If there is no double point, deletes all the trackpoints.
1206  * Returns the new end of the track (or the start if there are no double points)
1207  */
1208 VikCoord *vik_track_cut_back_to_double_point ( VikTrack *tr )
1209 {
1210   GList *iter = tr->trackpoints;
1211   VikCoord *rv;
1212
1213   if ( !iter )
1214     return NULL;
1215   while ( iter->next )
1216     iter = iter->next;
1217
1218
1219   while ( iter->prev ) {
1220     if ( vik_coord_equals((VikCoord *)iter->data, (VikCoord *)iter->prev->data) ) {
1221       GList *prev = iter->prev;
1222
1223       rv = g_malloc(sizeof(VikCoord));
1224       *rv = *((VikCoord *) iter->data);
1225
1226       /* truncate trackpoint list */
1227       iter->prev = NULL; /* pretend it's the end */
1228       g_list_foreach ( iter, (GFunc) g_free, NULL );
1229       g_list_free( iter );
1230
1231       prev->next = NULL;
1232
1233       return rv;
1234     }
1235     iter = iter->prev;
1236   }
1237
1238   /* no double point found! */
1239   rv = g_malloc(sizeof(VikCoord));
1240   *rv = *((VikCoord *) tr->trackpoints->data);
1241   g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
1242   g_list_free( tr->trackpoints );
1243   tr->trackpoints = NULL;
1244   return rv;
1245 }
1246