]> git.street.me.uk Git - andy/viking.git/blobdiff - src/viktrack.c
[QA] Shift Gtk dependent utility functions into separate file.
[andy/viking.git] / src / viktrack.c
index 8a23b0624b33a16e4e4bd69c44f1b549e08d3640..2c25f061dc669fb0ac70719f13f3baa6cfb2e209 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
@@ -37,6 +38,7 @@
 #include "viktrack.h"
 #include "globals.h"
 #include "dems.h"
+#include "settings.h"
 
 VikTrack *vik_track_new()
 {
@@ -45,6 +47,26 @@ VikTrack *vik_track_new()
   return tr;
 }
 
+#define VIK_SETTINGS_TRACK_NAME_MODE "track_draw_name_mode"
+#define VIK_SETTINGS_TRACK_NUM_DIST_LABELS "track_number_dist_labels"
+
+/**
+ * vik_track_set_defaults:
+ *
+ * Set some default values for a track.
+ * ATM This uses the 'settings' method to get values,
+ *  so there is no GUI way to control these yet...
+ */
+void vik_track_set_defaults(VikTrack *tr)
+{
+  gint tmp;
+  if ( a_settings_get_integer ( VIK_SETTINGS_TRACK_NAME_MODE, &tmp ) )
+    tr->draw_name_mode = tmp;
+
+  if ( a_settings_get_integer ( VIK_SETTINGS_TRACK_NUM_DIST_LABELS, &tmp ) )
+    tr->max_number_dist_labels = tmp;
+}
+
 void vik_track_set_comment_no_copy(VikTrack *tr, gchar *comment)
 {
   if ( tr->comment )
@@ -53,6 +75,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 +94,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,9 +126,13 @@ 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 );
-  g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
+  if ( tr->description )
+    g_free ( tr->description );
+  g_list_foreach ( tr->trackpoints, (GFunc) vik_trackpoint_free, NULL );
   g_list_free( tr->trackpoints );
   if (tr->property_dialog)
     if ( GTK_IS_WIDGET(tr->property_dialog) )
@@ -95,21 +140,43 @@ 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->name = g_strdup(tr->name);
   new_tr->visible = tr->visible;
+  new_tr->is_route = tr->is_route;
+  new_tr->draw_name_mode = tr->draw_name_mode;
+  new_tr->max_number_dist_labels = tr->max_number_dist_labels;
+  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;
+    GList *tp_iter = tr->trackpoints;
+    while ( tp_iter )
+    {
+      VikTrackpoint *new_tp = vik_trackpoint_copy ( (VikTrackpoint*)(tp_iter->data) );
+      new_tr->trackpoints = g_list_prepend ( new_tr->trackpoints, new_tp );
+      tp_iter = tp_iter->next;
+    }
+    if ( new_tr->trackpoints )
+      new_tr->trackpoints = g_list_reverse ( new_tr->trackpoints );
   }
+  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;
 }
 
@@ -127,14 +194,108 @@ VikTrackpoint *vik_trackpoint_new()
 
 void vik_trackpoint_free(VikTrackpoint *tp)
 {
+  g_free(tp->name);
   g_free(tp);
 }
 
