]> git.street.me.uk Git - andy/viking.git/blobdiff - src/file.c
SF Features#116: Add an Acquire From URL option.
[andy/viking.git] / src / file.c
index 6a8e75f35a3d1a3d0bf091f1ee3a231ffa77f2f0..b6f3a65d44bc9b1552482268dac14dd82113a570 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, Guilhem Bonnefille <guilhem.bonnefille@gmail.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
@@ -25,6 +26,7 @@
 #include "viking.h"
 
 #include "gpx.h"
+#include "babel.h"
 
 #include <string.h>
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+#ifdef WINDOWS
+#define realpath(X,Y) _fullpath(Y,X,MAX_PATH)
+#endif
 #include <glib.h>
 #include <glib/gstdio.h>
-
-/* Relax some dependencies */
-#if ! GLIB_CHECK_VERSION(2,12,0)
-static gboolean return_true (gpointer a, gpointer b, gpointer c) { return TRUE; }
-static g_hash_table_remove_all (GHashTable *ght) { g_hash_table_foreach_remove ( ght, (GHRFunc) return_true, FALSE ); }
-#endif
+#include <glib/gi18n.h>
 
 #define TEST_BOOLEAN(str) (! ((str)[0] == '\0' || (str)[0] == '0' || (str)[0] == 'n' || (str)[0] == 'N' || (str)[0] == 'f' || (str)[0] == 'F') )
 #define VIK_MAGIC "#VIK"
