/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/

#include "visu_basic.h"
#include "visu_extension.h"
#include "visu_dataatomic.h"
#include "visu_dataspin.h"
#include "visu_elements.h"
#include "visu_commandLine.h"
#include "visu_plugins.h"
#include "opengl.h"
#include "dumpModules/fileDump.h"
#include "dumpModules/glDump.h"
#include "visu_pairset.h"
#include "visu_tools.h"
#include "visu_configFile.h"
#include "extraFunctions/plane.h"
#include "extraFunctions/pot2surf.h"
#include "extraFunctions/map.h"
#include "extraFunctions/surfaces_resources.h"
#include "extraFunctions/sfielddata.h"
#include "extraFunctions/scalarFieldSet.h"
#include "openGLFunctions/objectList.h"
#include "openGLFunctions/text.h"
#include "openGLFunctions/interactive.h"
#include "OSOpenGL/visu_openGL.h"
#include "extensions/fogAndBGColor.h"
#include "extensions/scale.h"
#include "extensions/marks.h"
#include "extensions/axes.h"
#include "extensions/box.h"
#include "extensions/box_legend.h"
#include "extensions/legend.h"
#include "extensions/pairs.h"
#include "extensions/shade.h"
#include "extensions/node_vectors.h"
#include "extensions/planes.h"
#include "extensions/surfs.h"
#include "extensions/maps.h"
#include "extensions/forces.h"
#include "extensions/geodiff.h"
#include "extensions/paths.h"
#include "coreTools/toolConfigFile.h"
#include "extraFunctions/geometry.h"
#include "renderingMethods/elementAtomic.h"
#include "renderingMethods/elementSpin.h"
#include "renderingMethods/spinMethod.h"

#include <stdio.h>
#include <locale.h>
#include <unistd.h> /* For the access markers R_OK, W_OK ... */
#include <string.h>
#include <stdlib.h>

/**
 * SECTION:visu_basic
 * @short_description: Main functions of V_Sim (except graphical
 * ones).
 *
 * <para>There are here the main functions of V_Sim (except for
 * graphical methods) such as open file.</para>
 */

#if SYSTEM_X11 == 1
#define V_SIM_DATA_DIR_DEFAULT    "/usr/local/share/v_sim"
#define V_SIM_LEGAL_DIR_DEFAULT   "/usr/local/share/v_sim"
#define V_SIM_PIXMAPS_DIR_DEFAULT "/usr/local/share/v_sim/pixmaps"
#define V_SIM_ICONS_DIR_DEFAULT   "/usr/local/share/icons"
#define V_SIM_PLUGINS_DIR_DEFAULT "/usr/local/lib/v_sim/plug-ins"
#define V_SIM_LOCALE_DIR_DEFAULT  "/usr/local/share/locale"
#endif
#if SYSTEM_WIN32 == 1
#define V_SIM_DATA_DIR_DEFAULT    "C:\\PROGRAM FILES\\V_Sim\\share\\v_sim"
#define V_SIM_LEGAL_DIR_DEFAULT   "C:\\PROGRAM FILES\\V_Sim\\share\\doc\\v_sim"
#define V_SIM_PIXMAPS_DIR_DEFAULT "C:\\PROGRAM FILES\\V_Sim\\share\\v_sim\\pixmaps"
#define V_SIM_ICONS_DIR_DEFAULT   "C:\\PROGRAM FILES\\V_Sim\\share\\icons"
#define V_SIM_PLUGINS_DIR_DEFAULT "C:\\PROGRAM FILES\\V_Sim\\lib\\v_sim\\plug-ins"
#define V_SIM_LOCALE_DIR_DEFAULT  "C:\\PROGRAM FILES\\V_Sim\\share\\locale"
#endif
static gchar *exeLocation = NULL;
static gchar *v_sim_data_dir = NULL;
static gchar *v_sim_legal_dir = NULL;
static gchar *v_sim_pixmaps_dir = NULL;
static gchar *v_sim_icons_dir = NULL;
static gchar *v_sim_local_conf_dir = NULL;
static gchar *v_sim_old_local_conf_dir = NULL;
static gchar *v_sim_plugins_dir = NULL;
static gchar *v_sim_locale_dir = NULL;
static ToolUnits preferedUnit;

/* Local methods. */
static gboolean dumpData(gpointer data);
static gboolean _toUnit(const gchar *label, ToolUnits *unit);

#define FLAG_PARAMETER_UNIT   "main_unit"
#define DESC_PARAMETER_UNIT   "Define the prefered unit to display files ; string"
static void exportParameters(GString *data, VisuData *dataObj);

