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

#include "renderingAtomic_d3.h"

static int FREAD_C(char *var, unsigned int nb, VisuIO *io);
static int FREAD_I(unsigned int *var, unsigned int nb, VisuIO *io, int endianness);
/*static void FREAD_F(float *var, int nb, char *msg);*/
static int FREAD_D(double *var, unsigned int nb, VisuIO *io, int endianness);
static int read_title(VisuIO *io, int endianness);
static int read_nat_ntype(VisuIO *io, int endianness);
static int read_nattyp_natnom(VisuIO *io, int endianness);
static int read_dxx_dyx_dyy_dzx_dzy_dzz(VisuData *data, VisuIO *io, int endianness);
static int read_x(VisuIO *io, int endianness);
static int read_y(VisuIO *io, int endianness);
static int read_z(VisuIO *io, int endianness);
static void free_read_d3();

static unsigned int ncheck, mcheck;
static char title[129];
static unsigned int nat, ntypeD3;
static unsigned int *nattyp;
static char **natnom;
static double *x, *y, *z;

#define KEEP_ENDIANNESS   0
#define CHANGE_ENDIANNESS 1

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

static int FREAD_C(char *var, unsigned int nb, VisuIO *io)
{
  if (fread(var, sizeof(char), nb, *io->flux) != nb)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'FREAD_C error'\n"));
      return 1;
    }
  return 0;
}

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

static int FREAD_I(unsigned int *var, unsigned int nb, VisuIO *io, int endianness)
{
  char c[sizeof(int)];
  register unsigned int k, ks, l;

  if (fread(var, sizeof(int), nb, *io->flux) != nb)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'FREAD_I error'\n"));
      return 1;
    }
  
  if (endianness == CHANGE_ENDIANNESS)
    {
      for(k=0; k<nb; k++)
	{
	  ks = (k+1)*sizeof(int) - 1;
	  for(l=0; l<sizeof(int); l++)
	    c[l] = *((char*)var + ks - l);
	  var[k] = *(int *)&c[0];
	}
    }
  return 0;
}

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

/*
static void FREAD_F(float *var, int nb, char *msg) {

#ifdef DEC
   char c[sizeof(float)];
   register int k, ks, l;
#endif

   msg[0] = 0;
   if (fread(var, sizeof(float), nb, *io->flux) != nb) {
      (void)sprintf(msg, "FREAD_F error\n");
      return;
   }
#ifdef DEC
   for(k=0; k<nb; k++) {
      ks = (k+1)*sizeof(float) - 1;
      for(l=0; l<sizeof(float); l++)
         c[l] = *((char*)var + ks - l);
      var[k] = *(float *)&c[0];
   }
#endif
   
}
*/

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

static int FREAD_D(double *var, unsigned int nb, VisuIO *io, int endianness)
{
   char c[sizeof(double)];
   register unsigned int k, ks, l;

   if (fread(var, sizeof(double), nb, *io->flux) != nb)
     {
       g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						  " 'FREAD_D error'\n"));
       return 1;
     }

   if (endianness == CHANGE_ENDIANNESS)
     {
       for(k=0; k<nb; k++)
	 {
	   ks = (k+1)*sizeof(double) - 1;
	   for(l=0; l<sizeof(double); l++)
	     c[l] = *((char*)var + ks - l);
	   var[k] = *(double *)&c[0];
	 }
     }
   return 0;
}

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

/* NOTICE : title element of d3 format is not used in v_sim. */
static int read_title(VisuIO *io, int endianness)
{
  int res, pos;
  
  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != 128)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax, 'TITLE"
						 " INCORRECT'.\n"));
      return 1;
    }
  res = FREAD_C(title, ncheck, io); 
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax, 'ERROR"
						 " READING TITLE\n"));
      return 1;
    }
  pos = (int)ncheck;
  title[pos] = 0;
  pos -= 1;
  while (pos >= 0 && title[pos] == ' ')
    title[pos--] = '\0';

  return 0;
}

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

static int read_nat_ntype(VisuIO *io, int endianness)
{
  int res;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != 2*sizeof(int))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'NAT-NTYPE INCORRECT\n"));
      return 1;
    }   
  res = FREAD_I(&nat, 1, io, endianness);
  if(res) return 1;
  res = FREAD_I(&ntypeD3, 1, io, endianness);
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING NAT-NTYPE\n"));
      return 1;
    } 
  return 0;
}

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

