]> git.street.me.uk Git - andy/viking.git/blobdiff - src/viktrack.c
Create and use new menu level 'Transform' for some track/route operations.
[andy/viking.git] / src / viktrack.c
index 2a02b1e48cc6b39ebba64fdfcc3d5f861349090b..937e3fd045e9a3b2f75ac290483386f0b8cc056b 100644 (file)
@@ -2,6 +2,7 @@
  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
  *
  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
+ * Copyright (c) 2012, Rob Norris <rw_norris@hotmail.com>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -53,6 +54,14 @@ void vik_track_set_comment_no_copy(VikTrack *tr, gchar *comment)
 }
 
 
+void vik_track_set_name(VikTrack *tr, const gchar *name)
+{
+  if ( tr->name )
+    g_free ( tr->name );
+
+  tr->name = g_strdup(name);
+}
+
 void vik_track_set_comment(VikTrack *tr, const gchar *comment)
 {
   if ( tr->comment )
@@ -64,6 +73,17 @@ void vik_track_set_comment(VikTrack *tr, const gchar *comment)
     tr->comment = NULL;
 }
 
+void vik_track_set_description(VikTrack *tr, const gchar *description)
+{
+  if ( tr->description )
+    g_free ( tr->description );
+
+  if ( description && description[0] != '\0' )
+    tr->description = g_strdup(description);
+  else
+    tr->description = NULL;
+}
+
 void vik_track_ref(VikTrack *tr)
 {
   tr->ref_count++;
@@ -85,8 +105,12 @@ void vik_track_free(VikTrack *tr)
   if ( tr->ref_count-- > 1 )
     return;
 
+  if ( tr->name )
+    g_free ( tr->name );
   if ( tr->comment )
     g_free ( tr->comment );
+  if ( tr->description )
+    g_free ( tr->description );
   g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
   g_list_free( tr->trackpoints );
   if (tr->property_dialog)
@@ -95,21 +119,40 @@ void vik_track_free(VikTrack *tr)
   g_free ( tr );
 }
 
-VikTrack *vik_track_copy ( const VikTrack *tr )
+/**
+ * vik_track_copy:
+ * @tr: The Track to copy
+ * @copy_points: Whether to copy the track points or not
+ *
+ * Normally for copying the track it's best to copy all the trackpoints
+ * However for some operations such as splitting tracks the trackpoints will be managed separately, so no need to copy them.
+ *
+ * Returns: the copied VikTrack
+ */
+VikTrack *vik_track_copy ( const VikTrack *tr, gboolean copy_points )
 {
   VikTrack *new_tr = vik_track_new();
   VikTrackpoint *new_tp;
   GList *tp_iter = tr->trackpoints;
   new_tr->visible = tr->visible;
+  new_tr->is_route = tr->is_route;
+  new_tr->has_color = tr->has_color;
+  new_tr->color = tr->color;
+  new_tr->bbox = tr->bbox;
   new_tr->trackpoints = NULL;
-  while ( tp_iter )
+  if ( copy_points )
   {
-    new_tp = g_malloc ( sizeof ( VikTrackpoint ) );
-    *new_tp = *((VikTrackpoint *)(tp_iter->data));
-    new_tr->trackpoints = g_list_append ( new_tr->trackpoints, new_tp );
-    tp_iter = tp_iter->next;
+    while ( tp_iter )
+    {
+      new_tp = g_malloc ( sizeof ( VikTrackpoint ) );
+      *new_tp = *((VikTrackpoint *)(tp_iter->data));
+      new_tr->trackpoints = g_list_append ( new_tr->trackpoints, new_tp );
+      tp_iter = tp_iter->next;
+    }
   }
+  vik_track_set_name(new_tr,tr->name);
   vik_track_set_comment(new_tr,tr->comment);
+  vik_track_set_description(new_tr,tr->description);
   return new_tr;
 }
 
@@ -137,6 +180,48 @@ VikTrackpoint *vik_trackpoint_copy(VikTrackpoint *tp)
   return rv;
 }
 
