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