@@ -52,6 +52,8 @@ static g_hash_table_remove_all (GHashTable *ght) { g_hash_table_foreach_remove (
 #define FILE_SEP '/'
 #endif
 
+#define VIKING_FILE_VERSION 1
+
 typedef struct _Stack Stack;
 
 struct _Stack {
@@ -93,16 +95,7 @@ static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, gu
   return FALSE;
 }
 
-static guint16 layer_type_from_string ( const gchar *str )
-{
-  guint8 i;
-  for ( i = 0; i < VIK_LAYER_NUM_TYPES; i++ )
-    if ( strcasecmp ( str, vik_layer_get_interface(i)->name ) == 0 )
-      return i;
-  return -1;
-}
-
-void file_write_layer_param ( FILE *f, const gchar *name, guint8 type, VikLayerParamData data ) {
+void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
       /* string lists are handled differently. We get a GList (that shouldn't
        * be freed) back for get_param and if it is null we shouldn't write
        * anything at all (otherwise we'd read in a list with an empty string,
@@ -130,8 +123,9 @@ void file_write_layer_param ( FILE *f, const gchar *name, guint8 type, VikLayerP
           case VIK_LAYER_PARAM_UINT: fprintf ( f, "%d\n", data.u ); break;
           case VIK_LAYER_PARAM_INT: fprintf ( f, "%d\n", data.i ); break;
           case VIK_LAYER_PARAM_BOOLEAN: fprintf ( f, "%c\n", data.b ? 't' : 'f' ); break;
-          case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ); break;
+          case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
           case VIK_LAYER_PARAM_COLOR: fprintf ( f, "#%.2x%.2x%.2x\n", (int)(data.c.red/256),(int)(data.c.green/256),(int)(data.c.blue/256)); break;
+          default: break;
         }
       }
 }
@@ -151,7 +145,7 @@ static void write_layer_params_and_data ( VikLayer *l, FILE *f )
     guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
     for ( i = 0; i < params_count; i++ )
     {
-      data = get_param(l,i);
+      data = get_param(l, i, TRUE);
       file_write_layer_param(f, params[i].name, params[i].type, data);
     }
   }
@@ -172,7 +166,8 @@ static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
   Stack *stack = NULL;
   VikLayer *current_layer;
   struct LatLon ll;
-  gchar *modestring;
+  VikViewportDrawMode mode;
+  gchar *modestring = NULL;
 
   push(&stack);
   stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
@@ -181,19 +176,25 @@ static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
   /* crazhy CRAZHY */
   vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
 
-  switch ( vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) ) ) {
+  mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
+  switch ( mode ) {
     case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
     case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
-    case VIK_VIEWPORT_DRAWMODE_GOOGLE: modestring = "google"; break;
-    case VIK_VIEWPORT_DRAWMODE_KH: modestring = "kh"; break;
-    default: modestring = "mercator";
+    case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
+    case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
+    default:
+      g_critical("Houston, we've had a problem. mode=%d", mode);
   }
 
-  fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\ndrawscale=%s\ndrawcentermark=%s",
+  fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n" );
+  fprintf ( f, "FILE_VERSION=%d\n", VIKING_FILE_VERSION );
+  fprintf ( f, "\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\nhighlightcolor=%s\ndrawscale=%s\ndrawcentermark=%s\ndrawhighlight=%s\n",
       vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
       modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
+      vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
       vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
-      vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f" );
+      vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
+      vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
 
   if ( ! VIK_LAYER(top)->visible )
     fprintf ( f, "visible=f\n" );
@@ -201,7 +202,7 @@ static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
   while (stack && stack->data)
   {
     current_layer = VIK_LAYER(((GList *)stack->data)->data);
-    fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->name );
+    fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
     write_layer_params_and_data ( current_layer, f );
     if ( current_layer->type == VIK_LAYER_AGGREGATE && !vik_aggregate_layer_is_empty(VIK_AGGREGATE_LAYER(current_layer)) )
     {
@@ -256,10 +257,18 @@ static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
 {
   VikLayerParamData x;
   x.sl = list;
-  vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1] );
+  vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
 }
 
-static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
+/**
+ * Read in a Viking file and return how successful the parsing was
+ * ATM this will always work, in that even if there are parsing problems
+ *  then there will be no new values to override the defaults
+ *
+ * TODO flow up line number(s) / error messages of problems encountered...
+ *
+ */
+static gboolean file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
 {
   Stack *stack;
   struct LatLon ll = { 0.0, 0.0 };
@@ -273,6 +282,8 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
 
   GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
 
+  gboolean successful_read = TRUE;
+
   push(&stack);
   stack->under = NULL;
   stack->data = (gpointer) top;
@@ -309,6 +320,7 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
         int parent_type = VIK_LAYER(stack->data)->type;
         if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
         {
+          successful_read = FALSE;
           g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
           push(&stack); /* inside INVALID layer */
           stack->data = NULL;
@@ -316,10 +328,11 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
         }
         else
         {
-          gint16 type = layer_type_from_string ( line+6 );
+          VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
           push(&stack);
-          if ( type == -1 )
+          if ( type == VIK_LAYER_NUM_TYPES )
           {
+            successful_read = FALSE;
             g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
             stack->data = NULL;
           }
@@ -339,8 +352,10 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
       }
       else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
       {
-        if ( stack->under == NULL )
+        if ( stack->under == NULL ) {
+          successful_read = FALSE;
           g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
+        }
         else
         {
           /* add any string lists we've accumulated */
@@ -353,14 +368,16 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
           if ( stack->data && stack->under->data )
           {
             if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
-              vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data) );
+              vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
               vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
             }
             else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
               /* TODO: anything else needs to be done here ? */
             }
-            else
+            else {
+              successful_read = FALSE;
               g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
+            }
           }
           pop(&stack);
         }
@@ -368,9 +385,11 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
       else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
       {
         if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
-          vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f );
+        {
           /* must read until hits ~EndLayerData */
-
+          if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f ) )
+            successful_read = FALSE;
+        }
         else
         { /* simply skip layer data over */
           while ( fgets ( buffer, 4096, f ) )
@@ -392,6 +411,7 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
       }
       else
       {
+        successful_read = FALSE;
         g_warning ( "Line %ld: Unknown tilde command", line_num );
       }
     }
@@ -406,7 +426,14 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
         if ( line[i] == '=' )
           eq_pos = i;
 
-      if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
+      if ( stack->under == NULL && eq_pos == 12 && strncasecmp ( line, "FILE_VERSION", eq_pos ) == 0) {
+        gint version = strtol(line+13, NULL, 10);
+        g_debug ( "%s: reading file version %d", __FUNCTION__, version );
+        if ( version > VIKING_FILE_VERSION )
+          successful_read = FALSE;
+        // However we'll still carry and attempt to read whatever we can
+      }
+      else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
         vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
         vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
