/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	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-2005)

	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 <netcdf.h>
#include <string.h>

#include "nq_basic.h"
#include "nq_structure.h"
#include "nq_density.h"
#include <visu_tools.h>
#include <visu_basic.h>
#include <visu_dataatomic.h>

#define NANOQUANTA_DESCRIPTION _("<span size=\"smaller\">" \
				 "This plug-in introduces support for\n" \
				 "<b>ETSF</b> file format defined by the\n" \
				 "European network <b>NANOQUANTA</b>.</span>")
#define NANOQUANTA_AUTHORS     _("Caliste Damien:\n   structure/density loading.")

static gchar *iconPath;

/* Required methods for a loadable module. */
gboolean etsfInit()
{
  DBG_fprintf(stderr, "ETSF: loading plug-in 'nanoquanta'...\n");

  DBG_fprintf(stderr, "ETSF: declare a new rendering load method.\n");
  visu_data_atomic_class_addLoader(visu_data_loader_ETSF_getStatic());

  iconPath = g_build_filename(V_SIM_PIXMAPS_DIR, "nanoquanta.png", NULL);

  DBG_fprintf(stderr, "ETSF: declare a new density load method.\n");
  nqDensityInit();

  return TRUE;
}

const char* etsfGet_description()
{
  return NANOQUANTA_DESCRIPTION;
}

const char* etsfGet_authors()
{
  return NANOQUANTA_AUTHORS;
}

const char* etsfGet_icon()
{
  return iconPath;
}

GQuark nqError_quark()
{
  return g_quark_from_static_string("nanoquanta");
}



gboolean nqOpen_netcdfFile(const char* filename, int *netcdfId, GError **error)
{
  int status, i;
  char *varsNames[3] = {"file_format", "file_format_version", "Conventions"};
  nc_type varsType[3] = {NC_CHAR, NC_FLOAT, NC_CHAR};
  nc_type altVarsType[3] = {NC_CHAR, NC_DOUBLE, NC_CHAR};
  size_t varsLength[3] = {80, 1, 80};
  nc_type readType;
  size_t readLength[3];
  char format[256];
  float version;

  g_return_val_if_fail(error && *error == (GError*)0, FALSE);
  g_return_val_if_fail(netcdfId && filename, FALSE);

  DBG_fprintf(stderr, "NQ Basic: opening file '%s' as a NetCDF file.\n", filename);
  /* Open the file as a NETCDF file. */
  status = nc_open(filename, NC_NOWRITE, netcdfId);
  if (status != NC_NOERR)
    {
      DBG_fprintf(stderr, " | not a NetCDF file, can't open.\n");
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_OPEN,
			   "%s", nc_strerror(status));
      return FALSE;
    }

  /* From here, the file is opened. */

  /* Grep the header variables to check that it is a NETCDF file
     following rules of NANOQUANTA specifications. */
  DBG_fprintf(stderr, "NQ Basic: checking header of file '%s'.\n", filename);
  /* Check lengths and types. */
  for (i = 0; i < 3; i++)
    {
      status = nc_inq_att(*netcdfId, NC_GLOBAL, varsNames[i], &readType, readLength + i);
      if (status != NC_NOERR)
        {
          DBG_fprintf(stderr, " | cannot read header element %d (%s).\n", i, nc_strerror(status));
          *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
			       "inquiring global attribute '%s' raises: %s",
                               varsNames[i], nc_strerror(status));
          nqClose_netcdfFile(*netcdfId);
          return FALSE;
        }
      DBG_fprintf(stderr, " | header '%s' : type %d (%d), length %d (%d).\n",
                  varsNames[i], (int)readType, (int)varsType[i],
                  (int)readLength[i], (int)varsLength[i]);
      if ((readType != varsType[i] && readType != altVarsType[i]) || 
           readLength[i] > varsLength[i])
        {
          DBG_fprintf(stderr, " | header not valid.\n");
          *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
                               _("Global attribute '%s' has a wrong "
                                 "length or type.\n"), varsNames[i]);
          nqClose_netcdfFile(*netcdfId);
          return FALSE;
        }
    }
  /* Check values. */
  status = nc_get_att_text(*netcdfId, NC_GLOBAL, varsNames[0], format);
  if (status != NC_NOERR)
    {
      DBG_fprintf(stderr, " | cannot read format.\n");
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
			   "reading global attribute '%s' raises: %s",
                           varsNames[0], nc_strerror(status));
      nqClose_netcdfFile(*netcdfId);
      return FALSE;
    }
  format[readLength[0]] = '\0';
  DBG_fprintf(stderr, " | header '%s' value '%s'.\n", varsNames[0], format);
  if (strcmp(format, "ETSF Nanoquanta"))
    {
      DBG_fprintf(stderr, " | wrong format '%s'.\n", format);
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
			   _("Variable 'file_format' should be "
			     "'ETSF Nanoquanta' but is '%s'.\n"), format);
      nqClose_netcdfFile(*netcdfId);
      return FALSE;
    }
  status = nc_get_att_float(*netcdfId, NC_GLOBAL, varsNames[1], &version);
  if (status != NC_NOERR)
    {
      DBG_fprintf(stderr, " | cannot read version.\n");
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
			   "reading global attribute '%s' raises: %s",
                           varsNames[1], nc_strerror(status));
      nqClose_netcdfFile(*netcdfId);
      return FALSE;
    }
  DBG_fprintf(stderr, " | header '%s' value %f.\n", varsNames[1], version);
  if (version < 1.2)
    {
      DBG_fprintf(stderr, " | version too small (%f).\n", version);
      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_HEADER,
			   _("Supported version are 1.2 and over but"
			     " this file is only %f.\n"), version);
      nqClose_netcdfFile(*netcdfId);
      return FALSE;
    }

  return TRUE;
}

