/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2016)
  
	Adresse 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 : Damien
	CALISTE, laboratoire L_Sim, (2016)

	E-mail address:
	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 <glib.h>
#include <visu_tools.h>

#include "toolArray.h"

/**
 * SECTION:toolArray
 * @short_description: read text files formated in columns.
 *
 * <para>Defines various routines to read text files formatted in columns.</para>
 */

static GQuark quark = 0;
/**
 * tool_array_getErrorQuark:
 *
 * Internal routine for error handling.
 *
 * Since: 3.8
 *
 * Returns: the #GQuark associated to errors related to data
 * files.
 */
GQuark tool_array_getErrorQuark()
{
  if (!quark)
    quark =  g_quark_from_static_string("ToolArray");
  return quark;
}

/**
 * tool_array_fromFile:
 * @filename: (type filename): a filename.
 * @nColumns: (out caller-allocates): a location for an integer.
 * @error: an error location.
 *
 * Read a data column file.
 *
 * Since: 3.8
 *
 * Returns: (transfer full) (element-type float): a newly allocated #GArray.
 **/
GArray* tool_array_fromFile(const gchar *filename, guint *nColumns, GError **error)
{
  GArray *array;
  GIOChannel *readFrom;
  GIOStatus status;
  GError *err;
  GString *line;
  gboolean voidLine;
  gsize term;
  gchar **dataRead;
  float *data, fval;
  guint i, nb0, nb;
#if DEBUG == 1
  GTimer *timer;
  gulong fractionTimer;
#endif

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

  if (nColumns)
    *nColumns = 0;

  readFrom = g_io_channel_new_file(filename, "r", error);
  if (!readFrom)
    return (GArray*)0;

  g_debug("Tool Array: begin reading file '%s'.", filename);
#if DEBUG == 1
  timer = g_timer_new();
  g_timer_start(timer);
#endif

  array = g_array_new(FALSE, FALSE, sizeof(float));

  line = g_string_new("");
  data = (float*)0;

  /* If the file is not finished, we read until a non-void line
     and return this line. */
  nb0 = 0;
  do
    {
      voidLine = TRUE;
      do
        {
          err = (GError*)0;
          status = g_io_channel_read_line_string(readFrom, line, &term, &err);
          if (status == G_IO_STATUS_NORMAL)
            {
              g_strchug(line->str);
              voidLine = (line->str[0] == '#' ||
                          line->str[0] == '!' ||
                          line->str[0] == '\0');
            }
          if (!voidLine)
            {
              dataRead = g_strsplit_set(line->str, " \t;:\n", TOOL_MAX_LINE_LENGTH);
              if (!data)
                {
                  nb0 = 0;
                  for (i = 0; dataRead[i]; i++)
                    if (dataRead[i][0] && 1 == sscanf(dataRead[i], "%f", &fval))
                      nb0 += 1;
                  data = g_malloc(sizeof(float) * nb0);
                }
              nb = 0;
              for (i = 0; dataRead[i] && nb < nb0; i++)
                if (1 == sscanf(dataRead[i], "%f", data + nb))
                  {
                    g_debug("   '%s' - '%f'",
                                dataRead[i], data[nb]);
                    nb += 1;
                  }
              for (i = nb; i < nb0; i++)
                data[i] = 0.f;
              g_strfreev(dataRead);
              voidLine = (nb == 0);
            }          
        }
      while (status == G_IO_STATUS_NORMAL && voidLine);
      if (status == G_IO_STATUS_ERROR)
        {
          g_string_free(line, TRUE);
          g_free(data);
          g_array_free(array, TRUE);
          status = g_io_channel_shutdown(readFrom, FALSE, (GError**)0);
          g_io_channel_unref(readFrom);
          *error = err;
          return (GArray*)0;
        }
      if (!voidLine)
        g_array_append_vals(array, data, nb0);
    } while (status == G_IO_STATUS_NORMAL);

  g_free(data);
  g_string_free(line, TRUE);

  status = g_io_channel_shutdown(readFrom, FALSE, (GError**)0);
  g_io_channel_unref(readFrom);

#if DEBUG == 1
  g_timer_stop(timer);
  g_debug("Tool Array: %d (%d) data associated in %g micro-s.", array->len, nb0, g_timer_elapsed(timer, &fractionTimer)/1e-6);
  g_timer_destroy(timer);
#endif

  if (array->len == 0)
    g_set_error_literal(error, TOOL_ARRAY_ERROR, TOOL_ARRAY_ERROR_NO_COLUMN,
                        _("Can't find any columns with numbers.\n"
                          "Valid format are as much numbers as desired, separated"
                          " by any of the following characters : [ ;:\\t]."));

  if (nColumns)
    *nColumns = nb0;
  return array;
}

/**
 * tool_array_sizedFromFile:
 * @filename: a path;
 * @size: expected number of read lines;
 * @nColumns: (out caller-allocates): number of read columns;
 * @error: an error pointer.
 *
 * Like tool_array_fromFile(), but check that the number of read lines
 * corresponds to the expected value given by @size.
 *
 * Since: 3.8
 *
 * Returns: (transfer full) (element-type float): a newly allocated #GArray.
 **/
GArray* tool_array_sizedFromFile(const gchar *filename, guint size,
                                 guint *nColumns, GError **error)
{
  GArray *array;
  guint nRead;
  guint n;

  array = tool_array_fromFile(filename, &n, error);
  nRead = array ? array->len / n : 0;
  if (nRead != size)
    {
      if (array)
        g_array_set_size(array, 0);
      g_set_error(error, TOOL_ARRAY_ERROR, TOOL_ARRAY_ERROR_MISSING_DATA,
                  _("There is a different number of data (%d) compared to expected (%d)."),
                  nRead, size);
    }
  if (nColumns)
    *nColumns = n;

  return array;
}