+void vik_trackpoint_set_name(VikTrackpoint *tp, const gchar *name)
+{
+  if ( tp->name )
+    g_free ( tp->name );
+
+  // If the name is blank then completely remove it
+  if ( name && name[0] == '\0' )
+    tp->name = NULL;
+  else if ( name )
+    tp->name = g_strdup(name);
+  else
+    tp->name = NULL;
+}
+
 VikTrackpoint *vik_trackpoint_copy(VikTrackpoint *tp)
 {
-  VikTrackpoint *rv = vik_trackpoint_new();
-  *rv = *tp;
-  return rv;
+  VikTrackpoint *new_tp = vik_trackpoint_new();
+  memcpy ( new_tp, tp, sizeof(VikTrackpoint) );
+  if ( tp->name )
+    new_tp->name = g_strdup (tp->name);
+  return new_tp;
+}
+
+/**
+ * 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 )
+{
+  // When it's the first trackpoint need to ensure the bounding box is initialized correctly
+  gboolean adding_first_point = tr->trackpoints ? FALSE : TRUE;
+  tr->trackpoints = g_list_append ( tr->trackpoints, tp );
+  if ( adding_first_point )
+    vik_track_calculate_bounds ( tr );
+  else if ( recalculate )
+    track_recalculate_bounds_last_tp ( tr );
+}
+
+/**
+ * vik_track_get_length_to_trackpoint:
+ *
+ */
+gdouble vik_track_get_length_to_trackpoint (const VikTrack *tr, const VikTrackpoint *tp)
+{
+  gdouble len = 0.0;
+  if ( tr->trackpoints )
+  {
+    // Is it the very first track point?
+    if ( VIK_TRACKPOINT(tr->trackpoints->data) == tp )
+      return len;
+
+    GList *iter = tr->trackpoints->next;
+    while (iter)
+    {
+      VikTrackpoint *tp1 = VIK_TRACKPOINT(iter->data);
+      if ( ! tp1->newsegment )
+        len += vik_coord_diff ( &(tp1->coord),
+                                &(VIK_TRACKPOINT(iter->prev->data)->coord) );
+
+      // Exit when we reach the desired point
+      if ( tp1 == tp )
+        break;
+
+      iter = iter->next;
+    }
+  }
+  return len;
 }
 
 gdouble vik_track_get_length(const VikTrack *tr)
@@ -171,18 +332,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 +362,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 +488,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 +499,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 +511,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. */
@@ -286,6 +559,31 @@ void vik_track_reverse ( VikTrack *tr )
   }
 }
 
+/**
+ * vik_track_get_duration:
+ * @trk: The track
+ *
+ * Returns: The time in seconds that covers the whole track including gaps
+ *  NB this may be negative particularly if the track has been reversed
+ */
+time_t vik_track_get_duration(const VikTrack *trk)
+{
+  time_t duration = 0;
+  if ( trk->trackpoints ) {
+    // Ensure times are available
+    if ( vik_track_get_tp_first(trk)->has_timestamp ) {
+      // Get trkpt only once - as using vik_track_get_tp_last() iterates whole track each time
+      VikTrackpoint *trkpt_last = vik_track_get_tp_last(trk);
+      if ( trkpt_last->has_timestamp ) {
+        time_t t1 = vik_track_get_tp_first(trk)->timestamp;
+        time_t t2 = trkpt_last->timestamp;
+        duration = t2 - t1;
+      }
+    }
+  }
+  return duration;
+}
+
 gdouble vik_track_get_average_speed(const VikTrack *tr)
 {
   gdouble len = 0.0;
@@ -397,7 +695,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;
@@ -560,6 +863,8 @@ gdouble *vik_track_make_gradient_map ( const VikTrack *tr, guint16 num_chunks )
 
   pts[current_chunk] = current_gradient;
 
+  g_free ( altitudes );
+
   return pts;
 }
 
@@ -599,7 +904,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) );
@@ -673,7 +978,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) );
@@ -843,7 +1148,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) );
@@ -878,6 +1183,55 @@ gdouble *vik_track_make_speed_dist_map ( const VikTrack *tr, guint16 num_chunks
   return v;
 }
 