+/**
+ * track_recalculate_bounds_last_tp:
+ * @trk:   The track to consider the recalculation on
+ *
+ * A faster bounds check, since it only considers the last track point
+ */
+static void track_recalculate_bounds_last_tp ( VikTrack *trk )
+{
+  GList *tpl = g_list_last ( trk->trackpoints );
+
+  if ( tpl ) {
+    struct LatLon ll;
+    // See if this trackpoint increases the track bounds and update if so
+    vik_coord_to_latlon ( &(VIK_TRACKPOINT(tpl->data)->coord), &ll );
+    if ( ll.lat > trk->bbox.north )
+      trk->bbox.north = ll.lat;
+    if ( ll.lon < trk->bbox.west )
+      trk->bbox.west = ll.lon;
+    if ( ll.lat < trk->bbox.south )
+      trk->bbox.south = ll.lat;
+    if ( ll.lon > trk->bbox.east )
+      trk->bbox.east = ll.lon;
+  }
+}
+
+/**
+ * vik_track_add_trackpoint:
+ * @tr:          The track to which the trackpoint will be added
+ * @tp:          The trackpoint to add
+ * @recalculate: Whether to perform any associated properties recalculations
+ *               Generally one should avoid recalculation via this method if adding lots of points
+ *               (But ensure calculate_bounds() is called after adding all points!!)
+ *
+ * The trackpoint is added to the end of the existing trackpoint list
+ */
+void vik_track_add_trackpoint ( VikTrack *tr, VikTrackpoint *tp, gboolean recalculate )
+{
+  tr->trackpoints = g_list_append ( tr->trackpoints, tp );
+  if ( recalculate )
+    track_recalculate_bounds_last_tp ( tr );
+}
+
 gdouble vik_track_get_length(const VikTrack *tr)
 {
   gdouble len = 0.0;
@@ -171,18 +256,29 @@ gdouble vik_track_get_length_including_gaps(const VikTrack *tr)
 }
 
 gulong vik_track_get_tp_count(const VikTrack *tr)
+{
+  return g_list_length(tr->trackpoints);
+}
+
+gulong vik_track_get_dup_point_count ( const VikTrack *tr )
 {
   gulong num = 0;
   GList *iter = tr->trackpoints;
   while ( iter )
   {
-    num++;
+    if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
+                       &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
+      num++;
     iter = iter->next;
   }
   return num;
 }
 
-gulong vik_track_get_dup_point_count ( const VikTrack *tr )
+/*
+ * Deletes adjacent points that have the same position
+ * Returns the number of points that were deleted
+ */
+gulong vik_track_remove_dup_points ( VikTrack *tr )
 {
   gulong num = 0;
   GList *iter = tr->trackpoints;
@@ -190,26 +286,101 @@ gulong vik_track_get_dup_point_count ( const VikTrack *tr )
   {
     if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
                        &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
+    {
+      num++;
+      // Maintain track segments
+      if ( VIK_TRACKPOINT(iter->next->data)->newsegment && (iter->next)->next )
+        VIK_TRACKPOINT(((iter->next)->next)->data)->newsegment = TRUE;
+
+      vik_trackpoint_free ( iter->next->data );
+      tr->trackpoints = g_list_delete_link ( tr->trackpoints, iter->next );
+    }
+    else
+      iter = iter->next;
+  }
+
+  // NB isn't really be necessary as removing duplicate points shouldn't alter the bounds!
+  vik_track_calculate_bounds ( tr );
+
+  return num;
+}
+
+/*
+ * Get a count of trackpoints with the same defined timestamp
+ * Note is using timestamps with a resolution with 1 second
+ */
+gulong vik_track_get_same_time_point_count ( const VikTrack *tr )
+{
+  gulong num = 0;
+  GList *iter = tr->trackpoints;
+  while ( iter ) {
+    if ( iter->next &&
+        ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
+           VIK_TRACKPOINT(iter->next->data)->has_timestamp ) &&
+         ( VIK_TRACKPOINT(iter->data)->timestamp ==
+           VIK_TRACKPOINT(iter->next->data)->timestamp) )
       num++;
     iter = iter->next;
   }
   return num;
 }
 
