/*   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 "dumpToXyz.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include <visu_tools.h>
#include <visu_dataloadable.h>

/**
 * SECTION:dumpToXyz
 * @short_description: add an export capability of current positions.
 *
 * This provides a write routine to export V_Sim current
 * coordinates. It has several options to output or not hiddden nodes
 * or replicated nodes.
 */

static gboolean writeDataInXyz(VisuDumpData *format, const char* filename,
                               VisuData *dataObj, GError **error);

static VisuDumpData *xyz;

const VisuDumpData* visu_dump_xyz_getStatic()
{
  const gchar *typeXYZ[] = {"*.xyz", (char*)0};
#define descrXYZ _("Xyz file (current positions)")

  if (xyz)
    return xyz;

  xyz = visu_dump_data_new(descrXYZ, typeXYZ, writeDataInXyz);
  
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(xyz), "expand_box",
                                      _("Expand the bounding box"), TRUE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(xyz), "type_alignment",
                                      _("Export nodes sorted by elements"), FALSE);

  return xyz;
}

static gboolean writeDataInXyz(VisuDumpData *format, const char* filename,
                               VisuData *dataObj, GError **error)
{
  const gchar *nom;
  gchar *prevFile;
  gchar firstLine[256];
  gboolean expand, eleSort;
  gint nb;
  float xyz[3], ext[3], vertices[8][3];
  VisuNodeArrayIter iter;
  GString *output;
  VisuBoxBoundaries bc;
  gchar *bcStr[8] = {"FreeBC", "wire", "wire", "surface", "wire", "surface", "surface", "periodic"};
  const gchar *nodeComment;
  double ene;
  VisuBox *boxObj;

  g_return_val_if_fail(error && !*error, FALSE);

  expand = tool_file_format_getPropertyBoolean(TOOL_FILE_FORMAT(format), "expand_box");
  eleSort = tool_file_format_getPropertyBoolean(TOOL_FILE_FORMAT(format),
                                                "type_alignment");

  DBG_fprintf(stderr, "Dump XYZ: begin export of current positions...\n");

  output = g_string_new("");

  boxObj = visu_boxed_getBox(VISU_BOXED(dataObj));
  visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter);
  /* The number of elements will be prepended later... */
  /* The commentary line. */
  bc = visu_box_getBoundary(boxObj);
  if (bc != VISU_BOX_FREE)
    {
      visu_box_getVertices(boxObj, vertices, expand);
      fprintf(stderr, "Dump XYZ: box is\n");
      fprintf(stderr, " | v[0] %g, %g, %g\n", vertices[0][0], vertices[0][1], vertices[0][2]);
      fprintf(stderr, " | v[1] %g, %g, %g\n", vertices[1][0], vertices[1][1], vertices[1][2]);
      fprintf(stderr, " | v[2] %g, %g, %g\n", vertices[2][0], vertices[2][1], vertices[2][2]);
      fprintf(stderr, " | v[3] %g, %g, %g\n", vertices[3][0], vertices[3][1], vertices[3][2]);
      fprintf(stderr, " | v[4] %g, %g, %g\n", vertices[4][0], vertices[4][1], vertices[4][2]);
      vertices[1][0] -= vertices[0][0];
      vertices[1][1] -= vertices[0][1];
      vertices[1][2] -= vertices[0][2];
      vertices[2][0] -= vertices[0][0];
      vertices[2][1] -= vertices[0][1];
      vertices[2][2] -= vertices[0][2];
      vertices[3][0] -= vertices[0][0];
      vertices[3][1] -= vertices[0][1];
      vertices[3][2] -= vertices[0][2];
      vertices[4][0] -= vertices[0][0];
      vertices[4][1] -= vertices[0][1];
      vertices[4][2] -= vertices[0][2];
      if (vertices[1][1] == 0.f && vertices[1][2] == 0.f &&
	  vertices[3][0] == 0.f && vertices[3][2] == 0.f &&
	  vertices[4][0] == 0.f && vertices[4][1] == 0.f)
	g_string_append_printf(output, "%s %17.8g %17.8g %17.8g ", bcStr[bc],
			       vertices[1][0], vertices[3][1], vertices[4][2]);
      else
	g_warning("Can't export box, not orthogonal.");
    }
  if (VISU_IS_DATA_LOADABLE(dataObj))
    {
      nom = visu_data_loadable_getFilename(VISU_DATA_LOADABLE(dataObj), 0);
      prevFile = g_path_get_basename(nom);
      g_string_append_printf(output, "# V_Sim export to xyz from '%s'", prevFile);
      g_free(prevFile);
    }
  else
    {
      g_warning("Can't get the name of the file to export.");
      g_string_append_printf(output, "# V_Sim export to xyz");
    }
  g_string_append(output, "\n");

  visu_box_getVertices(boxObj, vertices, FALSE);
  if (expand)
    visu_box_getExtension(boxObj, ext);
  else
    {
      ext[0] = 0.;
      ext[1] = 0.;
      ext[2] = 0.;
    }

  nb = 0;
  for (visu_node_array_iterStartNumber(VISU_NODE_ARRAY(dataObj), &iter); iter.node && iter.element;
       (eleSort)?visu_node_array_iterNext(VISU_NODE_ARRAY(dataObj), &iter):
       visu_node_array_iterNextNodeNumber(VISU_NODE_ARRAY(dataObj), &iter))
    {
      visu_data_getNodePosition(dataObj, iter.node, xyz);
      if (visu_element_getRendered(iter.element) && iter.node->rendered)
	{
	  xyz[0] += ext[0] * vertices[1][0] + ext[1] * vertices[3][0] +
	    ext[2] * vertices[4][0];
	  xyz[1] += ext[1] * vertices[3][1] + ext[2] * vertices[4][1];
	  xyz[2] += ext[2] * vertices[4][2];

	  nb += 1;
	  g_string_append_printf(output, "%s %17.8g %17.8g %17.8g",
				 iter.element->name,
				 xyz[0], xyz[1], xyz[2]);
	  nodeComment = visu_data_getNodeLabelAt(dataObj, iter.node);
	  if (nodeComment)
	    g_string_append_printf(output, " %s", nodeComment);
          g_string_append(output, "\n");
	}
    }

  g_string_prepend(output, "\n");
  g_object_get(G_OBJECT(dataObj), "totalEnergy", &ene, NULL);
  if (ene != G_MAXFLOAT)
    {
      sprintf(firstLine, " %22.16f", ene / 27.21138386);
      g_string_prepend(output, firstLine);
    }
  switch (visu_box_getUnit(boxObj))
    {
    case TOOL_UNITS_ANGSTROEM:
      sprintf(firstLine, " %d angstroem", nb);
      break;
    case TOOL_UNITS_BOHR:
      sprintf(firstLine, " %d atomic", nb);
      break;
    default:
      sprintf(firstLine, " %d", nb);
      break;
    }
  g_string_prepend(output, firstLine);

  g_file_set_contents(filename, output->str, -1, error);
  g_string_free(output, TRUE);

  return TRUE;
}
