/*   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 "toolFortran.h"
#include <visu_dataloadable.h>

/**
 * SECTION:toolFortran
 * @short_description: Introduces routines to read the binary Fortran data format.
 *
 * <para>In Fortran binary data are written inside tags. These tags
 * give the size to the data that are between. The routines in this
 * module can read these tags and the data inside. One must know the
 * endianness of the file and the kind of data to be read (integer,
 * float, double...). If the first tag is known, one can test the
 * endianness of the file calling tool_files_fortran_testEndianness().</para>
 * <para>The size of the tag (32 bits or 64 bits) is not modifiable
 * for the moment and is fixed at 32 bits. This may be changed in the
 * futur with the same kind of things that for endianness.</para>
 */

/**
 * tool_files_fortran_open:
 * @file: a #ToolFiles object.
 * @filename: a file path.
 * @error: an error location.
 *
 * Open @filename as a Fortran binary file.
 *
 * Since: 3.8
 *
 * Returns: TRUE on success.
 **/
gboolean tool_files_fortran_open(ToolFiles *file,
                                 const gchar *filename, GError **error)
{
  if (!tool_files_open(file, filename, error))
    return FALSE;
  tool_files_setEncoding(file, NULL);
  return TRUE;
}

/**
 * tool_files_fortran_readFlag:
 * @flux: a pointer on an opened file ;
 * @nb: (out): a location t store the value of the flag ;
 * @endianness: reverse or not the order of multi-bytes.
 * @error: a pointer to an error location ;
 *
 * Read the flag of a record (a 32bits integer).
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readFlag(ToolFiles *flux, gsize *nb,
                                     ToolFortranEndianId endianness, GError **error)
{
  guint n;

  if (tool_files_read(flux, &n, sizeof(guint), error) != G_IO_STATUS_NORMAL)
    return FALSE;

  DBG_fprintf(stderr, "Tool Fortran: reading flag %d %d (%d).\n",
              n, GUINT32_SWAP_LE_BE(n), endianness);
  if (endianness == TOOL_FORTRAN_ENDIAN_CHANGE)
    *nb = GUINT32_SWAP_LE_BE(n);
  else
    *nb = n;
  return TRUE;
}

gboolean tool_files_fortran_readCharacter(ToolFiles *flux, char *var, gsize nb,
				   GError **error, ToolFortranEndianId endianness,
				   gboolean testFlag, gboolean store)
{
  if (testFlag && !tool_files_fortran_checkFlag(flux, nb, endianness, error))
    return FALSE;

  if ((store && tool_files_read(flux, var, sizeof(char) * nb, error) != G_IO_STATUS_NORMAL) ||
      (!store && tool_files_skip(flux, sizeof(char) * nb, error) != G_IO_STATUS_NORMAL))
    return FALSE;

  if (testFlag && !tool_files_fortran_checkFlag(flux, nb, endianness, error))
    return FALSE;

  return TRUE;
}
/**
 * tool_files_fortran_readString:
 * @flux: a #ToolFiles object.
 * @var: (out): a location to store the read string.
 * @nb: the length of the expected string.
 * @endianness: the endianness of @flux.
 * @testFlag: a boolean.
 * @error: an error location.
 *
 * Read a string from the next Fortran record. This string is
 * allocated with malloc and should be freed after use. The expected
 * string is supposed to employ @nb bytes on disk, padded with white
 * spaces. The output string is trimmed from whitespaces though.
 *
 * Since: 3.8
 *
 * Returns: TRUE on success.
 **/
