/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	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-2006)

	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;
/******************/
/* Storing colors */
/******************/
#define COLOR_NB_MAX 10
GList *color_storageArray;


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;
}


/******************/
/* Storing colors */
/******************/
void initColorStorage()
{
  color_storageArray = (GList*)0;
}
Color* colorNew_floatRGBA(float rgba[4])
{
  Color *color;
  int i;

  color = malloc(sizeof(Color));
  if (!color)
    {
      allocationProblems();
      exit(1);
    }
  for (i = 0; i< 4; i++)
    {
      if (rgba[i] < 0.)
	color->rgba[i] = 0.;
      else if (rgba[i] > 1.)
	color->rgba[i] = 1.;
      else
	color->rgba[i] = rgba[i];
    }
  color->userData = (gpointer)0;
  return color;
}
Color* colorGet_byId(int num)
{
  GList *tmpLst;

  tmpLst = g_list_nth(color_storageArray, num);
  if (tmpLst)
    return (Color*)tmpLst->data;
  else
    return (Color*)0;
}
int colorGet_byColor(Color *color)
{
  int pos;

  if (color)
    colorGet_byValues(&pos, color->rgba[0], color->rgba[1], color->rgba[2], color->rgba[3]);
  else
    pos = -1;
  return pos;

}
Color* colorGet_byValues(int *pos, float red, float green, float blue, float alpha)
{
  GList *tmpLst;
  int found;

  tmpLst = color_storageArray;
  found = 0;
  if (pos)
    *pos = -1;
  while (tmpLst && !found)
    {
      found = (red == ((Color*)tmpLst->data)->rgba[0]) &&
	(green == ((Color*)tmpLst->data)->rgba[1]) &&
	(blue == ((Color*)tmpLst->data)->rgba[2]) &&
	(alpha == ((Color*)tmpLst->data)->rgba[3]);
      if (pos)
	*pos += 1;
      if (!found)
	tmpLst = g_list_next(tmpLst);
    }
  if (found)
    return (Color*)tmpLst->data;
  else
    return (Color*)0;
}
GList* colorGet_storedColors()
{
  return color_storageArray;
}
Color* colorAdd_color(Color* color)
{
  int pos;

  g_return_val_if_fail(color, (Color*)0);

  if (!colorGet_byValues(&pos, color->rgba[0], color->rgba[1], color->rgba[2], color->rgba[3]))
    {
      color_storageArray = g_list_append(color_storageArray, (gpointer)color);
      DBG_fprintf(stderr, "Visu Tools : adding a new color at %p (%d).\n",
		  (gpointer)color_storageArray, g_list_length(color_storageArray));
      g_signal_emit (visu, VISU_GET_CLASS(visu)->colorNewAvailable_signal_id,
		     0 , (gpointer)color, NULL);
    }
  return color;
}
Color* colorAdd_floatRGBA(float rgba[4], int *position)
{
  Color *color;
  int i;
  int pos;

  for (i = 0; i < 4; i++)
    g_return_val_if_fail(rgba[i] >= 0. && rgba[i] <= 1., (Color*)0);

  color = colorGet_byValues(position, rgba[0], rgba[1], rgba[2], rgba[3]);
  if (color)
    {
      DBG_fprintf(stderr, "Visu Tools : color already exist, no color added.\n");
      return color;
    }

  color = colorNew_floatRGBA(rgba);
  color_storageArray = g_list_append(color_storageArray, (gpointer)color);
  if (position)
    *position = g_list_length(color_storageArray);
  DBG_fprintf(stderr, "Visu Tools : adding a new color at %p (%d).\n",
	      (gpointer)color_storageArray, g_list_length(color_storageArray));
  g_signal_emit (visu, VISU_GET_CLASS (visu)->colorNewAvailable_signal_id,
		 0 , (gpointer)color, NULL);
  return color;
}
Color* colorAdd_intRGBA(int rgba[4])
{
  Color *color;
  float rgbaf[4];
  int pos, i;

  for (i = 0; i < 4; i++)
    g_return_val_if_fail(rgba[i] >= 0 && rgba[i] < 256, (Color*)0);

  for (i = 0; i < 4; i++)
    rgbaf[i] = (float)rgba[i] / 255.;
  color = colorGet_byValues(&pos, rgbaf[0], rgbaf[1], rgbaf[2], rgbaf[3]);
  if (color)
    {
      DBG_fprintf(stderr, "Visu Tools : color already exist, no color added.\n");
      return color;
    }

  color = colorNew_floatRGBA(rgbaf);
  color_storageArray = g_list_append(color_storageArray, (gpointer)color);
  DBG_fprintf(stderr, "Visu Tools : adding a new color at %p (%d).\n",
	      (gpointer)color_storageArray, g_list_length(color_storageArray));
  g_signal_emit (visu, VISU_GET_CLASS (visu)->colorNewAvailable_signal_id,
		 0 , (gpointer)color, NULL);
  return color;
}
Color* colorGet_lastStored()
{
  return (Color*)g_list_last(color_storageArray)->data;
}

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

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

  if (fileSystemIsInUTF8)
    {
      strTo = g_strdup(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);
}

