/*   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 "atomic_xyz.h"
#include "renderingAtomic_ascii.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/******************************************************************************/

int read_xyz_file(VisuData *data, VisuIO *io)
{
  char line[MAX_LINE_LENGTH], info[MAX_LINE_LENGTH];
  char *ptChar;
  double xu, yu, zu;
  int i, res;
  char nomloc[MAX_LINE_LENGTH];
  VisuElement *type;
  VisuElement **types;
  int *nattyp;
  int ntype;
  GHashTable *elements;
  struct dataAscii *infos;
  double xMin, yMin, zMin, xMax, yMax, zMax;
  float boxGeometry[6];
  float translation[3];
  gchar *infoUTF8;

  /* We read every line that corresponds to this schema : "%s %f %f %f" */
  DBG_fprintf(stderr, "Atomic xyz : reading file as an xyz file.\n");

  info[0] = '\0';
  /* 1st pass to count ntype */
  *io->nbLine = 0;
  ntype = 0;
  elements = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, freeDataAscii);
  if (!elements)
    {
      allocationProblems();
      exit(1);
    }
  while(!feof(*io->flux))
    {
      (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
      (*io->nbLine) ++ ;
      if(feof(*io->flux))
	{
	  (void)rewind(*io->flux);
	  break;
	}
      if(sscanf(line, "%s %lf %lf %lf", nomloc, &xu, &yu, &zu) != 4)
	{
	  if ((*io->nbLine) == 2)
	    {
	      strcpy(info, line);
	      ptChar = strchr(info, '\n');
	      if (ptChar)
		*ptChar = '\0';
	    }
	  continue;
	}
      /* Don't read the line when the first element doesn't begin with a letter. */
      if ( (*nomloc < 'a' || *nomloc > 'z') && (*nomloc < 'A' || *nomloc > 'Z'))
	continue;
      

      nomloc[8] = '\0';
      /* adding nomloc to the hashtable */
      type = visuElementGet_fromName(nomloc);
      if (!type)
	{
	  type = visuElementNewWithName(nomloc);
	  if (!type)
	    {
	      g_warning("Cannot create a new"
			" type for '%s'\n", nomloc);
	      return 1;
	    }
	  res = visuElementAdd(type);
	  if (res)
	    {
	      g_string_append_printf(io->informations, _("INTERNAL ERROR! Cannot add"
							 " new element, maximum has "
							 "been reached.\n"));
	      return 1;
	    }
	}
      infos = (struct dataAscii*)g_hash_table_lookup(elements, (gconstpointer)type);
      if (!infos)
	{
	  infos = malloc(sizeof(struct dataAscii));
	  if (!infos)
	    {
	      allocationProblems();
	      exit(1);
	    }
	  infos->ele = type;
	  infos->pos = ntype;
	  infos->nbNodes = 1;
	  g_hash_table_insert(elements, (gpointer)type, (gpointer)infos);
	  ntype++;
	}
      else
	infos->nbNodes += 1;
    }
  /* Allocate the space for the nodes. */
  types = malloc(sizeof(VisuElement*) * ntype);
  if (!types)
    {
      allocationProblems();
      exit(1);
    }
  nattyp = malloc(sizeof(int) * ntype);
  if(!nattyp)
    {
      allocationProblems();
      exit(1);
    }
  g_hash_table_foreach(elements, (GHFunc)putValTypeInAsciiType, (gpointer)&types);
  g_hash_table_foreach(elements, (GHFunc)putValNbInAsciiType, (gpointer)&nattyp);
  g_hash_table_destroy(elements);
  if (ntype <= 0)
    {
      free(nattyp);
      free(types);
      g_string_append_printf(io->informations,
			     _("WARNING : the file contains no atom coordinates.\n"));
      return 1;
    }

  res = visuDataSet_population(data, ntype, nattyp, types);
  if (!res)
    {
      fprintf(stderr, "FATAL ERROR! Can't store the nodes in the VisuData object.\n");
      exit(1);
    }

  DBG_fprintf(stderr, "Atomic xyz : there are %d types in this file.\n", ntype);
  if (DEBUG)
    {
      for (i = 0; i < ntype; i++)
	DBG_fprintf(stderr, " | %d atom(s) for type %d.\n", nattyp[i], i);
    }
         
  /* reread the file to store the coordinates */
  xMin = 1e5;
  yMin = 1e5;
  zMin = 1e5;
  xMax = -1e5;
  yMax = -1e5;
  zMax = -1e5;
  
  i = 0;
  for(;;)
    {
      (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
      if(feof(*io->flux))
	break;
      
      if(sscanf(line, "%s %lf %lf %lf", nomloc, &xu, &yu, &zu) != 4)
	continue;
      /* Don't read the line when the first element doesn't begin with a letter. */
      if ( (*nomloc < 'a' || *nomloc > 'z') && (*nomloc < 'A' || *nomloc > 'Z'))
	continue;

      nomloc[8] = '\0';
      type = visuElementGet_fromName(nomloc);
      if(!type)
	{
	  g_string_append_printf(io->informations, _("INTERNAL ERROR! The input file must"
						     " have been modified when loading since"
						     " at the second reading the element '%s'"
						     " seems to be new.\n"), nomloc);
	  return 1;
	}
      visuDataAdd_VisuElement(data, type, xu, yu, zu, i);
      i++;
      if (xu < xMin)
	xMin = xu;
      if (yu < yMin)
	yMin = yu;
      if (zu < zMin)
	zMin = zu;
      if (xu > xMax)
	xMax = xu;
      if (yu > yMax)
	yMax = yu;
      if (zu > zMax)
	zMax = zu;
    }

  /* Set the commentary. */
/*   ptChar = strchr(info, '\n'); */
/*   if (ptChar) */
/*     *ptChar = '\0'; */
  if (info[0])
    {
      info[MAX_LINE_LENGTH - 1] = '\0';
      DBG_fprintf(stderr, "Atomic xyz : set the commentary to '%s'.\n", info);
      if (info[0] == '#')
	infoUTF8 = getStringInUTF8(info + 1);
      else
	infoUTF8 = getStringInUTF8(info);
      visuDataSet_fileCommentary(data, infoUTF8);
      g_free(infoUTF8);
    }

  DBG_fprintf(stderr, "Atomic xyz : the elements are in [%f, %f]x[%f, %f]x[%f, %f].\n",
	      xMin, xMax, yMin, yMax, zMin, zMax);
  boxGeometry[0] = xMax - xMin;
  boxGeometry[1] = 0.;
  boxGeometry[2] = yMax - yMin;
  boxGeometry[3] = 0.;
  boxGeometry[4] = 0.;
  boxGeometry[5] = zMax - zMin;
  visuDataSet_boxGeometry(data, boxGeometry, FALSE);

  translation[0] = -xMin;
  translation[1] = -yMin;
  translation[2] = -zMin;
  visuDataSet_XYZtranslation(data, translation);

  return 0;
}