gboolean tool_files_fortran_readString(ToolFiles *flux, gchar **var, gsize nb,
                                       ToolFortranEndianId endianness,
                                       gboolean testFlag, GError **error)
{
  if (testFlag && !tool_files_fortran_checkFlag(flux, nb, endianness, error))
    return FALSE;

  if (var)
    *var = g_malloc(sizeof(gchar) * (nb + 1));
  if ((var && tool_files_read(flux, *var, sizeof(char) * nb, error) != G_IO_STATUS_NORMAL) ||
      (!var && tool_files_skip(flux, sizeof(char) * nb, error) != G_IO_STATUS_NORMAL))
    {
      if (var)
        g_free(*var);
      return FALSE;
    }
  if (var)
    {
      (*var)[nb] = '\0';
      g_strchomp(*var);
    }
  
  if (testFlag && !tool_files_fortran_checkFlag(flux, nb, endianness, error))
    {
      if (var)
        g_free(*var);
      return FALSE;
    }

  return TRUE;
}
static gboolean _readArray(ToolFiles *flux, GArray **var, gsize esize, gsize nb,
                           ToolFortranEndianId endianness,
                           gboolean testFlag, GError **error)
{
  if (testFlag && !tool_files_fortran_checkFlag(flux, esize * nb, endianness, error))
    return FALSE;

  /* Read the data. */
  if (var)
    *var = g_array_sized_new(FALSE, FALSE, esize, nb);
  if ((var && tool_files_read(flux, (*var)->data, esize * nb, error) != G_IO_STATUS_NORMAL) ||
      (!var && tool_files_skip(flux, esize * nb, error) != G_IO_STATUS_NORMAL))
    {
      if (var)
        g_array_unref(*var);
      return FALSE;
    }
  if (var)
    g_array_set_size(*var, nb);
  
  if (testFlag && !tool_files_fortran_checkFlag(flux, esize * nb, endianness, error))
    {
      if (var)
        g_array_unref(*var);
      return FALSE;
    }

  return TRUE;
}
/**
 * tool_files_fortran_readInteger:
 * @flux: a pointer on an opened file ;
 * @var: (out): an integer location.
 * @error: a pointer to an error location ;
 * @endianness: reverse or not the order of multi-bytes ;
 *
 * Read one integer without reading enclosing flags.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readInteger(ToolFiles *flux, gint *var,
                                        ToolFortranEndianId endianness, GError **error)
{
  char c[sizeof(gint)];
  register guint ks, l;
  gint *val;

  if (tool_files_read(flux, (char*)var, sizeof(gint), error) != G_IO_STATUS_NORMAL)
    return FALSE;

  if (endianness == TOOL_FORTRAN_ENDIAN_CHANGE)
    {
      ks = sizeof(int) - 1;
      for(l=0; l<sizeof(int); l++)
        c[l] = *((char*)var + ks - l);
      val = (gint*)c;
      *var = *val;
    }
  return TRUE;
}
/**
 * tool_files_fortran_readIntegerArray:
 * @flux: a pointer on an opened file ;
 * @var: (element-type int) (out): an array location.
 * @nb: the expected size of the array @var ;
 * @error: a pointer to an error location ;
 * @endianness: reverse or not the order of multi-bytes ;
 * @testFlag: if TRUE, read start and stop flags and test their
 * values ;
 *
 * Read an array of integers from a fortran record.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readIntegerArray(ToolFiles *flux, GArray **var, gsize nb,
                                             ToolFortranEndianId endianness,
                                             gboolean testFlag, GError **error)
{
  char c[sizeof(guint)];
  register guint k, ks, l;
  guint *val, *data;

  if (!_readArray(flux, var, sizeof(gint), nb, endianness, testFlag, error))
    return FALSE;

  if (var && endianness == TOOL_FORTRAN_ENDIAN_CHANGE)
    {
      data = (guint*)(*var)->data;
      for(k=0; k<nb; k++)
	{
	  ks = (k+1)*sizeof(guint) - 1;
	  for(l=0; l<sizeof(guint); l++)
	    c[l] = *((char*)(*var)->data + ks - l);
	  val = (guint*)c;
	  data[k] = *val;
	}
    }
  return TRUE;
}
/**
 * tool_files_fortran_readRealArray:
 * @flux: a pointer on an opened file ;
 * @var: (out) (element-type float): an allocated array of float ;
 * @nb: the expected size of the array @var ;
 * @endianness: reverse or not the order of multi-bytes ;
 * @testFlag: if TRUE, read start and stop flags and test their
 * values ;
 * @error: a pointer to an error location ;
 *
 * Read an array of reals from a fortran record.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readRealArray(ToolFiles *flux, GArray **var, gsize nb,
                                          ToolFortranEndianId endianness,
                                          gboolean testFlag, GError **error)
{
  char c[sizeof(float)];
  register guint k, ks, l;
  float *val, *data;

  if (!_readArray(flux, var, sizeof(gfloat), nb, endianness, testFlag, error))
    return FALSE;

  if (var && endianness == TOOL_FORTRAN_ENDIAN_CHANGE)
    {
      data = (float*)(*var)->data;
      for(k=0; k<nb; k++)
	{
	  ks = (k+1)*sizeof(float) - 1;
	  for(l=0; l<sizeof(float); l++)
	    c[l] = *((char*)(*var)->data + ks - l);
	  val = (float*)c;
	  data[k] = *val;
	}
    }
  return TRUE;
}
/**
 * tool_files_fortran_readDouble:
 * @flux: a pointer on an opened file ;
 * @var: (out): a double location.
 * @error: a pointer to an error location ;
 * @endianness: reverse or not the order of multi-bytes ;
 *
 * Read one double without reading enclosing flags.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readDouble(ToolFiles *flux, gdouble *var,
                                       ToolFortranEndianId endianness, GError **error)
{
  char c[sizeof(gdouble)];
  register guint ks, l;
  gdouble *val;

  if (tool_files_read(flux, (char*)var, sizeof(gdouble), error) != G_IO_STATUS_NORMAL)
    return FALSE;

  if (endianness == TOOL_FORTRAN_ENDIAN_CHANGE)
    {
      ks = sizeof(gdouble) - 1;
      for(l=0; l<sizeof(gdouble); l++)
        c[l] = *((char*)var + ks - l);
      val = (gdouble*)c;
      *var = *val;
    }
  return TRUE;
}
/**
 * tool_files_fortran_readDoubleArray:
 * @flux: a pointer on an opened file ;
 * @var: (element-type double) (out): an array location.
 * @nb: the expected size of the array @var ;
 * @error: a pointer to an error location ;
 * @endianness: reverse or not the order of multi-bytes ;
 * @testFlag: if TRUE, read start and stop flags and test their values
 * ;
 *
 * Read an array of doubles from a fortran record.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_readDoubleArray(ToolFiles *flux, GArray **var, gsize nb,
                                            ToolFortranEndianId endianness,
                                            gboolean testFlag, GError **error)
{
  char c[sizeof(double)];
  register guint k, ks, l;
  double *val, *data;

  if (!_readArray(flux, var, sizeof(gdouble), nb, endianness, testFlag, error))
    return FALSE;

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

/**
 * tool_files_fortran_testEndianness:
 * @flux: a pointer on an opened file ;
 * @nb: the value of the flag to read ;
 * @endianness: (out): a location to store the endianness.
 *
 * Read a flag and compare the value with @nb for little and big endian.
 * It return the value of endianness to be used after. The file is rewind after the
 * call.
 *
 * Returns: TRUE if everything went right.
 */