static void _notNull(const GValue *from, GValue *to)
{
  g_value_set_boolean(to, (g_value_get_object(from) != NULL));
}
static void _notNullBoxed(const GValue *from, GValue *to)
{
  g_value_set_boolean(to, (g_value_get_boxed(from) != NULL));
}
/**
 * visu_basic_init:
 *
 * A call to this method is done at startup after having probe the locale of the file
 * system and having initialized the rendering window. It makes the following actions :
 * create the visu object to store the signals, initialize the module part (parameters,
 * and resources), initialize the dump part, the OpenGL part and its extensions, the
 * storage of elements and the 'colorize with data' part.
 */
void visu_basic_init(void)
{
  static gboolean done = FALSE;
  VisuConfigFileEntry *entry;

  if (done)
    return;

  DBG_fprintf(stderr,"--- Initialising variables ---\n");
  /* We want to read . as floating point separator : in french it is , */
  setlocale(LC_NUMERIC, "C");
  tool_matrix_init();
  tool_shade_get_type();
  preferedUnit = TOOL_UNITS_UNDEFINED;

  /* Force the creation of the main object class. */
  g_type_class_ref(VISU_TYPE_CONFIG_FILE);

  /* initialise OpenGL. */
  DBG_fprintf(stderr,"--- Initialising OpenGL ---\n");
  g_type_class_ref(VISU_TYPE_GL);
  g_type_class_ref(VISU_TYPE_GL_VIEW);
  g_type_class_ref(VISU_TYPE_GL_NODE_SCENE);
  g_type_class_ref(VISU_TYPE_INTERACTIVE);

  /* Initialise extra functions. */
  DBG_fprintf(stderr,"--- Initialising extra functions ---\n");
  g_type_class_ref(VISU_TYPE_SURFACE);
  g_type_class_ref(VISU_TYPE_SURFACE_RESOURCE);
  g_type_class_ref(VISU_TYPE_SCALAR_FIELD);
  g_type_class_ref(VISU_TYPE_SCALAR_FIELD_DATA);
  g_type_class_ref(VISU_TYPE_COLORIZATION);
  g_type_class_ref(VISU_TYPE_MAP);

  /* Force the creation of some internal classes. */
  DBG_fprintf(stderr,"--- Initialising internal classes ---\n");
  g_type_class_ref(VISU_TYPE_PAIR_LINK);
  g_type_class_ref(VISU_TYPE_ELEMENT_ATOMIC);
  g_type_class_ref(VISU_TYPE_GL_EXT_SET);
  g_type_class_ref(VISU_TYPE_GL_EXT);
  g_type_class_ref(VISU_TYPE_GL_EXT_AXES);
  g_type_class_ref(VISU_TYPE_GL_EXT_BOX);
  g_type_class_ref(VISU_TYPE_GL_EXT_BOX_LEGEND);
  g_type_class_ref(VISU_TYPE_GL_EXT_LEGEND);
  g_type_class_ref(VISU_TYPE_GL_EXT_PAIRS);
  g_type_class_ref(VISU_TYPE_GL_EXT_PLANES);
  g_type_class_ref(VISU_TYPE_GL_EXT_SURFACES);
  g_type_class_ref(VISU_TYPE_GL_EXT_BG);
  g_type_class_ref(VISU_TYPE_GL_EXT_MARKS);
  g_type_class_ref(VISU_TYPE_GL_EXT_NODE_VECTORS);
  g_type_class_ref(VISU_TYPE_GL_EXT_INFOS);
  g_type_class_ref(VISU_TYPE_GL_EXT_SCALE);
  g_type_class_ref(VISU_TYPE_GL_EXT_FORCES);
  g_type_class_ref(VISU_TYPE_GL_EXT_GEODIFF);
  g_type_class_ref(VISU_TYPE_GL_EXT_PATHS);
  g_type_class_ref(VISU_TYPE_ELEMENT);
  g_type_class_ref(VISU_TYPE_DATA_ATOMIC);
  g_type_class_ref(VISU_TYPE_DATA_SPIN);
  g_type_class_ref(VISU_TYPE_METHOD_SPIN);

  visu_config_file_ignoreEntry(VISU_CONFIG_FILE_PARAMETER,
                               "rendering_favoriteMethod", 1);
  entry = visu_config_file_addEnumEntry(VISU_CONFIG_FILE_PARAMETER,
                                        FLAG_PARAMETER_UNIT,
                                        DESC_PARAMETER_UNIT,
                                        &preferedUnit, _toUnit, FALSE);
  visu_config_file_entry_setVersion(entry, 3.5f);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_PARAMETER,
                                     exportParameters);

  g_value_register_transform_func(G_TYPE_BOXED, G_TYPE_BOOLEAN, _notNullBoxed);
  g_value_register_transform_func(G_TYPE_OBJECT, G_TYPE_BOOLEAN, _notNull);
  g_value_register_transform_func(VISU_TYPE_POINTSET, G_TYPE_BOOLEAN, _notNull);

  done = TRUE;
}

