/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD, Damien
	CALISTE, Olivier D'Astier, laboratoire L_Sim, (2001-2005)
  
	Adresses mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.
	D'ASTIER, dastier AT iie P cnam 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-2005)

	E-mail addresses :
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.
	D'ASTIER, dastier AT iie P cnam 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 "nq_basic.h"
#include "nq_density.h"

#include <glib.h>
#include <netcdf.h>

#include <extraFunctions/scalarFields.h>
#include <extraFunctions/sfielddata.h>
#include <coreTools/toolFileFormat.h>
#include <coreTools/toolMatrix.h>
#include <coreTools/toolOptions.h>
#include <visu_basic.h>

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

void nqDensityInit()
{
  const gchar *type[] = {"*.nc", "*-etsf.nc", (char*)0};
  const gchar *descr = _("Nanoquanta NETCDF format");
  VisuScalarFieldMethod *meth;
  
  meth = visu_scalar_field_method_new(descr, type, nqDensityLoad, G_PRIORITY_HIGH);
  tool_file_format_addPropertyInt(TOOL_FILE_FORMAT(meth), "number_of_components",
                                  _("spin channel (or -1 for all)"), -1);
  tool_file_format_addPropertyInt(TOOL_FILE_FORMAT(meth), "real_or_complex",
                                  _("real or complex values (or -1 for all)"), -1);
}