+/**
+ * vik_track_get_tp_by_dist:
+ * @trk:                  The Track on which to find a Trackpoint
+ * @meters_from_start:    The distance along a track that the trackpoint returned is near
+ * @get_next_point:       Since there is a choice of trackpoints, this determines which one to return
+ * @tp_metres_from_start: For the returned Trackpoint, returns the distance along the track
+ *
+ * TODO: Consider changing the boolean get_next_point into an enum with these options PREVIOUS, NEXT, NEAREST
+ *
+ * Returns: The #VikTrackpoint fitting the criteria or NULL
+ */
+VikTrackpoint *vik_track_get_tp_by_dist ( VikTrack *trk, gdouble meters_from_start, gboolean get_next_point, gdouble *tp_metres_from_start )
+{
+  gdouble current_dist = 0.0;
+  gdouble current_inc = 0.0;
+  if ( tp_metres_from_start )
+    *tp_metres_from_start = 0.0;
+
+  if ( trk->trackpoints ) {
+    GList *iter = g_list_next ( g_list_first ( trk->trackpoints ) );
+    while (iter) {
+      current_inc = vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
+                                     &(VIK_TRACKPOINT(iter->prev->data)->coord) );
+      current_dist += current_inc;
+      if ( current_dist >= meters_from_start )
+        break;
+      iter = g_list_next ( iter );
+    }
+    // passed the end of the track
+    if ( !iter )
+      return NULL;
+
+    if ( tp_metres_from_start )
+      *tp_metres_from_start = current_dist;
+
+    // we've gone past the distance already, is the previous trackpoint wanted?
+    if ( !get_next_point ) {
+      if ( iter->prev ) {
+        if ( tp_metres_from_start )
+          *tp_metres_from_start = current_dist-current_inc;
+        return VIK_TRACKPOINT(iter->prev->data);
+      }
+    }
+    return VIK_TRACKPOINT(iter->data);
+  }
+
+  return NULL;
+}
+
 /* by Alex Foobarian */
 VikTrackpoint *vik_track_get_closest_tp_by_percentage_dist ( VikTrack *tr, gdouble reldist, gdouble *meters_from_start )
 {
@@ -946,7 +1300,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;
@@ -1042,6 +1396,22 @@ VikTrackpoint* vik_track_get_tp_by_min_alt ( const VikTrack *tr )
   return min_alt_tp;
 }
 
+VikTrackpoint *vik_track_get_tp_first( const VikTrack *tr )
+{
+  if ( !tr->trackpoints )
+    return NULL;
+
+  return (VikTrackpoint*)g_list_first(tr->trackpoints)->data;
+}
+
+VikTrackpoint *vik_track_get_tp_last ( const VikTrack *tr )
+{
+  if ( !tr->trackpoints )
+    return NULL;
+
+  return (VikTrackpoint*)g_list_last(tr->trackpoints)->data;
+}
+
 gboolean vik_track_get_minmax_alt ( const VikTrack *tr, gdouble *min_alt, gdouble *max_alt )
 {
   *min_alt = 25000;
@@ -1076,24 +1446,35 @@ void vik_track_marshall ( VikTrack *tr, guint8 **data, guint *datalen)
   intp = b->len;
   g_byte_array_append(b, (guint8 *)&len, sizeof(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);
+
   tps = tr->trackpoints;
   ntp = 0;
   while (tps) {
     g_byte_array_append(b, (guint8 *)tps->data, sizeof(VikTrackpoint));
+    vtm_append(VIK_TRACKPOINT(tps->data)->name);
     tps = tps->next;
     ntp++;
   }
   *(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);
+  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;
@@ -1102,45 +1483,149 @@ 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->draw_name_mode = ((VikTrack *)data)->draw_name_mode;
+  new_tr->max_number_dist_labels = ((VikTrack *)data)->max_number_dist_labels;
+  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;
   data += sizeof(ntp);
 
+#define vtu_get(s) \
+  len = *(guint *)data; \
+  data += sizeof(len); \
+  if (len) { \
+    (s) = g_strdup((gchar *)data); \
+  } else { \
+    (s) = NULL; \
+  } \
+  data += len;
+
   for (i=0; i<ntp; i++) {
     new_tp = vik_trackpoint_new();
     memcpy(new_tp, data, sizeof(*new_tp));
     data += sizeof(*new_tp);
-    new_tr->trackpoints = g_list_append(new_tr->trackpoints, new_tp);
+    vtu_get(new_tp->name);
+    new_tr->trackpoints = g_list_prepend(new_tr->trackpoints, new_tp);
   }
+  if ( new_tr->trackpoints )
+    new_tr->trackpoints = g_list_reverse(new_tr->trackpoints);
+
+  vtu_get(new_tr->name);
+  vtu_get(new_tr->comment);
+  vtu_get(new_tr->description);
 
-  len = *(guint *)data;
-  data += sizeof(len);
-  if (len) {
-    new_tr->comment = g_strdup((gchar *)data);
-  }
   return new_tr;
 }
 
-void vik_track_apply_dem_data ( VikTrack *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;
+}
+
+/**
+ * vik_track_anonymize_times:
+ *
+ * Shift all timestamps to be relatively offset from 1901-01-01
+ */
+void vik_track_anonymize_times ( VikTrack *tr )
+{
+  GTimeVal gtv;
+  g_time_val_from_iso8601 ( "1901-01-01T00:00:00Z", &gtv );
+
+  time_t anon_timestamp = gtv.tv_sec;
+  time_t offset = 0;
+
+  GList *tp_iter;
+  tp_iter = tr->trackpoints;
+  while ( tp_iter ) {
+    VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
+    if ( tp->has_timestamp ) {
+      // Calculate an offset in time using the first available timestamp
+      if ( offset == 0 )
+       offset = tp->timestamp - anon_timestamp;
+
+      // Apply this offset to shift all timestamps towards 1901 & hence anonymising the time
+      // Note that the relative difference between timestamps is kept - thus calculating speeds will still work
+      tp->timestamp = tp->timestamp - offset;
+    }
+    tp_iter = tp_iter->next;
+  }
+}
+
+
+/**
+ * vik_track_apply_dem_data:
+ * @skip_existing: When TRUE, don't change the elevation if the trackpoint already has a value
+ *
+ * Set elevation data for a track using any available DEM information
+ */
+gulong vik_track_apply_dem_data ( VikTrack *tr, gboolean skip_existing )
 {
+  gulong num = 0;
   GList *tp_iter;
   gint16 elev;
   tp_iter = tr->trackpoints;
   while ( tp_iter ) {
-    /* TODO: of the 4 possible choices we have for choosing an elevation
-     * (trackpoint in between samples), choose the one with the least elevation change
-     * as the last */
-    elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(tp_iter->data)->coord), VIK_DEM_INTERPOL_BEST );
-    if ( elev != VIK_DEM_INVALID_ELEVATION )
-      VIK_TRACKPOINT(tp_iter->data)->altitude = elev;
+    // Don't apply if the point already has a value and the overwrite is off
+    if ( !(skip_existing && VIK_TRACKPOINT(tp_iter->data)->altitude != VIK_DEFAULT_ALTITUDE) ) {
+      /* TODO: of the 4 possible choices we have for choosing an elevation
+       * (trackpoint in between samples), choose the one with the least elevation change
+       * as the last */
+      elev = a_dems_get_elev_by_coord ( &(VIK_TRACKPOINT(tp_iter->data)->coord), VIK_DEM_INTERPOL_BEST );
+
+      if ( elev != VIK_DEM_INVALID_ELEVATION ) {
+        VIK_TRACKPOINT(tp_iter->data)->altitude = elev;
+       num++;
+      }
+    }
     tp_iter = tp_iter->next;
   }