/**
 * visu_basic_parseConfigFiles:
 * @error: location for an error.
 * 
 * Parse the parameter and the resource file. Used once at startup.
 *
 * Returns: a newly allocated #GString if some error occured.
 */
gboolean visu_basic_parseConfigFiles(GError **error)
{
  char* path;
  gboolean res;
  char *resFile;

  if (!g_type_class_peek(VISU_TYPE_CONFIG_FILE))
    visu_basic_init();

  DBG_fprintf(stderr,"--- Initialising the parameters ---\n");
  /* Look for parameters file */
  path = visu_config_file_getValidPath(VISU_CONFIG_FILE_PARAMETER, R_OK, 0);
  if (path)
    {
      res = visu_config_file_load(VISU_CONFIG_FILE_PARAMETER, path, error);
      g_free(path);
      if (!res)
        return FALSE;
    }

  DBG_fprintf(stderr,"--- Initialising resources ---\n");
  /* Look for resources file */
  resFile = commandLineGet_resourcesFile();
  if (!resFile)
    path = visu_config_file_getValidPath(VISU_CONFIG_FILE_RESOURCE, R_OK, 0);
  else
    path = g_strdup(resFile);
  if (path)
    {
      res = visu_config_file_load(VISU_CONFIG_FILE_RESOURCE, path, error);
      g_free(path);
      if (!res)
        return FALSE;
    }

  /* Overload with commandline options. */
  res = visu_config_file_loadCommandLine(error);
  if (!res)
    return FALSE;

  return TRUE;
}

/**
 * visu_basic_initConfigFiles:
 * @error: an error location.
 *
 * Same as visu_basic_parseConfigFiles(), but perform the operation
 * only once.
 *
 * Since: 3.8
 **/
void visu_basic_initConfigFiles(GError **error)
{
  static gboolean done = FALSE;

  if (done)
    return;

  visu_basic_parseConfigFiles(error);
  done = TRUE;
}

struct _dump
{
  GMainLoop *loop;

  VisuDump *format;
  gchar *exportFileName;

  VisuDataLoadable *dataObj;

  /* Return. */
  int status;
};

/**
 * visu_basic_mainExport:
 *
 * This method is called when V_Sim is in export mode from the command line. 
 *
 * Returns: 0 if everything is normal, 1 if an error occured.
 */