@@ -419,17 +446,29 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "expedia" ) == 0)
         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_EXPEDIA );
       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "google" ) == 0)
-        vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_GOOGLE );
+      {
+        successful_read = FALSE;
+        g_warning ( _("Draw mode '%s' no more supported"), "google" );
+      }
       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
-        vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_KH );
+      {
+        successful_read = FALSE;
+        g_warning ( _("Draw mode '%s' no more supported"), "kh" );
+      }
       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "mercator" ) == 0)
         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_MERCATOR );
+      else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "latlon" ) == 0)
+        vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_LATLON );
       else if ( stack->under == NULL && eq_pos == 5 && strncasecmp ( line, "color", eq_pos ) == 0 )
         vik_viewport_set_background_color ( VIK_VIEWPORT(vp), line+6 );
+      else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "highlightcolor", eq_pos ) == 0 )
+        vik_viewport_set_highlight_color ( VIK_VIEWPORT(vp), line+15 );
       else if ( stack->under == NULL && eq_pos == 9 && strncasecmp ( line, "drawscale", eq_pos ) == 0 )
         vik_viewport_set_draw_scale ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+10) );
       else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
         vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
+      else if ( stack->under == NULL && eq_pos == 13 && strncasecmp ( line, "drawhighlight", eq_pos ) == 0 )
+        vik_viewport_set_draw_highlight ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+14) );
       else if ( stack->under && eq_pos == 4 && strncasecmp ( line, "name", eq_pos ) == 0 )
         vik_layer_rename ( VIK_LAYER(stack->data), line+5 );
       else if ( eq_pos == 7 && strncasecmp ( line, "visible", eq_pos ) == 0 )
@@ -443,6 +482,7 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
 
         if ( ! params )
         {
+          successful_read = FALSE;
           g_warning ( "Line %ld: No options for this kind of layer", line_num );
           continue;
         }
@@ -453,8 +493,9 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
             VikLayerParamData x;
             line += eq_pos+1;
             if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
-              GList *l = g_list_append ( g_hash_table_lookup ( string_lists, (gpointer) ((gint) i) ), g_strdup(line) );
-              g_hash_table_replace ( string_lists, (gpointer) ((gint)i), l );
+              GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ), 
+                                        g_strdup(line) );
+              g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
               /* add the value to a list, possibly making a new list.
                * this will be passed to the layer when we read an ~EndLayer */
             } else {
@@ -469,16 +510,24 @@ static void file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
                 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
                 default: x.s = line;
               }
-              vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp );
+              vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
             }
             found_match = TRUE;
             break;
           }
-        if ( ! found_match )
+        if ( ! found_match ) {
+          // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
+          //   and don't what to worry users about raising such issues
+          // TODO Maybe hold old values here - compare the line value against them and if a match
+          //       generate a different style of message in the GUI...
+          // successful_read = FALSE;
           g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
+       }
       }
-      else
+      else {
+        successful_read = FALSE;
         g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
+      }
     }
 /* could be:
 [Layer Type=Bla]
@@ -493,7 +542,7 @@ name=this
   {
     if ( stack->under && stack->under->data && stack->data )
     {
-      vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data) );
+      vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
       vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
     }
     pop(&stack);
@@ -508,6 +557,8 @@ name=this
   /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
   g_hash_table_foreach ( string_lists, string_list_delete, NULL );
   g_hash_table_destroy ( string_lists );
+
+  return successful_read;
 }
 
 /*
@@ -542,52 +593,126 @@ static void xfclose ( FILE *f )
   }
 }
 
-/* 0 on failure, 1 on success (vik file) 2 on success (other file) */
-gshort a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename )
+/*
+ * Function to determine if a filename is a 'viking' type file
+ */
+gboolean check_file_magic_vik ( const gchar *filename )
 {
-  FILE *f = xfopen ( filename, "r" );
+  gboolean result = FALSE;
+  FILE *ff = xfopen ( filename, "r" );
+  if ( ff ) {
+    result = check_magic ( ff, VIK_MAGIC );
+    xfclose ( ff );
+  }
+  return result;
+}
 
