/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD, Damien
	CALISTE, Olivier D'Astier, laboratoire L_Sim, (2001-2011)
  
	Adresses 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 and Damien
	CALISTE and Olivier D'Astier, laboratoire L_Sim, (2001-2011)

	E-mail addresses :
	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 "xsf.h"
#include "xsf_density.h"

#include <glib.h>

#include <extraFunctions/sfielddata.h>

/* Local methods. */
static gboolean xsfDensityLoad(VisuScalarFieldMethod *meth,
                               VisuScalarFieldMethodData *data,
                               GCancellable *cancel, GError **error);

void xsfDensityInit()
{
  const gchar *type[] = {"*.xsf", "*.axsf", (char*)0};
  
  visu_scalar_field_method_new(_("XCrysDen density file format"),
                               type, xsfDensityLoad, G_PRIORITY_HIGH - 5);
}

static gboolean read_values(struct xsf_reader *rd, guint mesh[3],
                            GArray **values, GError **error)
{
  int i, j, n;
  gchar **tokens;
  GArray *density;
#if DEBUG == 1
  GTimer *timer;
  gulong fractionTimer;
#endif

#if DEBUG == 1
  timer = g_timer_new();
  g_timer_start(timer);
#endif

  n = mesh[0] * mesh[1] * mesh[2];
  density = g_array_sized_new(FALSE, FALSE, sizeof(double), n);
  density = g_array_set_size(density, n);

  DBG_fprintf(stderr, "XSF: read density (%gMo).\n",
              sizeof(double) * n / 1024. / 1024.);
  i = 0;
  do
    {
      tokens = g_strsplit(rd->line->str, " ", 0);
      for (j = 0; tokens[j] && i < n; j++)
        if (tokens[j][0])
          {
            if (sscanf(tokens[j], "%lf", &g_array_index(density, double, i)) != 1)
              {
                *error = g_error_new(TOOL_FILE_FORMAT_ERROR,
                                     TOOL_FILE_FORMAT_ERROR_FORMAT,
                                     _("Wrong XSF format, unreadable float value"
                                       " %d for density.\n"), i);
                g_strfreev(tokens);
                g_array_unref(density);
                return FALSE;
              }
            i += 1;
          }
      g_strfreev(tokens);
      if (!xsf_reader_skip_comment(rd, error))
	{
	  *error = g_error_new(TOOL_FILE_FORMAT_ERROR, TOOL_FILE_FORMAT_ERROR_FORMAT,
	        	       _("Wrong XSF format, missing density lines.\n"));
          g_array_unref(density);
	  return FALSE;
	}
    }
  while(i < n && rd->status == G_IO_STATUS_NORMAL);
#if DEBUG == 1
  g_timer_stop(timer);
  fprintf(stderr, "XSF: density parsed in %g milli-s.\n", g_timer_elapsed(timer, &fractionTimer)/1e-3);
  g_timer_destroy(timer);
#endif
  if (rd->status != G_IO_STATUS_NORMAL)
    {
      *error = g_error_new(TOOL_FILE_FORMAT_ERROR, TOOL_FILE_FORMAT_ERROR_FORMAT,
			   _("Wrong XSF format, missing float values"
			     " for density (%d read, %d awaited).\n"),
			   i, mesh[0] * mesh[1] * mesh[2]);
      g_array_unref(density);
      return FALSE;
    }
  *values = density;
  return TRUE;
}