int visu_basic_mainExport(void)
{
  GError *error;
  gboolean res;
  struct _dump dt;
  GList *pnt;
  GHashTable *opts;
  ToolOption *id;
  VisuGlNodeScene *scene;
  guint width, height;

  dt.exportFileName = commandLineGet_ExportFileName();
  if (!dt.exportFileName)
    {
      g_error("This method should be called with"
	      " an argument that is the file name to export to.\n");
    }
  
  id = (ToolOption*)0;
  opts = commandLineGet_options();
  if (opts)
    id = (ToolOption*)g_hash_table_lookup(opts, "fileFormatId");
  pnt = visu_dump_pool_getAllModules();
  if (!id)
    while (pnt && !tool_file_format_match(TOOL_FILE_FORMAT(pnt->data), dt.exportFileName))
      pnt = g_list_next(pnt);
  else
    pnt = g_list_nth(pnt, g_value_get_int(tool_option_getValue(id)) - 1);
  if (!pnt)
    {
      g_warning(_("The format can't be found from the"
                  " filename '%s' entered.\n"), dt.exportFileName);
      g_print(_("Use -o fileFormatId=id to specify a file format"
                " when the autodetection fails. Get a list of ids"
                " with option -o list:\n\n"));
      visu_basic_showOptionHelp(TRUE);
      return 1;
    }
  dt.format = VISU_DUMP(pnt->data);

  /* We transfer some options to file format. */
  tool_file_format_setPropertiesFromCLI(TOOL_FILE_FORMAT(dt.format));

#if ! GLIB_CHECK_VERSION(2, 36, 0)
  g_type_init();
#endif

  visu_basic_init();

  dt.dataObj = visu_data_loadable_new_fromCLI();
  if (!dt.dataObj)
    {
      g_error(_("a file to render is mandatory with the '--export' option."));
    }
  
  error = (GError*)0;
  if (VISU_IS_DUMP_SCENE(dt.format) &&
      !visu_basic_parseConfigFiles(&error))
    {
      g_warning("%s", error->message);
      g_error_free(error);
    }

  error = (GError*)0;
  res = visu_data_loadable_load(dt.dataObj, 0, (GCancellable*)0, &error);
  if (!res)
    {
      g_object_unref(dt.dataObj);
      g_error("%s", (error)?error->message:"No error message!");
    }

  dt.status = 0;
  if (VISU_IS_DUMP_SCENE(dt.format))
    {
      DBG_fprintf(stderr, "Visu Basic: begin dump exportation.\n");
      scene = visu_gl_node_scene_new();
      visu_gl_node_scene_setData(scene, VISU_DATA(dt.dataObj));

      error = (GError*)0;
      if (!visu_gl_node_scene_applyCLI(scene, &error))
        dt.status = 1;
      else
        {
          DBG_fprintf(stderr, "Visu Basic: adding the load call back in the queue.\n");
          /* Start the elements related to the main loop. */
          dt.loop = g_main_loop_new(NULL, FALSE);
          g_idle_add_full(G_PRIORITY_LOW + 100, dumpData, (gpointer)&dt, NULL);
          g_main_loop_run(dt.loop);
      
          DBG_fprintf(stderr, "Visu Basic: calling exportation routine.\n");
          commandLineGet_XWindowGeometry((int*)&width, (int*)&height);
          error = (GError*)0;
          if (!visu_gl_node_scene_dump(scene, dt.format, dt.exportFileName,
                                       width, height,
                                       (ToolVoidDataFunc)0, (gpointer)0, &error))
            dt.status = 1;
        }
      g_object_unref(scene);
    }
  else
    {
      error = (GError*)0;
      if (!visu_data_applyTransformationsFromCLI(VISU_DATA(dt.dataObj), &error))
        dt.status = 1;
      /* Direct export. */
      else if (!visu_dump_data_write(VISU_DUMP_DATA(dt.format), dt.exportFileName,
                                VISU_DATA(dt.dataObj), &error))
        dt.status = 1;
    }
  if (error)
    {
      g_warning("%s", error->message);
      g_error_free(error);
    }

  g_object_unref(dt.dataObj);

  return dt.status;
}

static gboolean dumpData(gpointer data)
{
  struct _dump *dt = (struct _dump*)data;

  DBG_fprintf(stderr, "Visu Basic: stopping the main loop.\n");
  g_main_loop_quit(dt->loop);

  return FALSE;
}

/**
 * visu_basic_showOptionHelp:
 * @force: a boolean.
 *
 * Display a small help for some options. The output is different from
 * the -h command line options, here some details about running time
 * options is displayed like the available file format for
 * exportation... If @force is TRUE, all possible values are output,
 * otherwise only those relevant to the user provided command line
 * options.
 *
 * Since: 3.6
 *
 * Returns: TRUE if something is displayed.
 */