/**
 * fModulo: 
 * 
 * This function is just like a%b whereas it works with @a as a floating p number. 
*/
float fModulo(float a, int b) {
  float fb = (float)b;
  while(a < fb) a += fb;
  while(a >= fb) a -= fb;
  return a;
}
  
void HSVtoRGB(float* rgb, float* hsv)
{
  float var_h, var_0, var_1, var_2, var_3;
  int var_i;
  
  g_return_if_fail(rgb && hsv);

  if (hsv[1] == 0)
    {
      rgb[0] = hsv[2];
      rgb[1] = hsv[2];
      rgb[2] = hsv[2];
    }
  else
    {
      var_h = hsv[0] * 6.;
      var_i = (int)var_h;
      var_0 = hsv[2];
      var_1 = hsv[2] * (1. - hsv[1]);
      var_2 = hsv[2] * (1. - hsv[1] * (var_h - (float)var_i));
      var_3 = hsv[2] * (1. - hsv[1] * (1. - (var_h - (float)var_i)));
      switch (var_i % 6)
	{
	case 0:
	  rgb[0] = var_0;
	  rgb[1] = var_3;
	  rgb[2] = var_1;
	  break;
	case 1:
	  rgb[0] = var_2;
	  rgb[1] = var_0;
	  rgb[2] = var_1;
	  break;
	case 2:
	  rgb[0] = var_1;
	  rgb[1] = var_0;
	  rgb[2] = var_3;
	  break;
	case 3:
	  rgb[0] = var_1;
	  rgb[1] = var_2;
	  rgb[2] = var_0;
	  break;
	case 4:
	  rgb[0] = var_3;
	  rgb[1] = var_1;
	  rgb[2] = var_0;
	  break;
	case 5:
	  rgb[0] = var_0;
	  rgb[1] = var_1;
	  rgb[2] = var_2;
	  break;
	}
    }
}

float Hue_2_RGB(float v1, float v2, float vH)
{
  /* from www.easyrgb.com */
  if (vH < 0) vH += 1;
  if (vH > 1) vH -= 1;
  if ((6*vH) < 1) 
    return (v1+(v2-v1)*6*vH);
  if ((2*vH) < 1) 
    return v2;
  if ((3*vH) < 2) 
    return (v1+(v2-v1)*((2./3.)-vH)*6);
  return v1;
}

/* hsl[0] = hue
   hsl[1] = saturation
   hsl[2] = lightness */
void HSLtoRGB(float *rgb, float *hsl)
{
  /* from www.easyrgb.com */
  if (hsl[1] == 0)                       /*HSL values = 0 ÷ 1*/
    {
      rgb[0] = hsl[2];                      /*RGB results = 0 ÷ 255*/
      rgb[1] = hsl[2];
      rgb[2] = hsl[2];
    }

  else
    {
      float var_1, var_2;
      if (hsl[2] < 0.5) 
	var_2 = hsl[2] * (1 + hsl[1]);		       
      else           
	var_2 = (hsl[2] + hsl[1]) - (hsl[1] * hsl[2]);
					
      var_1 = 2 * hsl[2] - var_2;

      rgb[0] = Hue_2_RGB( var_1, var_2, hsl[0] + ( 1. / 3. ) );
      rgb[1] = Hue_2_RGB( var_1, var_2, hsl[0] );
      rgb[2] = Hue_2_RGB( var_1, var_2, hsl[0] - ( 1. / 3. ) );
    }  
}