static gboolean read_one_density(struct xsf_reader *rd, VisuScalarFieldData *field, GError **error)
{
  VisuBox *boxObj;
  gchar *comment;
  gboolean found;
  int valInt;
  guint mesh[3];
  float trans[3];
  double box[3][3];
  GArray *values;

  /* Read the comment and the flag. */
  comment = g_strdup(rd->line->str);
  g_strstrip(comment);
  visu_scalar_field_setCommentary(VISU_SCALAR_FIELD(field), comment);
  g_free(comment);
  if (!xsf_reader_skip_comment(rd, error))
    return FALSE;
  if (!xsf_reader_get_flag(rd, &found, "BEGIN_DATAGRID_3D", &valInt, FALSE, error))
    return FALSE;

  /* Read the mesh size. */
  if (sscanf(rd->line->str, "%u %u %u", mesh, mesh + 1, mesh + 2) != 3)
    {
      g_set_error(error, TOOL_FILE_FORMAT_ERROR, TOOL_FILE_FORMAT_ERROR_FORMAT,
                  _("Wrong XSF format, missing or wrong mesh size"
                    " after tag '%s'.\n"), "BEGIN_DATAGRID_3D");
      return FALSE;
    }
  if (!xsf_reader_skip_comment(rd, error))
    return FALSE;
  visu_scalar_field_setGridSize(VISU_SCALAR_FIELD(field), mesh);

  /* Read the translation. */
  if (sscanf(rd->line->str, "%f %f %f", trans, trans + 1, trans + 2) != 3)
    {
      g_set_error(error, TOOL_FILE_FORMAT_ERROR, TOOL_FILE_FORMAT_ERROR_FORMAT,
                  _("Wrong XSF format, missing or wrong translation definition."));
      return FALSE;
    }
  if (!xsf_reader_skip_comment(rd, error))
    return FALSE;
  /* visu_pointset_setTranslation(VISU_POINTSET(field), trans, TRUE); */

  /* Read the box. */
  if (!xsf_reader_get_box(rd, box, error))
    return FALSE;
  boxObj = visu_box_new_full(box, VISU_BOX_PERIODIC);
  visu_box_setMargin(boxObj, 0.f, FALSE);
  visu_boxed_setBox(VISU_BOXED(field), VISU_BOXED(boxObj));
  g_object_unref(boxObj);

  /* Read the values. */
  if (!read_values(rd, mesh, &values, error))
    return FALSE;
  DBG_fprintf(stderr, "XSF: transfer density into field object.\n");
  visu_scalar_field_data_set(field, values, VISU_SCALAR_FIELD_DATA_XYZ);
  g_array_unref(values);

  return TRUE;
}

static gboolean xsfDensityLoad(VisuScalarFieldMethod *meth _U_,
                               VisuScalarFieldMethodData *data,
                               GCancellable *cancel _U_, GError **error)
{
  struct xsf_reader rd;
  gboolean flag;
  int valInt;
  VisuScalarFieldData *field;

  g_return_val_if_fail(data, FALSE);
  g_return_val_if_fail(!error || *error == (GError*)0, FALSE);

  xsf_reader_new(&rd);

  if (!tool_files_open(rd.flux, visu_scalar_field_method_data_getFilename(data), error))
    {
      xsf_reader_free(&rd);
      return FALSE;
    }

  field = (VisuScalarFieldData*)0;
  /* We read all the file. */
  if (!xsf_reader_skip_comment(&rd, error))
    {
      xsf_reader_free(&rd);
      return FALSE;
    }
  do
    {
      /* If BLOCK_DATAGRID_3D is found, we store the densities. */
      if (!xsf_reader_get_flag(&rd, &flag, "BEGIN_BLOCK_DATAGRID_3D", &valInt, FALSE, error))
	{
	  xsf_reader_free(&rd);
	  return FALSE;
	}
      if (flag)
        {
	  DBG_fprintf(stderr, "XSF: found the 'BEGIN_BLOCK_DATAGRID_3D' flag.\n");
          field = g_object_new(VISU_TYPE_SCALAR_FIELD_DATA, "label", visu_scalar_field_method_data_getFilename(data), NULL);
          g_object_ref(field);
          visu_scalar_field_method_data_addField(data, VISU_SCALAR_FIELD(field));
          visu_scalar_field_method_data_ready(data);
          if (!read_one_density(&rd, field, error))
            {
              g_object_unref(field);
              xsf_reader_free(&rd);
              return TRUE;
            }
          g_object_unref(field);
        }
      
      /* We go on. */
      if (!xsf_reader_skip_comment(&rd, error))
	{
	  xsf_reader_free(&rd);
          return field != (VisuScalarFieldData*)0;
	}
    }
  while(rd.status != G_IO_STATUS_EOF);

  xsf_reader_free(&rd);
  return field != (VisuScalarFieldData*)0;
}
