/*   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_tools.h"
#include "visu_object.h"

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


int fileSystemIsInUTF8;

void setFileSystemInUTF8(int val)
{
  DBG_fprintf(stderr, "Visu Tools : the file system is in UTF8 : %d.\n", val);
  fileSystemIsInUTF8 = val;
}
int getFileSystemInUTF8()
{
  return fileSystemIsInUTF8;
}


/* Used to free the keys or the values of a GHashTable
   where gpointer are char*. */
void freeString(gpointer ele)
{
  free((char*)ele);
}
/* Used to free the keys or the values of a GHashTable
   where gpointer are float*. */
void freeFloat(gpointer ele)
{
  free((float*)ele);
}
/* Used to free the keys or the values of a GHashTable
   where gpointer are int*. */
void freeInt(gpointer ele)
{
  free((int*)ele);
}
void freeGPointer(gpointer ele)
{
  free(ele);
}

gchar* getValidPath(GList **pathList, char *fileName, int accessMode)
{
  gchar *validPath;
  int fileOk;

  validPath = (char*)0;
  /* look for a directory to save or read a file. */
  fileOk = 0;
  while (*pathList && !fileOk)
    {
      validPath = g_build_filename((gchar*)(*pathList)->data, fileName, NULL);
      DBG_fprintf(stderr, "Visu Tools : test access (%d) for '%s' ... ", accessMode, validPath);
      fileOk = !access((char*)validPath, accessMode); /* return 0 if success */
      if (!fileOk)
	{
	  /* if access mode is write access and the file does not already exist :
	     we test if the directory has written permitions. */
	  if ( accessMode == W_OK && !g_file_test(validPath, G_FILE_TEST_EXISTS) )
	    fileOk = !access((char*)(*pathList)->data, accessMode); /* return 0 if success */
	  if (!fileOk)
	    {
	      DBG_fprintf(stderr, " failed.\n");
	      g_free(validPath);
	      *pathList = g_list_next(*pathList);
	    }
	}
      
    }
  if (fileOk)
    {
      DBG_fprintf(stderr, " OK.\n");
      return validPath;
    }
  else
      return (gchar*)0;
}


void allocationProblems()
{
  fprintf(stderr, "INTERNAL ERROR! Can't allocate the requested object.\n");
}

gchar* getStringInUTF8(const gchar* str)
{
  gchar* strTo;
  const gchar *end;
  gsize ecrit, lu;

  if (fileSystemIsInUTF8)
    {
      /* We validate the UTF8 file name before using it. */
      if (g_utf8_validate(str, -1, &end))
	strTo = g_strdup(str);
      else
	{
	  g_warning("Encoding error in name (%s), invalid UTF8.\n", str);
	  strTo = g_strndup(str, (int)(end - str));
	}
      return strTo;
    }
  
  DBG_fprintf(stderr, "Visu Tools : A conversion to UTF8 is required.\n");
  strTo = g_filename_to_utf8(str, -1, &lu, &ecrit, NULL);
  g_return_val_if_fail(strTo, (gchar*)0);

  return strTo;
}

/* It puts in dest all the characters of value without ' ' or '\t'
   at the begining at at the end. */
int getTrimString(char **dest, const char* value)
{
  int debut, fin;

  if (!value)
    return 1;
  *dest = realloc(*dest, sizeof(char) * (strlen(value) + 1));
  if (!*dest)
    {
      allocationProblems();
      exit(1);
    }
  debut = 0;
  while (value[debut] == ' ' || value[debut] == '\t')
    debut++;
  /* retire les blancs à la fin */
  fin = strlen(value) - 1;
  while (fin >= 0 && (value[fin] == ' ' || value[fin] == '\t' || value[fin] == '\n'))
    fin--;
  strncpy(*dest, value + debut, fin - debut + 1);
  (*dest)[fin - debut + 1] = '\0';
  return 0;
}

/* Reallocates the pointer dest and strcpy value within. */
void putString(char **dest, const char* value)
{
  *dest = realloc(*dest, sizeof(char) * (strlen(value) + 1));
  if (!*dest)
    {
      allocationProblems();
      exit(1);
    }
  strcpy(*dest, value);
}

float fModulo(float a, int b) {
  float fb = (float)b;
  while(a < fb) a += fb;
  while(a >= fb) a -= fb;
  return a;
}

gchar* normalize_path(gchar* path)
{
#if SYSTEM_X11 == 1
#define FILE_SYSTEM_SEP "/"
#endif
#if SYSTEM_WIN32 == 1
#define FILE_SYSTEM_SEP "\\"
#endif
  gchar **tokens;
  int i;
  GString *normPath;
  GList *lst, *tmplst;
  gchar *allPath;

  if (!path)
    return (gchar*)0;

  if (!g_path_is_absolute(path))
    allPath = g_build_filename(g_get_current_dir(), path, NULL);
  else
    allPath = g_strdup(path);

  tokens = g_strsplit(allPath, FILE_SYSTEM_SEP, -1);

  normPath = g_string_new("");

  lst = (GList*)0;
  for (i = 0; tokens[i]; i++)
    {
      /* If tokens[i] == . or is empty (because of //), we ignore. */
      if (!strcmp(tokens[i], "."))
	continue;
      if (!tokens[i][0])
	continue;
      /* If token[i] == .. then we pop one element from lst. */
      if (!strcmp(tokens[i], ".."))
	{
	  lst = g_list_delete_link(lst, lst);
	  continue;
	}
      /* Token[i] is a valid chain, then we prepend it to the list. */
      lst = g_list_prepend(lst, tokens[i]);
    }
    /* Write the lst to the string. */
    tmplst = lst;
  while(tmplst)
    {
      g_string_prepend(normPath, (gchar*)tmplst->data);
      g_string_prepend(normPath, FILE_SYSTEM_SEP);
      tmplst = g_list_next(tmplst);
    }
  g_list_free(lst);
#if SYSTEM_WIN32 == 1
  g_string_erase(normPath, 0,1);
#endif
  g_strfreev(tokens);
  g_free(allPath);
  DBG_fprintf(stderr, "Visu Tools : normalizing path, from '%s' to '%s'.\n",
	      path, normPath->str);
  return g_string_free(normPath, FALSE);
}


syntax highlighted by Code2HTML, v. 0.9.1