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

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

int readFile_is_comment(char *str) {
   int n = strlen(str);
   register int i;
   
   if(n == 0) return 1;
   else if(str[0] == '#') return 1;
   else if(str[0] == '!') return 1;
   else {
      /* n-2 to skip terminal \n */
      for(i=n-2; i>= 0; i--) {
         if(str[i] != ' ') return 0;
      }
   }
   return 1;
}

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

void freeDataAscii(gpointer data)
{
  free((struct dataAscii*)data);
}
void putValTypeInAsciiType(gpointer key, gpointer value, gpointer data)
{
  VisuElement **tab;
  struct dataAscii *infos;
  
  tab = *(VisuElement***)data;
  infos = (struct dataAscii *)value;
  tab[infos->pos] = infos->ele;
}
void putValNbInAsciiType(gpointer key, gpointer value, gpointer data)
{
  int *tab;
  struct dataAscii *infos;
  
  tab = *(int**)data;
  infos = (struct dataAscii *)value;
  tab[infos->pos] = infos->nbNodes;
}
/******************************************************************************/

int read_ascii_file(VisuData *data, VisuIO *io)
{
  char line[MAX_LINE_LENGTH], info[MAX_LINE_LENGTH];
  double xu, yu, zu;
  int i, res;
  char nomloc[9], *ptChar;
  VisuElement *type;
  VisuElement **types;
  int *nattyp;
  int ntype;
  GHashTable *elements;
  struct dataAscii *infos;
  float boxGeometry[6];
  gchar *infoUTF8;
    
  /* The first line is a commentry. */
  (void)fgets(info, MAX_LINE_LENGTH, *io->flux);
  if(feof(*io->flux))
    {
      g_string_append_printf(io->informations, _("WARNING : the ASCII file should"
						 " contain more than 3 lines\n"));
      /* The file doesn't conform to ascii norm, we exit with a wrong type flag. */
      return -1;
    }
  /* The second line contains xx, xy and yy */
  (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
  if(feof(*io->flux))
    {
      g_string_append_printf(io->informations, _("WARNING : the ASCII file should"
						 " contain more than 3 lines\n"));
      /* The file doesn't conform to ascii norm, we exit with a wrong type flag. */
      return -1;
    }
  if(sscanf(line, "%f %f %f", &(boxGeometry[0]), &(boxGeometry[1]), &(boxGeometry[2])) != 3)
    {
      g_string_append_printf(io->informations, _("WARNING : cannot read dxx dyx dyy"
						 " on 2nd line of ASCII file\n"));
      /* The file doesn't conform to ascii norm, we exit with a wrong type flag. */
      return -1;
    }
  /* The third line contains xz, yz and zz */
  (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
  if(feof(*io->flux))
    {
      g_string_append_printf(io->informations, _("WARNING : the ASCII file should"
						 " contain more than 3 lines\n"));
      /* The file doesn't conform to ascii norm, we exit with a wrong type flag. */
      return -1;
    }
  if(sscanf(line, "%f %f %f", &boxGeometry[3], &boxGeometry[4], &boxGeometry[5]) != 3)
    {
      g_string_append_printf(io->informations, _("WARNING : cannot read dzx dzy dzz"
						 " on 3rd line of ASCII file\n"));
      /* The file doesn't conform to ascii norm, we exit with a wrong type flag. */
      return -1;
    }
  visuDataSet_boxGeometry(data, boxGeometry, TRUE);
   
  /* Ok, from this point we assert that the file is in ascii format.
     All following errors are treated as syntax errors and the corresponding
     flag is return. */

  /* 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);
    }
  for(;;)
    {
      (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
      (*io->nbLine) ++ ;
      if(feof(*io->flux))
	{
	  (void)rewind(*io->flux);
	  break;
	}
      if(readFile_is_comment(line)) continue;
      if(sscanf(line, "%lf %lf %lf %s", 
            &xu, &yu, &zu, nomloc) != 4)
	{
	  g_string_append_printf(io->informations, _("WARNING : cannot read x, y, z,"
						     " name in ASCII file at line %d.\n"),
				 *io->nbLine);
	  g_string_append_printf(io->informations, _(" quoting '%s'.\n"), line);
	  return 1;
	}
      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;
    }

  /* Set the commentary. */
  info[MAX_LINE_LENGTH - 1] = '\0';
  ptChar = strchr(info, '\n');
  if (ptChar)
    *ptChar = '\0';
  if (info[0] == '#')
    infoUTF8 = getStringInUTF8(info + 1);
  else
    infoUTF8 = getStringInUTF8(info);
  visuDataSet_fileCommentary(data, infoUTF8);
  g_free(infoUTF8);

  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);
    }
         
  /* reread the file to store the coordinates */
  
  (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
  (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
  (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
   
  i = 0;
  for(;;)
    {
      (void)fgets(line, MAX_LINE_LENGTH, *io->flux);
      if(feof(*io->flux))
	break;
      if(readFile_is_comment(line)) continue;
      
      (void)sscanf(line, "%lf %lf %lf %s", 
		   &xu, &yu, &zu, nomloc);
      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++;
    }
   
   return 0;
}