-void vik_track_remove_dup_points ( VikTrack *tr )
+/*
+ * Deletes adjacent points that have the same defined timestamp
+ * Returns the number of points that were deleted
+ */
+gulong vik_track_remove_same_time_points ( VikTrack *tr )
 {
+  gulong num = 0;
   GList *iter = tr->trackpoints;
-  while ( iter )
-  {
-    if ( iter->next && vik_coord_equals ( &(VIK_TRACKPOINT(iter->data)->coord),
-                       &(VIK_TRACKPOINT(iter->next->data)->coord) ) )
-    {
-      g_free ( iter->next->data );
+  while ( iter ) {
+    if ( iter->next &&
+        ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
+           VIK_TRACKPOINT(iter->next->data)->has_timestamp ) &&
+         ( VIK_TRACKPOINT(iter->data)->timestamp ==
+           VIK_TRACKPOINT(iter->next->data)->timestamp) ) {
+
+      num++;
+      
+      // Maintain track segments
+      if ( VIK_TRACKPOINT(iter->next->data)->newsegment && (iter->next)->next )
+        VIK_TRACKPOINT(((iter->next)->next)->data)->newsegment = TRUE;
+
+      vik_trackpoint_free ( iter->next->data );
       tr->trackpoints = g_list_delete_link ( tr->trackpoints, iter->next );
     }
     else
       iter = iter->next;
   }
+
+  vik_track_calculate_bounds ( tr );
+
+  return num;
+}
+
+/*
+ * Deletes all 'extra' trackpoint information
+ *  such as time stamps, speed, course etc...
+ */
+void vik_track_to_routepoints ( VikTrack *tr )
+{
+  GList *iter = tr->trackpoints;
+  while ( iter ) {
+
+    // c.f. with vik_trackpoint_new()
+
+    VIK_TRACKPOINT(iter->data)->has_timestamp = FALSE;
+    VIK_TRACKPOINT(iter->data)->timestamp = 0;
+    VIK_TRACKPOINT(iter->data)->speed = NAN;
+    VIK_TRACKPOINT(iter->data)->course = NAN;
+    VIK_TRACKPOINT(iter->data)->hdop = VIK_DEFAULT_DOP;
+    VIK_TRACKPOINT(iter->data)->vdop = VIK_DEFAULT_DOP;
+    VIK_TRACKPOINT(iter->data)->pdop = VIK_DEFAULT_DOP;
+    VIK_TRACKPOINT(iter->data)->nsats = 0;
+    VIK_TRACKPOINT(iter->data)->fix_mode = VIK_GPS_MODE_NOT_SEEN;
+
+    iter = iter->next;
+  }
 }
 
 guint vik_track_get_segment_count(const VikTrack *tr)
@@ -241,7 +412,7 @@ VikTrack **vik_track_split_into_segments(VikTrack *t, guint *ret_len)
   }
 
   rv = g_malloc ( segs * sizeof(VikTrack *) );
-  tr = vik_track_copy ( t );
+  tr = vik_track_copy ( t, TRUE );
   rv[0] = tr;
   iter = tr->trackpoints;
 
@@ -252,11 +423,11 @@ VikTrack **vik_track_split_into_segments(VikTrack *t, guint *ret_len)
     {
       iter->prev->next = NULL;
       iter->prev = NULL;
-      rv[i] = vik_track_new();
-      if ( tr->comment )
-        vik_track_set_comment ( rv[i], tr->comment );
-      rv[i]->visible = tr->visible;
+      rv[i] = vik_track_copy ( tr, FALSE );
       rv[i]->trackpoints = iter;
+
+      vik_track_calculate_bounds ( rv[i] );
+
       i++;
     }
   }
@@ -264,13 +435,39 @@ VikTrack **vik_track_split_into_segments(VikTrack *t, guint *ret_len)
   return rv;
 }
 