gboolean nqClose_netcdfFile(int netcdfId)
{
  int status;

  status = nc_close(netcdfId);
  if (status != NC_NOERR)
    {
      g_warning("%s", nc_strerror(status));
      return FALSE;
    }

  return TRUE;
}

static gboolean nqErrorReport(GError **error, const char *message, ...)
{
  va_list args;
  gchar *formatted;

  if (error)
    {
      va_start(args, message);
      formatted = g_strdup_vprintf(message, args);
      va_end(args);

      *error = g_error_new(NQ_ERROR, NQ_ERROR_FILE_FORMAT, "%s", formatted);

      g_free(formatted);
    }
  
  return FALSE;
}

gboolean nqGetDim(int netcdfId, GError **error, char *name, int *varId, size_t *value)
{
  int status;

  /* Grep the number of elements. */
  status = nc_inq_dimid(netcdfId, name, varId);
  if (status != NC_NOERR)
    return nqErrorReport(error, _("Reading '%s': %s."),
                         name, nc_strerror(status));
  status = nc_inq_dimlen(netcdfId, *varId, value);
  if (status != NC_NOERR)
    return nqErrorReport(error, _("Retrieve value for variable '%s': %s."),
                         name, nc_strerror(status));
  return TRUE;
}

gboolean nqCheckVar(int netcdfId, GError **error, char *name, int *varId,
			              nc_type ncType, int nbDims, size_t *nbEleDims)
{
  int status;
  nc_type localType;
  char *typeNames[] = {"NAT", "BYTE", "CHAR", "SHORT", "INT", "FLOAT", "DOUBLE"};
  int localDims;
  int *localNbDims;
  int i;
  size_t dimSize;

  status = nc_inq_varid(netcdfId, name, varId);
  if (status != NC_NOERR)
    return nqErrorReport(error, _("Reading '%s': %s."),
			    name, nc_strerror(status));
  status = nc_inq_vartype(netcdfId, *varId, &localType);
  if (status != NC_NOERR)
    return nqErrorReport(error, _("Checking variable '%s': %s."),
			    name, nc_strerror(status));
  if (localType != ncType)
    return nqErrorReport(error, _("Variable '%s' should be of type '%s'."),
			    name, typeNames[ncType]);
  status = nc_inq_varndims(netcdfId, *varId, &localDims);
  if (status != NC_NOERR)
    return nqErrorReport(error, _("Checking variable '%s': %s."),
			    name, nc_strerror(status));
  if (localDims != nbDims)
    return nqErrorReport(error,
			    _("Variable '%s' should be a %d dimension array."),
			    name, nbDims);
  localNbDims = g_malloc(sizeof(int) * nbDims);
  status = nc_inq_vardimid(netcdfId, *varId, localNbDims);
  if (status != NC_NOERR)
    {
      g_free(localNbDims);
      return nqErrorReport(error, _("Checking variable '%s': %s."),
			      name, nc_strerror(status));
    }
  for (i = 0; i< nbDims; i++)
    {
      status = nc_inq_dimlen(netcdfId, localNbDims[i], &dimSize);
      if (status != NC_NOERR)
	{
	  g_free(localNbDims);
	  return nqErrorReport(error, _("Checking dimension ID %d: %s."),
				  localNbDims[i], nc_strerror(status));
	}
      if (dimSize != nbEleDims[i])
      {
	g_free(localNbDims);
	return nqErrorReport(error,
				_("Variable '%s' is not consistent with"
				  " declaration of dimensions."), name);
      }
    }
  g_free(localNbDims);
  return TRUE;
}