-  g_assert ( vp );
+VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
+{
+  g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
+
+  char *filename = (char *)filename_or_uri;
+  if (strncmp(filename, "file://", 7) == 0) {
+    // Consider replacing this with:
+    // filename = g_filename_from_uri ( entry, NULL, NULL );
+    // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it)
+    filename = filename + 7;
+    g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
+  }
+  FILE *f = xfopen ( filename, "r" );
 
   if ( ! f )
-    return 0;
+    return LOAD_TYPE_READ_FAILURE;
+
+  // Enables relative paths in a .vik file to work
+  // Also allows us to remember what directory we where using
+  gchar *dir = g_path_get_dirname ( filename );
+  if ( dir ) {
+    if ( g_chdir ( dir ) ) {
+      g_warning ( "Could not change directory to %s", dir );
+    }
+    g_free (dir);
+  }
 
+  VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
+
+  // Attempt loading the primary file type first - our internal .vik file:
   if ( check_magic ( f, VIK_MAGIC ) )
   {
-    file_read ( top, f, vp );
-    if ( f != stdin )
-      xfclose(f);
-    return 1;
+    if ( file_read ( top, f, vp ) )
+      load_answer = LOAD_TYPE_VIK_SUCCESS;
+    else
+      load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
   }
   else
   {
-    VikCoord new_center;
-    VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, NULL, FALSE );
-    vik_layer_rename ( vtl, a_file_basename ( filename ) );
+       // For all other file types which consist of tracks, routes and/or waypoints,
+       //  must be loaded into a new TrackWaypoint layer (hence it be created)
+    gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
 
-    if ( check_magic ( f, GPX_MAGIC ) )
-      a_gpx_read_file ( VIK_TRW_LAYER(vtl), f );
-    else
-     a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f );
-
-    vik_layer_post_read ( vtl, vp, TRUE );
+    VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, NULL, FALSE );
 
-    vik_aggregate_layer_add_layer ( top, vtl );
+    // In fact both kml & gpx files start the same as they are in xml
+    if ( check_file_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
+      // Implicit Conversion
+      if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
+        load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
+      }
+    }
+    // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
+    //    - which currently confuses our check_magic function
+    else if ( check_file_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
+      if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
+        load_answer = LOAD_TYPE_GPX_FAILURE;
+      }
+    }
+    else {
+      // Try final supported file type
+      if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
+               // Failure here means we don't know how to handle the file
+        load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
+         }
+    }
 
-    if ( vik_trw_layer_find_center ( VIK_TRW_LAYER(vtl), &new_center ) )
-      vik_viewport_set_center_coord ( VIK_VIEWPORT(vp), &new_center );
-    xfclose(f);
-    return 2;
+    // Clean up when we can't handle the file
+    if ( ! success ) {
+      // free up layer
+      g_object_unref ( vtl );
+    }
+    else {
+      // Complete the setup from the successful load
+      vik_layer_rename ( vtl, a_file_basename ( filename ) );
+      vik_layer_post_read ( vtl, vp, TRUE );
+      vik_aggregate_layer_add_layer ( top, vtl, FALSE );
+      vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
+    }
   }
+  xfclose(f);
+  return load_answer;
 }
 
 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
 {
-  FILE *f = g_fopen(filename, "w");
+  FILE *f;
+
+  if (strncmp(filename, "file://", 7) == 0)
+    filename = filename + 7;
+
+  f = g_fopen(filename, "w");
 
   if ( ! f )
     return FALSE;
 
+  // Enable relative paths in .vik files to work
+  // Also allows us to remember what directory we where using
+  gchar *dir = g_path_get_dirname ( filename );
+  if ( dir ) {
+    if ( g_chdir ( dir ) ) {
+      g_warning ( "Could not change directory to %s", dir );
+    }
+    g_free (dir);
+  }
+
   file_write ( top, f, vp );
 
   fclose(f);
@@ -608,17 +733,82 @@ const gchar *a_file_basename ( const gchar *filename )
   return filename;
 }
 
-gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, gshort file_type )
+/* example: 
+     gboolean is_gpx = check_file_ext ( "a/b/c.gpx", ".gpx" );
+*/
+gboolean check_file_ext ( const gchar *filename, const gchar *fileext )
 {
+  g_return_val_if_fail ( filename != NULL, FALSE );
+  g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
+  const gchar *basename = a_file_basename(filename);
+  if (!basename)
+    return FALSE;
+
+  const char * dot = strrchr(basename, '.');
+  if (dot && !strcmp(dot, fileext))
+    return TRUE;
+
+  return FALSE;
+}
+
+/**
+ * a_file_export:
+ * @vtl: The TrackWaypoint to export data from
+ * @filename: The name of the file to be written
+ * @file_type: Choose one of the supported file types for the export
+ * @trk: If specified then only export this track rather than the whole layer
+ * @write_hidden: Whether to write invisible items
+ *
+ * A general export command to convert from Viking TRW layer data to an external supported format.
+ * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
+ */
+gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
+{
+  GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
   FILE *f = g_fopen ( filename, "w" );
   if ( f )
   {
-    if ( file_type == FILE_TYPE_GPSMAPPER )
-      a_gpsmapper_write_file ( vtl, f );
-    else if ( file_type == FILE_TYPE_GPX )
-      a_gpx_write_file ( vtl, f );
-    else
-      a_gpspoint_write_file ( vtl, f );
+    if ( trk ) {
+      switch ( file_type ) {
+        case FILE_TYPE_GPX:
+          // trk defined so can set the option
+          options.is_route = trk->is_route;
+          a_gpx_write_track_file ( trk, f, &options );
+          break;
+        default:
+          g_critical("Houston, we've had a problem. file_type=%d", file_type);
+      }
+    } else {
+      switch ( file_type ) {
+        case FILE_TYPE_GPSMAPPER:
+          a_gpsmapper_write_file ( vtl, f );
+          break;
+        case FILE_TYPE_GPX:
+          a_gpx_write_file ( vtl, f, &options );
+          break;
+        case FILE_TYPE_GPSPOINT:
+          a_gpspoint_write_file ( vtl, f );
+          break;
+        case FILE_TYPE_KML:
+         fclose ( f );
+         f = NULL;
+         switch ( a_vik_get_kml_export_units () ) {
+           case VIK_KML_EXPORT_UNITS_STATUTE:
+             return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
+             break;
+           case VIK_KML_EXPORT_UNITS_NAUTICAL:
+             return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
+             break;
+           default:
+             // VIK_KML_EXPORT_UNITS_METRIC:
+             return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
+             break;
+         }
+         break;
+        default:
+          g_critical("Houston, we've had a problem. file_type=%d", file_type);
+      }
+    }
     fclose ( f );
     f = NULL;
     return TRUE;
@@ -626,32 +816,129 @@ gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, gshort file_ty
   return FALSE;
 }
 
-const gchar *a_get_viking_dir()
+/**
+ * Just a wrapper around realpath, which itself is platform dependent
+ */
+char *file_realpath ( const char *path, char *real )
 {
-  static gchar *viking_dir = NULL;
+  return realpath ( path, real );
+}
+
+/**
+ * Permission granted to use this code after personal correspondance
+ * Slightly reworked for better cross platform use, glibisms, function rename and a compacter format
+ *
+ * FROM http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263
+ */
 
-  // TODO: use g_get_user_config_dir ?
+// GetRelativeFilename(), by Rob Fisher.
+// rfisher@iee.org
+// http://come.to/robfisher
 
-  if (!viking_dir) {
-    const gchar *home = g_getenv("HOME");
-    if (!home || g_access(home, W_OK))
-      home = g_get_home_dir ();
-#ifdef HAVE_MKDTEMP
-    if (!home || g_access(home, W_OK))
-    {
-      static gchar temp[] = {"/tmp/vikXXXXXX"};
-      home = mkdtemp(temp);
-    }
+// defines
+#ifndef MAXPATHLEN
+#define MAXPATHLEN 1024
 #endif
-    if (!home || g_access(home, W_OK))
-      /* Fatal error */
-      g_critical("Unable to find a base directory");
-
-    /* Build the name of the directory */
-    viking_dir = g_build_filename(home, ".viking", NULL);
-    if (g_file_test(viking_dir, G_FILE_TEST_EXISTS) == FALSE)
-      g_mkdir(viking_dir, 0755);
+// The number of characters at the start of an absolute filename.  e.g. in DOS,
+// absolute filenames start with "X:\" so this value should be 3, in UNIX they start
+// with "\" so this value should be 1.
+#ifdef WINDOWS
+#define ABSOLUTE_NAME_START 3
+#else
+#define ABSOLUTE_NAME_START 1
+#endif
+
+// Given the absolute current directory and an absolute file name, returns a relative file name.
+// For example, if the current directory is C:\foo\bar and the filename C:\foo\whee\text.txt is given,
+// GetRelativeFilename will return ..\whee\text.txt.
+
+const gchar *file_GetRelativeFilename ( gchar *currentDirectory, gchar *absoluteFilename )
+{
+  gint afMarker = 0, rfMarker = 0;
+  gint cdLen = 0, afLen = 0;
+  gint i = 0;
+  gint levels = 0;
+  static gchar relativeFilename[MAXPATHLEN+1];
+
+  cdLen = strlen(currentDirectory);
+  afLen = strlen(absoluteFilename);
+
+  // make sure the names are not too long or too short
+  if (cdLen > MAXPATHLEN || cdLen < ABSOLUTE_NAME_START+1 ||
+      afLen > MAXPATHLEN || afLen < ABSOLUTE_NAME_START+1) {
+    return NULL;
   }
 
-  return viking_dir;
+  // Handle DOS names that are on different drives:
+  if (currentDirectory[0] != absoluteFilename[0]) {
+    // not on the same drive, so only absolute filename will do
+    strcpy(relativeFilename, absoluteFilename);
+    return relativeFilename;
+  }
+
+  // they are on the same drive, find out how much of the current directory
+  // is in the absolute filename
+  i = ABSOLUTE_NAME_START;
+  while (i < afLen && i < cdLen && currentDirectory[i] == absoluteFilename[i]) {
+    i++;
+  }
+
+  if (i == cdLen && (absoluteFilename[i] == G_DIR_SEPARATOR || absoluteFilename[i-1] == G_DIR_SEPARATOR)) {
+    // the whole current directory name is in the file name,
+    // so we just trim off the current directory name to get the
+    // current file name.
+    if (absoluteFilename[i] == G_DIR_SEPARATOR) {
+      // a directory name might have a trailing slash but a relative
+      // file name should not have a leading one...
+      i++;
+    }
+
+    strcpy(relativeFilename, &absoluteFilename[i]);
+    return relativeFilename;
+  }
+
+  // The file is not in a child directory of the current directory, so we
+  // need to step back the appropriate number of parent directories by
+  // using "..\"s.  First find out how many levels deeper we are than the
+  // common directory
+  afMarker = i;
+  levels = 1;
+
+  // count the number of directory levels we have to go up to get to the
+  // common directory
+  while (i < cdLen) {
+    i++;
+    if (currentDirectory[i] == G_DIR_SEPARATOR) {
+      // make sure it's not a trailing slash
+      i++;
+      if (currentDirectory[i] != '\0') {
+       levels++;
+      }
+    }
+  }
+
+  // move the absolute filename marker back to the start of the directory name
+  // that it has stopped in.
+  while (afMarker > 0 && absoluteFilename[afMarker-1] != G_DIR_SEPARATOR) {
+    afMarker--;
+  }
+
+  // check that the result will not be too long
+  if (levels * 3 + afLen - afMarker > MAXPATHLEN) {
+    return NULL;
+  }
+
+  // add the appropriate number of "..\"s.
+  rfMarker = 0;
+  for (i = 0; i < levels; i++) {
+    relativeFilename[rfMarker++] = '.';
+    relativeFilename[rfMarker++] = '.';
+    relativeFilename[rfMarker++] = G_DIR_SEPARATOR;
+  }
+
+  // copy the rest of the filename into the result string
+  strcpy(&relativeFilename[rfMarker], &absoluteFilename[afMarker]);
+
+  return relativeFilename;
 }
+/* END http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263 */