+  return num;
 }
 
-/*
+/**
+ * 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 )
@@ -1154,23 +1639,125 @@ void vik_track_apply_dem_data_last_trackpoint ( VikTrack *tr )
   }
 }
 
-/* appends t2 to t1, leaving t2 with no trackpoints */
+
+/**
+ * smoothie:
+ *
+ * Apply elevation smoothing over range of trackpoints between the list start and end points
+ */
+static void smoothie ( GList *tp1, GList *tp2, gdouble elev1, gdouble elev2, guint points )
+{
+  // If was really clever could try and weigh interpolation according to the distance between trackpoints somehow
+  // Instead a simple average interpolation for the number of points given.
+  gdouble change = (elev2 - elev1)/(points+1);
+  gint count = 1;
+  GList *tp_iter = tp1;
+  while ( tp_iter != tp2 && tp_iter ) {
+    VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
+
+    tp->altitude = elev1 + (change*count);
+
+    count++;
+    tp_iter = tp_iter->next;
+  }
+}
+
+/**
+ * vik_track_smooth_missing_elevation_data:
+ * @flat: Specify how the missing elevations will be set.
+ *        When TRUE it uses a simple flat method, using the last known elevation
+ *        When FALSE is uses an interpolation method to the next known elevation
+ *
+ * For each point with a missing elevation, set it to use the last known available elevation value.
+ * Primarily of use for smallish DEM holes where it is missing elevation data.
+ * Eg see Austria: around N47.3 & E13.8
+ *
+ * Returns: The number of points that were adjusted
+ */
+gulong vik_track_smooth_missing_elevation_data ( VikTrack *tr, gboolean flat )
+{
+  gulong num = 0;
+
+  GList *tp_iter;
+  gdouble elev = VIK_DEFAULT_ALTITUDE;
+
+  VikTrackpoint *tp_missing = NULL;
+  GList *iter_first = NULL;
+  guint points = 0;
+
+  tp_iter = tr->trackpoints;
+  while ( tp_iter ) {
+    VikTrackpoint *tp = VIK_TRACKPOINT(tp_iter->data);
+
+    if ( VIK_DEFAULT_ALTITUDE == tp->altitude ) {
+      if ( flat ) {
+        // Simply assign to last known value
+       if ( elev != VIK_DEFAULT_ALTITUDE ) {
+          tp->altitude = elev;
+          num++;
+       }
+      }
+      else {
+        if ( !tp_missing ) {
+          // Remember the first trackpoint (and the list pointer to it) of a section of no altitudes
+          tp_missing = tp;
+          iter_first = tp_iter;
+          points = 1;
+        }
+        else {
+          // More missing altitudes
+          points++;
+        }
+      }
+    }
+    else {
+      // Altitude available (maybe again!)
+      // If this marks the end of a section of altitude-less points
+      //  then apply smoothing for that section of points
+      if ( points > 0 && elev != VIK_DEFAULT_ALTITUDE )
+        if ( !flat ) {
+          smoothie ( iter_first, tp_iter, elev, tp->altitude, points );
+          num = num + points;
+        }
+
+      // reset
+      points = 0;
+      tp_missing = NULL;
+
+      // Store for reuse as the last known good value
+      elev = tp->altitude;
+    }
+
+    tp_iter = tp_iter->next;
+  }
+
+  return num;
+}
+
+/**
+ * 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.
+/**
+ * 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)
+ * 
+ * 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 )
 {
@@ -1184,11 +1771,13 @@ VikCoord *vik_track_cut_back_to_double_point ( VikTrack *tr )
 
 
   while ( iter->prev ) {
-    if ( vik_coord_equals((VikCoord *)iter->data, (VikCoord *)iter->prev->data) ) {
+    VikCoord *cur_coord = &((VikTrackpoint*)iter->data)->coord;
+    VikCoord *prev_coord = &((VikTrackpoint*)iter->prev->data)->coord;
+    if ( vik_coord_equals(cur_coord, prev_coord) ) {
       GList *prev = iter->prev;
 
       rv = g_malloc(sizeof(VikCoord));
-      *rv = *((VikCoord *) iter->data);
+      *rv = *cur_coord;
 
       /* truncate trackpoint list */
       iter->prev = NULL; /* pretend it's the end */
