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