static int read_nattyp_natnom(VisuIO *io, int endianness)
{
  unsigned int i, k, res;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != ntypeD3*(sizeof(int) + 8))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'NATI-NOM INCORRECT'\n"));
      return 1;
    }   
  res = FREAD_I(nattyp, ntypeD3, io, endianness);
  if(res) return 1;
  for(k=0; k<ntypeD3; k++)
    {
      res = FREAD_C(natnom[k], 8, io);
      if(res) return 1;
      natnom[k][8] = 0;
      for (i = 0; i < 8; i++)
	if (natnom[k][i] == ' ')
	  natnom[k][i] = '\0';
    }
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING NATI-NOM'\n"));
      return 1;
    }
  return 0;
}

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

static int read_dxx_dyx_dyy_dzx_dzy_dzz(VisuData *data, VisuIO *io, int endianness)
{
  int res;
  double boxGeometry[6];
  float geometry[6];
  int i;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != 6*sizeof(double))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'DXX-DYX-DYY-DZX-DZY-DZZ INCORRECT'\n"));
      return 1;
    }
  res = FREAD_D(&(boxGeometry[0]), 1, io, endianness);
  if(res) return 1;
  res = FREAD_D(&(boxGeometry[1]), 1, io, endianness);
  if(res) return 1;
  res = FREAD_D(&(boxGeometry[2]), 1, io, endianness);
  if(res) return 1;
  res = FREAD_D(&(boxGeometry[3]), 1, io, endianness);   
  if(res) return 1;
  res = FREAD_D(&(boxGeometry[4]), 1, io, endianness);   
  if(res) return 1;
  res = FREAD_D(&(boxGeometry[5]), 1, io, endianness); 
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING DXX-DYX-DYY-DZX-DZY-DZZ'\n"));
      return 1;
    }
  for (i = 0; i < 6; i++)
    geometry[i] = (float)boxGeometry[i];
  visuDataSet_boxGeometry(data, geometry, TRUE);
  return 0;
}

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

static int read_x(VisuIO *io, int endianness)
{
  int res;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != nat*sizeof(double))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'X INCORRECT'\n"));
      return 1;
    }
  res = FREAD_D(x, nat, io, endianness); 
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING X'\n")); 
      return 1;
    }
  return 0;
}

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

static int read_y(VisuIO *io, int endianness)
{
  int res;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != nat*sizeof(double))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'Y INCORRECT\n"));
      return 1;
    }   
  res = FREAD_D(y, nat, io, endianness); 
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING Y\n")); 
      return 1;
    }
  return 0;
}

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

static int read_z(VisuIO *io, int endianness)
{
  int res;

  res = FREAD_I(&ncheck, 1, io, endianness);
  if(res) return 1;
  if (ncheck != nat*sizeof(double))
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'Z INCORRECT\n"));
      return 1;
    }   
  res = FREAD_D(z, nat, io, endianness); 
  if(res) return 1;
  res = FREAD_I(&mcheck, 1, io, endianness);
  if(res) return 1;
  if (mcheck != ncheck)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'ERROR READING Z\n")); 
      return 1;
    }
  return 0;
}

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

