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

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

#include <visu_tools.h>
#include <visu_dataloadable.h>
#include <extraFunctions/gdiff.h>

static VisuDumpData *ascii = NULL;

/**
 * SECTION:dumpToAscii
 * @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 writeDataInAscii(VisuDumpData *format, const char* filename,
				 VisuData *dataObj, GError **error);

const VisuDumpData* visu_dump_ascii_getStatic()
{
  const gchar *typeASCII[] = {"*.ascii", (char*)0};
#define descrASCII _("ASCII file (current positions)")

  if (ascii)
    return ascii;

  ascii = visu_dump_data_new(descrASCII, typeASCII, writeDataInAscii);
  
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "delete_hidden_nodes",
				_("Don't output hidden nodes"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "comment_hidden_nodes",
				_("Comment hidden nodes (if output)"), TRUE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "expand_box",
				_("Keep primitive box (in case of node expansion)"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "reduced_coordinates",
				_("Export positions in reduced coordinates"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "angdeg_box",
				_("Export box as lengths and angles"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ascii), "type_alignment",
				_("Export nodes sorted by elements"), FALSE);

  return ascii;
}

static gboolean writeDataInAscii(VisuDumpData *format, const char* filename,
				 VisuData *dataObj, GError **error)
{
  const gchar *nom;
  gchar *prevFile;
  char tmpChr;
  gchar *diff;
  gboolean suppr, comment, expand, reduced, angdeg, eleSort;
  float xyz[3], ext[3], uvw[3], vertices[8][3], box[6];
  double ene;
  VisuNodeArrayIter iter;
  GString *output;
  const gchar *nodeComment;
  ToolFileFormatIter it;
  VisuBox *boxObj;
  VisuDataDiff *geodiff;
  VisuBoxBoundaries bc;

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

  comment = TRUE;
  expand  = FALSE;
  suppr   = FALSE;
  reduced = FALSE;
  angdeg  = FALSE;
  eleSort = FALSE;
  it.lst = (GList*)0;
  for (tool_file_format_iterNextProperty(TOOL_FILE_FORMAT(format), &it); it.lst;
       tool_file_format_iterNextProperty(TOOL_FILE_FORMAT(format), &it))
    {
      DBG_fprintf(stderr, "Dump ASCII: test property '%s'.\n", it.name);
      if (strcmp(it.name, "comment_hidden_nodes") == 0)
	comment = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "expand_box") == 0)
	expand  = !g_value_get_boolean(it.val);
      else if (strcmp(it.name, "delete_hidden_nodes") == 0)
	suppr   = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "reduced_coordinates") == 0)
	reduced = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "angdeg_box") == 0)
	angdeg  = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "type_alignment") == 0)
	eleSort = g_value_get_boolean(it.val);
    }

  DBG_fprintf(stderr, "Dump ASCII: begin export of current positions...\n");
  DBG_fprintf(stderr, " | comment %d ;\n", comment);
  DBG_fprintf(stderr, " | expand  %d ;\n", expand);
  DBG_fprintf(stderr, " | suppr   %d ;\n", suppr);
  DBG_fprintf(stderr, " | reduced %d ;\n", reduced);
  DBG_fprintf(stderr, " | angdeg  %d ;\n", angdeg);
  DBG_fprintf(stderr, " | eleSort %d ;\n", eleSort);

  output = g_string_new("");

  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 ascii from '%s'\n", prevFile);
      g_free(prevFile);
    }
  else
    {
      g_string_append(output, "# V_Sim export to ascii\n");
    }

  boxObj = visu_boxed_getBox(VISU_BOXED(dataObj));
  visu_box_getVertices(boxObj, vertices, expand);
  if (angdeg)
    {
      box[0] = sqrt((vertices[1][0] - vertices[0][0]) *
		    (vertices[1][0] - vertices[0][0]) +
		    (vertices[1][1] - vertices[0][1]) *
		    (vertices[1][1] - vertices[0][1]) +
		    (vertices[1][2] - vertices[0][2]) *
		    (vertices[1][2] - vertices[0][2]));
      box[1] = sqrt((vertices[3][0] - vertices[0][0]) *
		    (vertices[3][0] - vertices[0][0]) +
		    (vertices[3][1] - vertices[0][1]) *
		    (vertices[3][1] - vertices[0][1]) +
		    (vertices[3][2] - vertices[0][2]) *
		    (vertices[3][2] - vertices[0][2]));
      box[2] = sqrt((vertices[4][0] - vertices[0][0]) *
		    (vertices[4][0] - vertices[0][0]) +
		    (vertices[4][1] - vertices[0][1]) *
		    (vertices[4][1] - vertices[0][1]) +
		    (vertices[4][2] - vertices[0][2]) *
		    (vertices[4][2] - vertices[0][2]));
      box[3] = acos(CLAMP(((vertices[3][0] - vertices[0][0]) *
			   (vertices[4][0] - vertices[0][0]) +
			   (vertices[3][1] - vertices[0][1]) *
			   (vertices[4][1] - vertices[0][1]) +
			   (vertices[3][2] - vertices[0][2]) *
			   (vertices[4][2] - vertices[0][2])) /
			  box[1] / box[2], -1.f, 1.f)) * 180.f / G_PI;
      box[4] = acos(CLAMP(((vertices[1][0] - vertices[0][0]) *
			   (vertices[4][0] - vertices[0][0]) +
			   (vertices[1][1] - vertices[0][1]) *
			   (vertices[4][1] - vertices[0][1]) +
			   (vertices[1][2] - vertices[0][2]) *
			   (vertices[4][2] - vertices[0][2])) /
			  box[0] / box[2], -1.f, 1.f)) * 180.f / G_PI;
      box[4] *= (vertices[4][2] < 0.)?-1.:+1.;
      box[5] = acos(CLAMP(((vertices[3][0] - vertices[0][0]) *
			   (vertices[1][0] - vertices[0][0]) +
			   (vertices[3][1] - vertices[0][1]) *
			   (vertices[1][1] - vertices[0][1]) +
			   (vertices[3][2] - vertices[0][2]) *
			   (vertices[1][2] - vertices[0][2])) /
			  box[0] / box[1], -1.f, 1.f)) * 180.f / G_PI;
    }
  else
    {
      box[0] = vertices[1][0] - vertices[0][0];
      box[1] = vertices[3][0] - vertices[0][0];
      box[2] = vertices[3][1] - vertices[0][1];
      box[3] = vertices[4][0] - vertices[0][0];
      box[4] = vertices[4][1] - vertices[0][1];
      box[5] = vertices[4][2] - vertices[0][2];
    }
  g_string_append_printf(output, "%17.8g %17.8g %17.8g\n", box[0], box[1], box[2]);
  g_string_append_printf(output, "%17.8g %17.8g %17.8g\n", box[3], box[4], box[5]);
  if (angdeg)
    g_string_append(output, "#keyword: angdeg\n");
  if (reduced)
    g_string_append(output, "#keyword: reduced\n");
  switch (visu_box_getUnit(boxObj))
    {
    case TOOL_UNITS_ANGSTROEM:
      g_string_append(output, "#keyword: angstroem\n");
      break;
    case TOOL_UNITS_BOHR:
      g_string_append(output, "#keyword: atomic\n");
      break;
    default:
      break;
    }
  bc = visu_box_getBoundary(boxObj);
  switch (bc)
    {
    case VISU_BOX_SURFACE_XY:
      g_string_append(output, "#keyword: surfaceXY\n");
      break;
    case VISU_BOX_SURFACE_YZ:
      g_string_append(output, "#keyword: surfaceYZ\n");
      break;
    case VISU_BOX_SURFACE_ZX:
      g_string_append(output, "#keyword: surface\n");
      break;
    case VISU_BOX_FREE:
      if (reduced)
	g_warning("Using reduced coordinates in free boundary conditions"
		  " is possible but not not adviced. The given box will be"
		  " used to obtain the real coordinates.");
      g_string_append(output, "#keyword: freeBC\n");
      break;
    default:
      break;
    }
  g_object_get(G_OBJECT(dataObj), "totalEnergy", &ene, NULL);
  if (ene != G_MAXFLOAT)
    g_string_append_printf(output, "#metaData: totalEnergy=%22.16feV\n", ene);

  visu_box_getVertices(boxObj, vertices, FALSE);
  if (expand)
    visu_box_getExtension(boxObj, ext);
  else
    {
      ext[0] = 0.;
      ext[1] = 0.;
      ext[2] = 0.;
    }
  if (ext[0] != 0. || ext[1] != 0. || ext[2] != 0.)
    {
      g_string_append(output, "# Box is expanded, previous box size:\n");
      g_string_append_printf(output, "# %15g %15g %15g\n", vertices[1][0],
			     vertices[3][0], vertices[3][1]);
      g_string_append_printf(output, "# %15g %15g %15g\n", vertices[4][0],
			     vertices[4][1], vertices[4][2]);
      g_string_append(output, "# and box extension:\n");
      g_string_append_printf(output, "# %15g %15g %15g\n", ext[0], ext[1], ext[2]);
    }
  if (comment)
    {
      g_string_append(output, "# Statistics are valid for all nodes (hidden or not).\n");
      g_string_append(output, "# Hidden nodes are printed, but commented.\n");
    }
  visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter);
  g_string_append_printf(output, "# Box contains %d element(s).\n", iter.nElements);
  g_string_append_printf(output, "# Box contains %d nodes.\n", iter.nAllStoredNodes);
  for (visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter); iter.element;
       visu_node_array_iterNextElement(VISU_NODE_ARRAY(dataObj), &iter, FALSE))
    g_string_append_printf(output, "#  | %d nodes for element '%s'.\n",
	    iter.nStoredNodes, iter.element->name);
  if (suppr)
    g_string_append(output, "# Hidden nodes have been suppressed.\n");
  geodiff = VISU_DATA_DIFF(visu_data_getNodeProperties(dataObj, VISU_DATA_DIFF_DEFAULT_ID));
  if (geodiff)
    {
      diff = visu_data_diff_export(geodiff);
      g_string_append(output, diff);
      g_free(diff);
    }

  for ((eleSort)?visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter):
	 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))
    {
      if ((visu_element_getRendered(iter.element) && iter.node->rendered) || !comment)
	tmpChr = ' ';
      else
	tmpChr = '#';

      visu_data_getNodePosition(dataObj, iter.node, xyz);

      if ((visu_element_getRendered(iter.element) && iter.node->rendered) || !suppr)
	{
/*g_message("ext : %f,  vertices : %f, ext : %f, vertices : %f, ext : %f, vertice : %f\n",ext[0],vertices[1][0],ext[1],vertices[3][0],
	    ext[2],vertices[4][0]);*/
	  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];
	  
	  if (reduced)
	    {
	      visu_box_convertXYZtoBoxCoordinates(boxObj, uvw, xyz);
              if (bc & 1)
                uvw[0] /= (1.f + 2.f * ext[0]);
              else
                uvw[0] = xyz[0];
              if (bc & 2)
                uvw[1] /= (1.f + 2.f * ext[1]);
              else
                uvw[1] = xyz[1];
              if (bc & 4)
                uvw[2] /= (1.f + 2.f * ext[2]);
              else
                uvw[2] = xyz[2];
	    }
	  else
	    {
	      uvw[0] = xyz[0];
	      uvw[1] = xyz[1];
	      uvw[2] = xyz[2];
	    }
	  g_string_append_printf(output, "%c%17.8g %17.8g %17.8g %c%s", tmpChr,
                                 uvw[0], uvw[1], uvw[2],
                                 (visu_element_getPhysical(iter.element))?' ':'%',
                                 iter.element->name);
	  nodeComment = visu_data_getNodeLabelAt(dataObj, iter.node);
	  if (nodeComment)
	    g_string_append_printf(output, " %s", nodeComment);
	  g_string_append(output, "\n");
	}
    }
      
  g_file_set_contents(filename, output->str, -1, error);
  g_string_free(output, TRUE);

  if (*error)
    return FALSE;
  else
    return TRUE;
}