@@ -1204,10 +1793,42 @@ VikCoord *vik_track_cut_back_to_double_point ( VikTrack *tr )
 
   /* no double point found! */
   rv = g_malloc(sizeof(VikCoord));
-  *rv = *((VikCoord *) tr->trackpoints->data);
+  *rv = ((VikTrackpoint*) tr->trackpoints->data)->coord;
   g_list_foreach ( tr->trackpoints, (GFunc) g_free, NULL );
   g_list_free( tr->trackpoints );
   tr->trackpoints = NULL;
   return rv;
 }
 
+/**
+ * Function to compare two tracks by their first timestamp
+ **/
+int vik_track_compare_timestamp (const void *x, const void *y)
+{
+  VikTrack *a = (VikTrack *)x;
+  VikTrack *b = (VikTrack *)y;
+
+  VikTrackpoint *tpa = NULL;
+  VikTrackpoint *tpb = NULL;
+
+  if ( a->trackpoints )
+    tpa = VIK_TRACKPOINT(g_list_first(a->trackpoints)->data);
+
+  if ( b->trackpoints )
+    tpb = VIK_TRACKPOINT(g_list_first(b->trackpoints)->data);
+
+  if ( tpa && tpb ) {
+    if ( tpa->timestamp < tpb->timestamp )
+      return -1;
+    if ( tpa->timestamp > tpb->timestamp )
+      return 1;
+  }
+
+  if ( tpa && !tpb )
+    return 1;
+
+  if ( !tpa && tpb )
+    return -1;
+
+  return 0;
+}