gboolean tool_files_fortran_testEndianness(ToolFiles *flux, gsize nb,
                                           ToolFortranEndianId *endianness)
{
  gsize n;
  guint nf;
  
  if (!tool_files_fortran_readFlag(flux, &n, TOOL_FORTRAN_ENDIAN_KEEP, NULL))
    return FALSE;
  nf = n;
  DBG_fprintf(stderr, "Tool Fortran: testing endianness %d %d (%ld).\n",
              nf, GUINT32_SWAP_LE_BE(nf), nb);
  *endianness = TOOL_FORTRAN_ENDIAN_KEEP;
  if (GUINT32_SWAP_LE_BE(nf) == (guint)nb)
    *endianness = TOOL_FORTRAN_ENDIAN_CHANGE;
  else if (n != nb)
    return FALSE;

  return TRUE;
}

/**
 * tool_files_fortran_checkFlag:
 * @flux: a #ToolFiles object.
 * @ncheck: the size to be checked for.
 * @endian: the endianness of @flux.
 * @error: a location for an error.
 *
 * Read the next Fortran flag and check that it's content is equal to @ncheck.
 *
 * Since: 3.8
 *
 * Returns: TRUE on successful read.
 **/
gboolean tool_files_fortran_checkFlag(ToolFiles *flux, gsize ncheck,
                                      ToolFortranEndianId endian, GError **error)
{
  gsize mcheck;
  
  if (!tool_files_fortran_readFlag(flux, &mcheck, endian, error))
    return FALSE;

  if (ncheck != mcheck)
    {
      g_set_error(error, VISU_DATA_LOADABLE_ERROR, DATA_LOADABLE_ERROR_FORMAT,
                  _("wrong fortran syntax, flag size unmatched (%ld != %ld).\n"),
                  ncheck, mcheck);
      return FALSE;
    }
  return TRUE;
}
