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