int read_d3_file(VisuData *data, VisuIO *io)
{
  unsigned int i, j;
  unsigned int snat;
  unsigned int res, val;
  VisuElement *type;
  VisuElement **types;
  int endianness;
  gchar *infoUTF8;

  g_return_val_if_fail(*io->flux, 1);

  /* Check the first element to find the endianness.
     The first element is an int equal to 128. We test Littl endian first. */
  DBG_fprintf(stderr, "Atomic D3 : test for endianness.\n");
  res = FREAD_I(&val, 1, io, KEEP_ENDIANNESS);
  if (res)
    return -1;
  if (val == 128)
    {
      endianness = KEEP_ENDIANNESS;
      DBG_fprintf(stderr, "Atomic D3 : this file is in the endianness of your machine.\n");
    }
  else
    {
      rewind(*io->flux);
      res = FREAD_I(&val, 1, io, CHANGE_ENDIANNESS);
      if (res)
	return -1;
      if (val == 128)
	{
	  endianness = CHANGE_ENDIANNESS;
	  DBG_fprintf(stderr, "Atomic D3 : this file is not in the endianness of your machine.\n");
	}
      else
	return -1;
    }
  rewind(*io->flux);

  /* TITLE */
  res = read_title(io, endianness);
  if(res)
    return -1;

  /* NAT-NTYPE */   
  res = read_nat_ntype(io, endianness);
  if(res)
    return 1;
               
  /* NATI-NOM */      
  nattyp = malloc(ntypeD3*sizeof(int));
  if(!nattyp)
    {
      allocationProblems();
      exit(1);
    }
  natnom = malloc(ntypeD3*sizeof(char *));
  if(!natnom)
    {
      allocationProblems();
      exit(1);
    }
  for(i=0; i<ntypeD3; i++)
    {
      natnom[i] = malloc(9*sizeof(char));
      if(!natnom[i])
	{
	  allocationProblems();
	  exit(1);
	}
    }
  res = read_nattyp_natnom(io, endianness);
  if(res)
    {
      free_read_d3();
      return 1;
    }
  snat = 0;
  for(i=0; i<ntypeD3; i++)
    snat = snat + nattyp[i];
  if(snat != nat)
    {
      g_string_append_printf(io->informations, _("WARNING : wrong d3 syntax,"
						 " 'sum of nattyp's not equal to nat'\n"));
      free_read_d3();
      return 1;
    }

         
  /* DXX-DYX-DYY-DZX-DZY-DZZ */
  res = read_dxx_dyx_dyy_dzx_dzy_dzz(data, io, endianness);
  if(res)
    {
      free_read_d3();
      return 1;
    }
   
  /* X */      
  x = malloc(sizeof(double) * nat);
  if (!x)
    {
      allocationProblems();
      exit(1);
    }
  res = read_x(io, endianness);
  if(res)
    {
      free_read_d3();
      return 1;
    }
   
  /* Y */      
  y = malloc(sizeof(double) * nat);
  if (!y)
    {
      allocationProblems();
      exit(1);
    }
  res = read_y(io, endianness);  
  if(res)
    {
      free_read_d3();
      return 1;
    }
   
  /* Z */      
  z = malloc(sizeof(double) * nat);
  if (!z)
    {
      allocationProblems();
      exit(1);
    }
  res = read_z(io, endianness);  
  if(res)
    {
      free_read_d3();
      return 1;
    }

  DBG_fprintf(stderr, "Atomic d3 : nat = %d | ntypeD3 = %d\n", nat, ntypeD3);
  for(i = 0; i < ntypeD3; i++)
    DBG_fprintf(stderr, " | natnom %d = '%s', nb %d\n", i, natnom[i], nattyp[i]);
  /* Now we have all the element and the number of atoms per element.
     So we allocate the memory. */
  types = malloc(sizeof(VisuElement*) * ntypeD3);
  if (!types)
    {
      allocationProblems();
      exit(1);
    }
  for(i = 0; i < ntypeD3; i++)
    {
      /* adding nomloc to the hashtable */
      type = visuElementGet_fromName(natnom[i]);
      if (!type)
	{
	  type = visuElementNewWithName(natnom[i]);
	  if (!type)
	    {
	      g_warning("Cannot create a new"
			" type for '%s'\n", natnom[i]);
	      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;
	    }
	}
      types[i] = type;
    }

  /* Set the commentary. */
  infoUTF8 = getStringInUTF8(title);
  visuDataSet_fileCommentary(data, infoUTF8);
  g_free(infoUTF8);

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

  nat = 0;
  for (i = 0; i < ntypeD3; i++)
    {
      for (j = 0; j < nattyp[i]; j++)
	{
	  visuDataAdd_int(data, i, x[nat], y[nat], z[nat], nat + 1);
	  nat++;
	}
    }
  
  free_read_d3();
   
  return 0;
}

void free_read_d3()
{
  unsigned int i;
  
  DBG_fprintf(stderr, "Atomic d3 : freeing tmp variables.\n");
  for(i = 0; i < ntypeD3; i++)
    if (natnom[i])
      free(natnom[i]);
  if (natnom)
    free(natnom);
  if(nattyp)
    free(nattyp);
  if (x)
    free(x);
  if (y)
    free(y);
  if (z)
    free(z);
}

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