gboolean visu_basic_showOptionHelp(gboolean force)
{
  ToolFileFormatIter iter;
  GList *pnt;
  GHashTable *opts;
  ToolFileFormat *format;
  guint i;

  if (!force)
    {
      opts = commandLineGet_options();
      if (!opts || !g_hash_table_lookup(opts, "list"))
        return FALSE;
    }

  i = 1;
  for (pnt = visu_dump_pool_getAllModules(); pnt; pnt = g_list_next(pnt))
    {
      format = TOOL_FILE_FORMAT(pnt->data);
      fprintf(stdout, _("\n#%2d - exportation file format '%s':\n"),
              i++, tool_file_format_getName(format));
      iter.lst = (GList*)0;
      for (tool_file_format_iterNextProperty(format, &iter); iter.lst;
           tool_file_format_iterNextProperty(format, &iter))
	{
	  fprintf(stdout, " - '%25s'", iter.name);
	  switch (G_VALUE_TYPE(iter.val))
	    {
	    case G_TYPE_INT:
	      fprintf(stdout, " %10s (%5d): ", _("integer"), g_value_get_int(iter.val));
	      break;
	    case G_TYPE_BOOLEAN:
	      fprintf(stdout, " %10s (%5d): ", _("boolean"), g_value_get_boolean(iter.val));
	      break;
	    case G_TYPE_STRING:
	      fprintf(stdout, " %10s: ", _("string"));
	      break;
	    default:
              g_warning("Unknown type for file format property.");
	      break;
	    }
	  fprintf(stdout, "%s.\n", iter.label);
	}
      tool_file_format_iterNextProperty(format, &iter);
      if (!iter.lst)
	fprintf(stdout, _("No option for this file format.\n"));
    }
  i = 1;
  for (pnt = visu_data_atomic_class_getLoaders(); pnt; pnt = g_list_next(pnt))
    {
      format = TOOL_FILE_FORMAT(pnt->data);
      fprintf(stdout, _("\n#%2d - input file format '%s':\n"),
              i++, tool_file_format_getName(format));
      iter.lst = (GList*)0;
      for (tool_file_format_iterNextProperty(format, &iter); iter.lst;
           tool_file_format_iterNextProperty(format, &iter))
	{
	  fprintf(stdout, " - '%25s'", iter.name);
	  switch (G_VALUE_TYPE(iter.val))
	    {
	    case G_TYPE_INT:
	      fprintf(stdout, " %10s (%5d): ", _("integer"), g_value_get_int(iter.val));
	      break;
	    case G_TYPE_BOOLEAN:
	      fprintf(stdout, " %10s (%5d): ", _("boolean"), g_value_get_boolean(iter.val));
	      break;
	    case G_TYPE_STRING:
	      fprintf(stdout, " %10s: ", _("string"));
	      break;
	    default:
              g_warning("Unknown type for file format property.");
	      break;
	    }
	  fprintf(stdout, "%s.\n", iter.label);
	}
      tool_file_format_iterNextProperty(format, &iter);
      if (!iter.lst)
	fprintf(stdout, _("No option for this file format.\n"));
    }

  return TRUE;
}

static gchar* setDir(const gchar* const *sysDirs, const gchar *prefix,
		     const gchar* subDir, const gchar* defaultDir)
{
  gchar *dir;
  int i;

  dir = g_build_filename(prefix, subDir, NULL);
  if (!g_file_test(dir, G_FILE_TEST_IS_DIR))
    {
      g_free(dir);
      dir = (gchar*)0;
      /* We try the XDG stuff. */
      for (i = 0; sysDirs[i]; i++)
	{
	  dir = g_build_filename(sysDirs[i], subDir, NULL);
	  if (g_file_test(dir, G_FILE_TEST_IS_DIR))
	    break;
	  else
	    g_free(dir);
	  dir = (gchar*)0;
	}
    }
  if (!dir)
    dir = g_strdup(defaultDir);
  return dir;
}

/**
 * visu_basic_setExePath:
 * @exePath: a path where the V_Sim executable is running in.
 *
 * This method is used to tell V_Sim where V_Sim is running (usually
 * reading from argv[0]. This makes it possible to relocate everything
 * on the fly. @exePath is copied.
 *
 * Since: 3.6
 */
void visu_basic_setExePath(const gchar *exePath)
{
  if (exeLocation)
    g_free(exeLocation);

  exeLocation = g_strdup(exePath);
}
/**
 * setVisuPaths:
 * 
 * This method sets the paths. On Unix systems, this method sets the paths
 * from macros defined by configure. On Win32 systems, it reads paths in
 * a v_sim.ini file found in the current directory or in the C:\windows.
 */