gboolean nqDensityLoad(VisuScalarFieldMethod *meth _U_,
                       VisuScalarFieldMethodData *data,
                       GCancellable *cancel _U_, GError **error)
{
  gboolean res;
  int netcdfId, varId, status, i, j;
  size_t gridSize[3];
  size_t spinDim;
  size_t realOrComplex;
  int varIdRprimd;
  size_t dimsRprimd[2];
  double rprimd[3][3];
  size_t start[] = {0, 0};
  size_t startDensity[] = {0, 0, 0, 0, 0};
  int varIdDensity;
  size_t dimsDensity[5];
  GArray *density;
  double boxGeometry[6];
  VisuBox *box;
  guint size[3];
  int option_spin, option_realOrComplex;
  ToolOption *option;
  VisuScalarFieldData *field;
  nc_type ncType;
  size_t sizeTitle;
  char title[256];
  gchar *comment;
  GList *fields, *lst;
#if DEBUG == 1
  GTimer *timer;
  gulong fractionTimer;
#endif

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

  res = nqOpen_netcdfFile(visu_scalar_field_method_data_getFilename(data),
                          &netcdfId, error);
  if (!res)
    return FALSE;

#if DEBUG == 1
  timer = g_timer_new();
  g_timer_start(timer);
#endif
    
  /* ToolOptional elements. */
  comment = (gchar*)0;
  status = nc_inq_att(netcdfId, NC_GLOBAL, "title", &ncType, &sizeTitle);
  if (status == NC_NOERR && ncType == NC_CHAR && sizeTitle < 255)
    {
      status = nc_get_att_text(netcdfId, NC_GLOBAL, "title", title);
      if (status == NC_NOERR)
	{
	  title[sizeTitle] = '\0';
	  comment = g_locale_to_utf8(title, -1, NULL, NULL, NULL);
	}
    }

  /* We parse a first time the options, if given. */
  option_spin = tool_file_format_getPropertyInt(TOOL_FILE_FORMAT(meth),
                                                "number_of_components");
  option_realOrComplex = tool_file_format_getPropertyInt(TOOL_FILE_FORMAT(meth),
                                                         "real_or_complex");

  /* We now have a valid NetCDF file.
     We check the existence and the shape of all
     required variables and dimensions. */
  /* Get the grid size dimensions. */
  if (!nqGetDim(netcdfId, error, "number_of_grid_points_vector1", &varId, gridSize))
    {
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  if (!nqGetDim(netcdfId, error, "number_of_grid_points_vector2", &varId, gridSize + 1))
    {
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  if (!nqGetDim(netcdfId, error, "number_of_grid_points_vector3", &varId, gridSize + 2))
    {
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  size[0] = (int)gridSize[0];
  size[1] = (int)gridSize[1];
  size[2] = (int)gridSize[2];
  /* Get the spin dimension. */
  if (!nqGetDim(netcdfId, error, "number_of_components", &varId, &spinDim))
    {
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  /* Get real or complex. */
  if (!nqGetDim(netcdfId, error, "real_or_complex_density", &varId, &realOrComplex))
    {
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }

  /* Check values for spin and realOrComplex. */
  if (option_spin >= (int)spinDim)
    {
      g_warning("Requested value (%d) of spin component is out of range ([0;%d[).",
		option_spin, (int)spinDim);
      option_spin = 0;
    }
  if (option_realOrComplex >= (int)realOrComplex)
    {
      g_warning("Requested value (%d) of real or complex part is out of range ([0;%d[).",
		option_realOrComplex, (int)realOrComplex);
      option_realOrComplex = 0;
    }

  DBG_fprintf(stderr, "NQ Density : read dimensions.\n");
  DBG_fprintf(stderr, " | grid size (%d ; %d ; %d).\n", size[0], size[1], size[2]);
  DBG_fprintf(stderr, " | spin components %d.\n", (int)spinDim);
  DBG_fprintf(stderr, " | real or complex %d.\n", (int)realOrComplex);
    
  /* Check the rprimd matrix. */
  dimsRprimd[0] = 3;
  dimsRprimd[1] = 3;
  if (!nqCheckVar(netcdfId, error, "primitive_vectors", &varIdRprimd,
		              NC_DOUBLE, 2, dimsRprimd))
		{
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  /* Check the density values. */
  dimsDensity[0] = spinDim;
  dimsDensity[1] = gridSize[2];
  dimsDensity[2] = gridSize[1];
  dimsDensity[3] = gridSize[0];
  dimsDensity[4] = realOrComplex;
  if (!nqCheckVar(netcdfId, error, "density", &varIdDensity,
		              NC_DOUBLE, 5, dimsDensity))
		{
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }

  /* Ok, everything is OK in the file. We can load it. */
  /* Grep the box definition. */
  status = nc_get_vara_double(netcdfId, varIdRprimd, start, dimsRprimd, &rprimd[0][0]);
  if (status != NC_NOERR)
    {
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_FORMAT,
			   _("Retrieve value for variable 'primitive_vectors': %s."),
			   nc_strerror(status));
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  res = tool_matrix_reducePrimitiveVectors(boxGeometry, rprimd);
  if (!res)
    {
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_FORMAT,
			   _("The variable 'primitive_vectors' is not well formed"
			     " (the basis is not 3D)."));
      nqClose_netcdfFile(netcdfId);
      return TRUE;
    }
  
  /* Get one part of the density. */
  density = g_array_sized_new(FALSE, FALSE, sizeof(double),
                              gridSize[2] * gridSize[1] * gridSize[0]);
  density = g_array_set_size(density, gridSize[2] * gridSize[1] * gridSize[0]);

  fields = (GList*)0;
  for (i = (option_spin < 0)?0:option_spin ;
       i < ((option_spin < 0)?(int)spinDim:option_spin + 1) ; i++)
    for (j = (option_realOrComplex < 0)?0:option_realOrComplex ;
	 j < ((option_realOrComplex < 0)?(int)realOrComplex:option_realOrComplex + 1) ; j++)
      fields = g_list_append(fields, g_object_new(VISU_TYPE_SCALAR_FIELD_DATA, "label", visu_scalar_field_method_data_getFilename(data), NULL));
  
  for (lst = fields; lst; lst = g_list_next(lst))
    visu_scalar_field_method_data_addField(data, VISU_SCALAR_FIELD(g_object_ref(lst->data)));
  visu_scalar_field_method_data_ready(data);

  lst = fields;
  for (i = (option_spin < 0)?0:option_spin ;
       i < ((option_spin < 0)?(int)spinDim:option_spin + 1) ; i++)
    for (j = (option_realOrComplex < 0)?0:option_realOrComplex ;
	 j < ((option_realOrComplex < 0)?(int)realOrComplex:option_realOrComplex + 1) ; j++)
      {
	startDensity[0] = i;
	startDensity[4] = j;
	dimsDensity[0] = 1;
	dimsDensity[4] = 1;
	status = nc_get_vara_double(netcdfId, varIdDensity, startDensity, dimsDensity,
                                    (double*)density->data);
	if (status != NC_NOERR)
	  {
	    *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_FORMAT,
				 _("Retrieve value for variable 'density': %s."),
				 nc_strerror(status));
	    nqClose_netcdfFile(netcdfId);
	    g_array_unref(density);
            g_list_free_full(fields, g_object_unref);
	    return TRUE;
	  }
	/* Ok, now everything is in memory, we can populate the field object. */
	field = VISU_SCALAR_FIELD_DATA(lst->data);
        g_return_val_if_fail(field, FALSE);
        
        visu_scalar_field_setCommentary(VISU_SCALAR_FIELD(field), comment);
        box = visu_box_new(boxGeometry, VISU_BOX_PERIODIC);
        visu_box_setMargin(box, 0.f, FALSE);
        visu_boxed_setBox(VISU_BOXED(field), VISU_BOXED(box));
        g_object_unref(box);
        visu_scalar_field_setGridSize(VISU_SCALAR_FIELD(field), size);
        DBG_fprintf(stderr, "NQ Density : transfer density into field object.\n");
        visu_scalar_field_data_set(field, density, VISU_SCALAR_FIELD_DATA_XYZ);
        if ((int)spinDim == 1)
          option = tool_option_new("number_of_components",
                                   _("1, no spin information"), G_TYPE_INT);
        else if ((int)spinDim == 2)
          option = tool_option_new("number_of_components",
                                   _("1, spin-up ; 2, spin-down"), G_TYPE_INT);
        else if ((int)spinDim == 4)
          option = tool_option_new("number_of_components",
                                   _("1, average density ; "
                                     "[2;4], magnetisation vector"), G_TYPE_INT);
        else
          option = tool_option_new("number_of_components",
                                   _("unknown value"), G_TYPE_INT);
        g_value_set_int(tool_option_getValue(option), i + 1);
        visu_scalar_field_addOption(VISU_SCALAR_FIELD(field), option);

        lst = g_list_next(lst);
      }
  g_array_unref(density);
  if (comment)
    g_free(comment);
  g_list_free_full(fields, g_object_unref);

#if DEBUG == 1
  g_timer_stop(timer);
  fprintf(stderr, "ETSF: density parsed in %g milli-s.\n",
          g_timer_elapsed(timer, &fractionTimer)/1e-3);
  g_timer_destroy(timer);
#endif

  nqClose_netcdfFile(netcdfId);
  
  return TRUE;
}