+/*
+ * Simply remove any subsequent segment markers in a track to form one continuous track
+ * Return the number of segments merged
+ */
+guint vik_track_merge_segments(VikTrack *tr)
+{
+  guint num = 0;
+  GList *iter = tr->trackpoints;
+  if ( !iter )
+    return num;
+
+  // Always skip the first point as this should be the first segment
+  iter = iter->next;
+
+  while ( (iter = iter->next) )
+  {
+    if ( VIK_TRACKPOINT(iter->data)->newsegment ) {
+      VIK_TRACKPOINT(iter->data)->newsegment = FALSE;
+      num++;
+    }
+  }
+  return num;
+}
+
 void vik_track_reverse ( VikTrack *tr )
 {
-  GList *iter;
+  if ( ! tr->trackpoints )
+    return;
+
   tr->trackpoints = g_list_reverse(tr->trackpoints);
 
   /* fix 'newsegment' */
-  iter = g_list_last ( tr->trackpoints );
+  GList *iter = g_list_last ( tr->trackpoints );
   while ( iter )
   {
     if ( ! iter->next ) /* last segment, was first, cancel newsegment. */
@@ -309,6 +506,42 @@ gdouble vik_track_get_average_speed(const VikTrack *tr)
   return (time == 0) ? 0 : ABS(len/time);
 }
 
+/**
+ * Based on a simple average speed, but with a twist - to give a moving average.
+ *  . GPSs often report a moving average in their statistics output
+ *  . bicycle speedos often don't factor in time when stopped - hence reporting a moving average for speed
+ *
+ * Often GPS track will record every second but not when stationary
+ * This method doesn't use samples that differ over the specified time limit - effectively skipping that time chunk from the total time
+ *
+ * Suggest to use 60 seconds as the stop length (as the default used in the TrackWaypoint draw stops factor)
+ */
+gdouble vik_track_get_average_speed_moving (const VikTrack *tr, int stop_length_seconds)
+{
+  gdouble len = 0.0;
+  guint32 time = 0;
+  if ( tr->trackpoints )
+  {
+    GList *iter = tr->trackpoints->next;
+    while (iter)
+    {
+      if ( VIK_TRACKPOINT(iter->data)->has_timestamp &&
+          VIK_TRACKPOINT(iter->prev->data)->has_timestamp &&
+          (! VIK_TRACKPOINT(iter->data)->newsegment) )
+      {
+       if ( ( VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp ) < stop_length_seconds ) {
+         len += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
+                                 &(VIK_TRACKPOINT(iter->prev->data)->coord) );
+       
+         time += ABS(VIK_TRACKPOINT(iter->data)->timestamp - VIK_TRACKPOINT(iter->prev->data)->timestamp);
+       }
+      }
+      iter = iter->next;
+    }
+  }
+  return (time == 0) ? 0 : ABS(len/time);
+}
+
 gdouble vik_track_get_max_speed(const VikTrack *tr)
 {
   gdouble maxspeed = 0.0, speed = 0.0;
@@ -361,7 +594,12 @@ gdouble *vik_track_make_elevation_map ( const VikTrack *tr, guint16 num_chunks )
     gboolean okay = FALSE;
     while ( iter )
     {
-      if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE ) {
+      // Sometimes a GPS device (or indeed any random file) can have stupid numbers for elevations
+      // Since when is 9.9999e+24 a valid elevation!!
+      // 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)
+      // Some protection against trying to work with crazily massive numbers (otherwise get SIGFPE, Arithmetic exception)
+      if ( VIK_TRACKPOINT(iter->data)->altitude != VIK_DEFAULT_ALTITUDE &&
+          VIK_TRACKPOINT(iter->data)->altitude < 1E9 ) {
         okay = TRUE; break;
       }
       iter = iter->next;
@@ -412,7 +650,8 @@ gdouble *vik_track_make_elevation_map ( const VikTrack *tr, guint16 num_chunks )
        **/
 
       if ( ignore_it )
-        pts[current_chunk] = VIK_DEFAULT_ALTITUDE;
+       // Seemly can't determine average for this section - so use last known good value (much better than just sticking in zero)
+        pts[current_chunk] = altitude1;
       else
         pts[current_chunk] = altitude1 + (altitude2-altitude1)*((dist_along_seg - (chunk_length/2))/current_seg_length);
 
@@ -445,7 +684,7 @@ gdouble *vik_track_make_elevation_map ( const VikTrack *tr, guint16 num_chunks )
 
       /* final seg */
       dist_along_seg = chunk_length - current_dist;
-      if ( ignore_it || !iter->next ) {
+      if ( ignore_it || ( iter && !iter->next ) ) {
         pts[current_chunk] = current_area_under_curve / current_dist;
         if (!iter->next) {
           int i;
@@ -488,6 +727,45 @@ void vik_track_get_total_elevation_gain(const VikTrack *tr, gdouble *up, gdouble
     *up = *down = VIK_DEFAULT_ALTITUDE;
 }
 
+gdouble *vik_track_make_gradient_map ( const VikTrack *tr, guint16 num_chunks )
+{
+  gdouble *pts;
+  gdouble *altitudes;
+  gdouble total_length, chunk_length, current_gradient;
+  gdouble altitude1, altitude2;
+  guint16 current_chunk;
+
+  g_assert ( num_chunks < 16000 );
+
+  total_length = vik_track_get_length_including_gaps ( tr );
+  chunk_length = total_length / num_chunks;
+
+  /* Zero chunk_length (eg, track of 2 tp with the same loc) will cause crash */
+  if (chunk_length <= 0) {
+    return NULL;
+  }
+
+  altitudes = vik_track_make_elevation_map (tr, num_chunks);
+  if (altitudes == NULL) {
+    return NULL;
+  }
+
+  current_gradient = 0.0;
+  pts = g_malloc ( sizeof(gdouble) * num_chunks );
+  for (current_chunk = 0; current_chunk < (num_chunks - 1); current_chunk++) {
+    altitude1 = altitudes[current_chunk];
+    altitude2 = altitudes[current_chunk + 1];
+    current_gradient = 100.0 * (altitude2 - altitude1) / chunk_length;
+
+    pts[current_chunk] = current_gradient;
+  }
+
+  pts[current_chunk] = current_gradient;
+
+  g_free ( altitudes );
+
+  return pts;
+}
 
 /* by Alex Foobarian */
 gdouble *vik_track_make_speed_map ( const VikTrack *tr, guint16 num_chunks )
@@ -525,7 +803,7 @@ gdouble *vik_track_make_speed_map ( const VikTrack *tr, guint16 num_chunks )
   iter = tr->trackpoints->next;
   numpts = 0;
   s[0] = 0;
-  t[0] = VIK_TRACKPOINT(iter->prev->data)->timestamp;
+  t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
   numpts++;
   while (iter) {
     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
@@ -599,7 +877,7 @@ gdouble *vik_track_make_distance_map ( const VikTrack *tr, guint16 num_chunks )
   iter = tr->trackpoints->next;
   numpts = 0;
   s[0] = 0;
-  t[0] = VIK_TRACKPOINT(iter->prev->data)->timestamp;
+  t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
   numpts++;
   while (iter) {
     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
@@ -769,7 +1047,7 @@ gdouble *vik_track_make_speed_dist_map ( const VikTrack *tr, guint16 num_chunks
   iter = tr->trackpoints->next;
   numpts = 0;
   s[0] = 0;
-  t[0] = VIK_TRACKPOINT(iter->prev->data)->timestamp;
+  t[0] = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
   numpts++;
   while (iter) {
     s[numpts] = s[numpts-1] + vik_coord_diff ( &(VIK_TRACKPOINT(iter->prev->data)->coord), &(VIK_TRACKPOINT(iter->data)->coord) );
@@ -872,7 +1150,7 @@ VikTrackpoint *vik_track_get_closest_tp_by_percentage_time ( VikTrack *tr, gdoub
     if (VIK_TRACKPOINT(iter->data)->timestamp > t_pos) {
       if (iter->prev == NULL)  /* first trackpoint */
         break;
-      time_t t_before = t_pos - VIK_TRACKPOINT(iter->prev)->timestamp;
+      time_t t_before = t_pos - VIK_TRACKPOINT(iter->prev->data)->timestamp;
       time_t t_after = VIK_TRACKPOINT(iter->data)->timestamp - t_pos;
       if (t_before <= t_after)
         iter = iter->prev;
@@ -1011,15 +1289,25 @@ void vik_track_marshall ( VikTrack *tr, guint8 **data, guint *datalen)
   }
   *(guint *)(b->data + intp) = ntp;
 
-  len = (tr->comment) ? strlen(tr->comment)+1 : 0; 
-  g_byte_array_append(b, (guint8 *)&len, sizeof(len)); 
-  if (tr->comment) g_byte_array_append(b, (guint8 *)tr->comment, len);
+  // This allocates space for variant sized strings
+  //  and copies that amount of data from the track to byte array
+#define vtm_append(s) \
+  len = (s) ? strlen(s)+1 : 0; \
+  g_byte_array_append(b, (guint8 *)&len, sizeof(len)); \
+  if (s) g_byte_array_append(b, (guint8 *)s, len);
+
+  vtm_append(tr->name);
+  vtm_append(tr->comment);
+  vtm_append(tr->description);
 
   *data = b->data;
   *datalen = b->len;
   g_byte_array_free(b, FALSE);
 }
 
+/*
+ * Take a byte array and convert it into a Track
+ */
 VikTrack *vik_track_unmarshall (guint8 *data, guint datalen)
 {
   guint len;
@@ -1028,8 +1316,13 @@ VikTrack *vik_track_unmarshall (guint8 *data, guint datalen)
   guint ntp;
   gint i;
 
-  /* only the visibility is needed */
+  /* basic properties: */
   new_tr->visible = ((VikTrack *)data)->visible;
+  new_tr->is_route = ((VikTrack *)data)->is_route;
+  new_tr->has_color = ((VikTrack *)data)->has_color;
+  new_tr->color = ((VikTrack *)data)->color;
+  new_tr->bbox = ((VikTrack *)data)->bbox;
+
   data += sizeof(*new_tr);
 
   ntp = *(guint *)data;
@@ -1042,14 +1335,65 @@ VikTrack *vik_track_unmarshall (guint8 *data, guint datalen)
     new_tr->trackpoints = g_list_append(new_tr->trackpoints, new_tp);
   }
 
-  len = *(guint *)data;
-  data += sizeof(len);
-  if (len) {
-    new_tr->comment = g_strdup((gchar *)data);
-  }
+#define vtu_get(s) \
+  len = *(guint *)data; \
+  data += sizeof(len); \
+  if (len) { \
+    (s) = g_strdup((gchar *)data); \
+  } else { \
+    (s) = NULL; \
+  } \
+  data += len;
+
+  vtu_get(new_tr->name);
+  vtu_get(new_tr->comment);
+  vtu_get(new_tr->description);
+
   return new_tr;
 }
 
+/**
+ * (Re)Calculate the bounds of the given track,
+ *  updating the track's bounds data.
+ * This should be called whenever a track's trackpoints are changed
+ */
+void vik_track_calculate_bounds ( VikTrack *trk )
+{
+  GList *tp_iter;
+  tp_iter = trk->trackpoints;
+  
+  struct LatLon topleft, bottomright, ll;
+  
+  // Set bounds to first point
+  if ( tp_iter ) {
+    vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &topleft );
+    vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &bottomright );
+  }
+  while ( tp_iter ) {
+
+    // See if this trackpoint increases the track bounds.
+   
+    vik_coord_to_latlon ( &(VIK_TRACKPOINT(tp_iter->data)->coord), &ll );
+  
+    if ( ll.lat > topleft.lat) topleft.lat = ll.lat;
+    if ( ll.lon < topleft.lon) topleft.lon = ll.lon;
+    if ( ll.lat < bottomright.lat) bottomright.lat = ll.lat;
+    if ( ll.lon > bottomright.lon) bottomright.lon = ll.lon;
+    
+    tp_iter = tp_iter->next;
+  }
+  g_debug ( "Bounds of track: '%s' is: %f,%f to: %f,%f", trk->name, topleft.lat, topleft.lon, bottomright.lat, bottomright.lon );
+
+  trk->bbox.north = topleft.lat;
+  trk->bbox.east = bottomright.lon;
+  trk->bbox.south = bottomright.lat;
+  trk->bbox.west = topleft.lon;
+}
+
+/**
+ *
+ */
 void vik_track_apply_dem_data ( VikTrack *tr )
 {
   GList *tp_iter;
@@ -1066,24 +1410,45 @@ void vik_track_apply_dem_data ( VikTrack *tr )
   }
 }
 
-/* appends t2 to t1, leaving t2 with no trackpoints */
+/**
+ * vik_track_apply_dem_data_last_trackpoint:
+ * Apply DEM data (if available) - to only the last trackpoint
+ */
+void vik_track_apply_dem_data_last_trackpoint ( VikTrack *tr )
+{
+  gint16 elev;
+  if ( tr->trackpoints ) {
+    /* As in vik_track_apply_dem_data above - use 'best' interpolation method */
+    elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->coord), VIK_DEM_INTERPOL_BEST );
+    if ( elev != VIK_DEM_INVALID_ELEVATION )
+      VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->altitude = elev;
+  }
+}
+
+/**
+ * vik_track_steal_and_append_trackpoints:
+ * 
+ * appends t2 to t1, leaving t2 with no trackpoints
+ */
 void vik_track_steal_and_append_trackpoints ( VikTrack *t1, VikTrack *t2 )
 {
   if ( t1->trackpoints ) {
-    GList *tpiter = t1->trackpoints;
-    while ( tpiter->next )
-      tpiter = tpiter->next;
-    tpiter->next = t2->trackpoints;
-    t2->trackpoints->prev = tpiter;
+    t1->trackpoints = g_list_concat ( t1->trackpoints, t2->trackpoints );
   } else
     t1->trackpoints = t2->trackpoints;
   t2->trackpoints = NULL;
+
+  // Trackpoints updated - so update the bounds
+  vik_track_calculate_bounds ( t1 );
 }
 
-/* starting at the end, looks backwards for the last "double point", a duplicate trackpoint.
- * this is indicative of magic scissors continued use. If there is no double point,
- * deletes all the trackpoints. Returns the new end of the track (or the start if
- * there are no double points
+/**
+ * vik_track_cut_back_to_double_point:
+ * 
+ * starting at the end, looks backwards for the last "double point", a duplicate trackpoint.
+ * If there is no double point, deletes all the trackpoints.
+ * 
+ * Returns: the new end of the track (or the start if there are no double points)
  */
 VikCoord *vik_track_cut_back_to_double_point ( VikTrack *tr )
 {