static void setVisuPaths(void)
{
#if SYSTEM_WIN32 == 1
  #define V_SIM_INI_FILE PACKAGE".ini"
  GIOChannel *iniFile;
  gchar *iniPath, *tmp, *me, *prefix;
  gchar *buffer, *line;
  GIOStatus res;
  GError *err;
  gchar **tokens;
  gsize length;

  if (!exeLocation)
    exeLocation = g_strdup(PACKAGE_TARNAME);

  v_sim_data_dir    = g_strdup(V_SIM_DATA_DIR_DEFAULT);
  v_sim_legal_dir   = g_strdup(V_SIM_LEGAL_DIR_DEFAULT);
  v_sim_pixmaps_dir = g_strdup(V_SIM_PIXMAPS_DIR_DEFAULT);
  v_sim_icons_dir   = g_strdup(V_SIM_ICONS_DIR_DEFAULT);
  v_sim_plugins_dir = g_strdup(V_SIM_PLUGINS_DIR_DEFAULT);
  v_sim_locale_dir  = g_strdup(V_SIM_LOCALE_DIR_DEFAULT);
  iniPath = g_strdup(V_SIM_INI_FILE);
  /* Try to find the INI file from cwd. */
  prefix = (gchar*)0;
  iniFile = g_io_channel_new_file(iniPath, "r", (GError**)0);
  if (iniFile)
    prefix = g_get_current_dir();
  /* Try to find the INI file from the name of the executable. */
  if (!iniFile)
    {
      g_free(iniPath);

      if (g_file_test(exeLocation, G_FILE_TEST_IS_SYMLINK))
	tmp = g_file_read_link(exeLocation, (GError**)0);
      else
	tmp = g_strdup(exeLocation);
      me = tool_path_normalize(tmp);
      g_free(tmp);
    
      DBG_fprintf(stderr, "Visu Basic: running program is '%s'.\n", me);
      /* From the location of the executable, we take the base dir. */
      prefix = g_path_get_dirname(me);
      g_free(me);

      iniPath = g_build_filename(prefix, V_SIM_INI_FILE, NULL);
      iniFile = g_io_channel_new_file(iniPath, "r", (GError**)0);
    }  
  /* Try to find the INI file in the Windows directory. */
  if (!iniFile)
    {
      g_free(iniPath);
      prefix = g_strdup("C:\\WINDOWS");
      iniPath = g_build_filename(prefix, V_SIM_INI_FILE, NULL);
      iniFile = g_io_channel_new_file(iniPath, "r", (GError**)0);
    }
  if (iniFile)
    {
      buffer = (gchar*)0;
      err = (GError*)0;
      do
	{
	  res = g_io_channel_read_line(iniFile, &line, &length, NULL, &err);
	  if (line && res == G_IO_STATUS_NORMAL)
	    {
	      tokens = g_strsplit(line, "=", 2);
	      if (!strcmp(g_strstrip(tokens[0]), "data_dir") && tokens[1])
		{
		  g_free(v_sim_data_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_data_dir = g_strdup(tmp);
		  else
		    v_sim_data_dir = g_build_filename(prefix, tmp, NULL);
		}
	      if (!strcmp(g_strstrip(tokens[0]), "legal_dir") && tokens[1])
		{
		  g_free(v_sim_legal_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_legal_dir = g_strdup(tmp);
		  else
		    v_sim_legal_dir = g_build_filename(prefix, tmp, NULL);
		}
	      if (!strcmp(g_strstrip(tokens[0]), "pixmaps_dir") && tokens[1])
		{
		  g_free(v_sim_pixmaps_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_pixmaps_dir = g_strdup(tmp);
		  else
		    v_sim_pixmaps_dir = g_build_filename(prefix, tmp, NULL);
		}
	      if (!strcmp(g_strstrip(tokens[0]), "icons_dir") && tokens[1])
		{
		  g_free(v_sim_icons_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_icons_dir = g_strdup(tmp);
		  else
		    v_sim_icons_dir = g_build_filename(prefix, tmp, NULL);
		}
	      if (!strcmp(g_strstrip(tokens[0]), "plugins_dir") && tokens[1])
		{
		  g_free(v_sim_plugins_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_plugins_dir = g_strdup(tmp);
		  else
		    v_sim_plugins_dir = g_build_filename(prefix, tmp, NULL);
		}
	      if (!strcmp(g_strstrip(tokens[0]), "locale_dir") && tokens[1])
		{
		  g_free(v_sim_locale_dir);
		  tmp = g_strstrip(tokens[1]);
		  if (g_path_is_absolute(tmp))
		    v_sim_locale_dir = g_strdup(tmp);
		  else
		    v_sim_locale_dir = g_build_filename(prefix, tmp, NULL);
		}
	      g_strfreev(tokens);
	      g_free(line);
	    }
	}
      while (res != G_IO_STATUS_EOF);
      g_io_channel_shutdown (iniFile, FALSE, (GError**)0);
      g_io_channel_unref (iniFile);
    }
  g_free(iniPath);
#endif

#if SYSTEM_X11 == 1
  const gchar* const *sysDirs;
  gchar *me, *prefix, *tmp;
#if DEBUG == 1
  int i;
#endif

  /* We try to get the dirs from XDG specs, otherwise we fall back to
     hard coded values at compilation time. */
#if GLIB_MINOR_VERSION > 5
  sysDirs = g_get_system_data_dirs();
#if DEBUG == 1
  fprintf(stderr, "Visu Basic: available data dirs:\n");
  for (i = 0; sysDirs[i]; i++)
    fprintf(stderr, " | '%s'.\n", sysDirs[i]);
#endif
#else
  sysDirs = g_malloc(sizeof(const gchar*));
  sysDirs[0] = (const gchar*)0;
#endif

  if (!exeLocation)
    exeLocation = g_strdup(PACKAGE_TARNAME);
  if (g_file_test(exeLocation, G_FILE_TEST_IS_SYMLINK))
    tmp = g_file_read_link(exeLocation, (GError**)0);
  else
    tmp = g_strdup(exeLocation);
  me = tool_path_normalize(tmp);
  g_free(tmp);
    
  DBG_fprintf(stderr, "Visu Basic: running program is '%s'.\n", me);
  /* From the location of the executable, we take the base dir
     or its parents if the basedir is bin. */
  prefix = g_path_get_dirname(me);
  g_free(me);
  me = g_path_get_basename(prefix);
  if (!strcmp(me, "bin"))
    {
      g_free(me);
      me = prefix;
      prefix = g_path_get_dirname(me);
    }
  g_free(me);
  DBG_fprintf(stderr, " | prefix is '%s'.\n", prefix);

  v_sim_data_dir = setDir(sysDirs, prefix, "share/" PACKAGE, DATA_DIR);
  v_sim_legal_dir = setDir(sysDirs, prefix, "share/doc/" PACKAGE, LEGAL_DIR);
  v_sim_pixmaps_dir = setDir(sysDirs, prefix, "share/" PACKAGE "/pixmaps", PIXMAPS_DIR);
  v_sim_icons_dir = setDir(sysDirs, prefix, "share/icons", ICONS_DIR);
  v_sim_plugins_dir = setDir(sysDirs, prefix, "lib/" PACKAGE "/plug-ins", PLUGINS_DIR);
  v_sim_locale_dir = setDir(sysDirs, prefix, "share/locale", LOCALE_DIR);

  g_free(prefix);
#endif

  /* Create the local dirs. */
#if GLIB_MINOR_VERSION > 5
  v_sim_local_conf_dir = g_build_filename(g_get_user_config_dir(), "v_sim", NULL);
#else
  v_sim_local_conf_dir = g_build_filename(g_get_home_dir(), ".config/v_sim", NULL);
#endif
  if (!v_sim_local_conf_dir)
    g_warning("WARNING! Impossible to get the default"
	      " path $XDG_CONFIG_HOME/v_sim.\n");
  v_sim_old_local_conf_dir = g_build_filename(g_get_home_dir(), ".v_sim", NULL);

  DBG_fprintf(stderr, "Visu Basic: data directory      : '%s'.\n", v_sim_data_dir);
  DBG_fprintf(stderr, "Visu Basic: local conf directory: '%s'.\n", v_sim_local_conf_dir);
  DBG_fprintf(stderr, "Visu Basic: legal directory     : '%s'.\n", v_sim_legal_dir);
  DBG_fprintf(stderr, "Visu Basic: pixmaps directory   : '%s'.\n", v_sim_pixmaps_dir);
  DBG_fprintf(stderr, "Visu Basic: icons directory     : '%s'.\n", v_sim_icons_dir);
  DBG_fprintf(stderr, "Visu Basic: plug-ins directory  : '%s'.\n", v_sim_plugins_dir);
  DBG_fprintf(stderr, "Visu Basic: locale directory    : '%s'.\n", v_sim_locale_dir);
}
/**
 * visu_basic_getDataDir:
 *
 * Get the static string where V_Sim looks for its data files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getDataDir(void)
{
  if (!v_sim_data_dir)
    setVisuPaths();

  return v_sim_data_dir;
}
/**
 * visu_basic_getLegalDir:
 *
 * Get the static string where V_Sim looks for its legal files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getLegalDir(void)
{
  if (!v_sim_legal_dir)
    setVisuPaths();

  return v_sim_legal_dir;
}
/**
 * visu_basic_getPixmapsDir:
 *
 * Get the static string where V_Sim looks for its pixmap files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getPixmapsDir(void)
{
  if (!v_sim_pixmaps_dir)
    setVisuPaths();

  return v_sim_pixmaps_dir;
}
/**
 * visu_basic_getIconsDir:
 *
 * Get the static string where V_Sim looks for its icon files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getIconsDir(void)
{
  if (!v_sim_icons_dir)
    setVisuPaths();

  return v_sim_icons_dir;
}
/**
 * visu_basic_getLocalDir:
 *
 * Get the static string where V_Sim looks for its user configuration files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getLocalDir(void)
{
  if (!v_sim_local_conf_dir)
    setVisuPaths();

  return v_sim_local_conf_dir;
}
/**
 * visu_basic_getOldLocalDir:
 *
 * Get the static string where V_Sim looks for its user configuration
 * files (old location).
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getOldLocalDir(void)
{
  if (!v_sim_old_local_conf_dir)
    setVisuPaths();

  return v_sim_old_local_conf_dir;
}
/**
 * visu_basic_getPluginsDir:
 *
 * Get the static string where V_Sim looks for its plug-in files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getPluginsDir(void)
{
  if (!v_sim_plugins_dir)
    setVisuPaths();

  return v_sim_plugins_dir;
}
/**
 * visu_basic_getLocaleDir:
 *
 * Get the static string where V_Sim looks for its localisation files.
 *
 * Since: 3.4
 *
 * Returns: (transfer none): a string owned by V_Sim.
 */
const gchar* visu_basic_getLocaleDir(void)
{
  if (!v_sim_locale_dir)
    setVisuPaths();

  return v_sim_locale_dir;
}
/**
 * visu_basic_freeAll:
 *
 * This routine is called by V_Sim when quiting and it frees the memory
 * used by visu_basic.
 *
 * Since: 3.5
 */
void visu_basic_freeAll(void)
{
  DBG_fprintf(stderr, "Visu Basic: free all.\n - the paths\n");
  g_free(v_sim_data_dir);
  g_free(v_sim_legal_dir);
  g_free(v_sim_pixmaps_dir);
  g_free(v_sim_plugins_dir);
  g_free(v_sim_locale_dir);
  g_free(v_sim_local_conf_dir);
  g_free(v_sim_old_local_conf_dir);

  DBG_fprintf(stderr, " - the color storage\n");
  g_object_unref(tool_color_getStorage());
  g_object_unref(tool_shade_getStorage());

  visu_surface_resource_pool_finalize();
  visu_scalar_field_method_class_finalize();
  visu_scalarfield_set_class_finalize();

  visu_dump_pool_finalize();
  visu_pair_pool_finalize();
  visu_element_renderer_pool_finalize();
  visu_element_atomic_pool_finalize();
  visu_element_spin_pool_finalize();
  visu_element_pool_finalize();
  g_object_unref(visu_method_spin_getDefault());
  
  visu_data_atomic_class_finalize();
  visu_data_spin_class_finalize();

  g_object_unref(VISU_CONFIG_FILE_RESOURCE);
  g_object_unref(VISU_CONFIG_FILE_PARAMETER);

  visu_plugins_free();
  
#if DEBUG == 1
  tool_dbg_obj_class_summarize();
#endif
}
/**
 * visu_basic_getMainContext:
 *
 * Even without GUI, V_Sim requires to run a main loop. This method is
 * to get the main loop.
 *
 * Since: 3.6
 *
 * Returns: (transfer none): the main loop, as defined in GLib.
 */
GMainContext* visu_basic_getMainContext(void)
{
  return g_main_context_default();
}


/* Resources. */
/**
 * visu_basic_getPreferedUnit:
 *
 * By setting the prefered unit, when a file is load, V_Sim tries to
 * render it in this prefered unit.
 *
 * Since: 3.5
 *
 * Returns: the prefered unit set by the user (default is
 * #TOOL_UNITS_UNDEFINED).
 */
ToolUnits visu_basic_getPreferedUnit(void)
{
  return preferedUnit;
}
/**
 * visu_basic_setPreferedUnit:
 * @unit: a #ToolUnits value.
 *
 * By setting the prefered unit, when a file is load, V_Sim tries to
 * render it in this prefered unit.
 *
 * Since: 3.5
 *
 * Returns: TRUE if the prefered unit is actually changed.
 */
gboolean visu_basic_setPreferedUnit(ToolUnits unit)
{
  if (unit == preferedUnit)
    return FALSE;

  preferedUnit = unit;
  return TRUE;
}
static gboolean _toUnit(const gchar *label, ToolUnits *unit)
{
  ToolUnits val;

  val = tool_physic_getUnitFromName(label);
  if (val != TOOL_UNITS_UNDEFINED)
    *unit = val;
  return (val != TOOL_UNITS_UNDEFINED);
}
static void exportParameters(GString *data, VisuData *dataObj _U_)
{
  const gchar **units;

  if (preferedUnit != TOOL_UNITS_UNDEFINED)
    {
      units = tool_physic_getUnitNames();

      g_string_append_printf(data, "# %s\n", DESC_PARAMETER_UNIT);
      g_string_append_printf(data, "%s: %s\n\n", FLAG_PARAMETER_UNIT,
			     units[preferedUnit]);
    }
}