#ifndef PI
#define PI 3.1415926
#endif

#ifndef RAD2DEG
#define RAD2DEG(x) ((180./PI)*x)
#endif

#ifndef DEG2RAD
#define DEG2RAD(x) ((PI/180.)*x)
#endif

/* s[0] = pho, s[1] = theta, s[2] = phi
   c[0] = x, c[1] = y, c[2] = z */
void cartesian_to_spherical(float *spherical, float *cartesian)
{
  const float *c = cartesian;
  float *s = spherical;

  double rho;
  double theta; 
  double phi;

  if(c[0] == 0 && c[1] == 0 && c[2] == 0)
    {
      s[0] = 0;
      s[1] = 0;
      s[2] = 0;
      return;
    }

  rho = sqrt(c[0]*c[0] + c[1]*c[1] + c[2]*c[2]);

  if(c[0] == 0 && c[1] == 0)
    theta = (c[2] > 0) ? 0 : PI;
  else 
    theta = acos(c[2]/rho);

  if(c[0] != 0)
    {
      phi = atan(c[1]/c[0]) + PI*((c[0] < 0) ? 1 : 0);
    }
  else
    {
      if(c[1] == 0) /* facultatif*/
	phi = 0;    /* facultatif*/
      else if(c[1] > 0)
	phi = PI/2;
      else
	phi = -PI/2;
    }

  s[0] = rho;
  s[1] = /*fModulo(RAD2DEG(theta), 180);*/ RAD2DEG(theta);
  s[2] = fModulo(RAD2DEG(phi), 360);
}

void spherical_to_cartesian(float *cartesian, float *spherical)
{
  cartesian[0] = spherical[0] * sin(DEG2RAD(spherical[1]))*cos(DEG2RAD(spherical[2]));
  cartesian[1] = spherical[0] * sin(DEG2RAD(spherical[1]))*sin(DEG2RAD(spherical[2]));
  cartesian[2] = spherical[0] * cos(DEG2RAD(spherical[1]));

  return;
}
 

void square_matrix_product(float *matrix, float *vector, float *result, int dim)
{
  int i, j;

  for(i=0; i<dim; i++)
    {
      result[i] = 0;
      for(j=0; j<dim; j++)
	result[i] += matrix[dim*i+j]*vector[j];
    }
}
void matrixProduct(float matRes[3][3], float matA[3][3], float matB[3][3])
{
  int i, j, k;

  for (i = 0; i < 3; i++)
    for (j = 0; j < 3; j++)
      {
	matRes[i][j] = 0.;
	for (k = 0; k < 3; k++)
	  matRes[i][j] += matA[i][k] * matB[k][j];
      }
}
void vectorProduct(float vectRes[3], float mat[3][3], float vect[3])
{
  int i, j;

  for (i = 0; i < 3; i++)
    {
      vectRes[i] = 0.;
      for (j = 0; j < 3; j++)
	vectRes[i] += mat[i][j] * vect[j];
    }
}

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, n;
  GString *normPath;
  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);
  for (n = 0; tokens[n]; n++);

  normPath = g_string_new("");
  if (n == 0)
    return g_string_free(normPath, FALSE);

  for (i = n - 1; i >= 0 && tokens[i]; i--)
    {
      if (!strcmp(tokens[i], "."))
	continue;
      if (!strcmp(tokens[i], ".."))
	{
	  i -= 1;
	  continue;
	}
      if (!tokens[i][0])
	continue;
      g_string_prepend(normPath, tokens[i]);
      g_string_prepend(normPath, FILE_SYSTEM_SEP);
    }
#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);
}
