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

	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 "dumpToABINIT.h"

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

#include <visu_tools.h>
#include <visu_dataloadable.h>
#include <extraFunctions/geometry.h>
#include <coreTools/toolPhysic.h>

/**
 * SECTION:dumpToABINIT
 * @short_description: add an export capability of current positions
 * in ABINIT format.
 *
 * 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 writeDataInABINIT(VisuDumpData *format, const char* filename,
                                  VisuData *dataObj, GError **error);

static VisuDumpData *ab;

const VisuDumpData* visu_dump_abinit_getStatic()
{
  const gchar *typeABINIT[] = {"*.in", (char*)0};
#define descrABINIT _("ABINIT file (crystal only)")

  if (ab)
    return ab;

  ab = visu_dump_data_new(descrABINIT, typeABINIT, writeDataInABINIT);
  
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ab), "reduced_coordinates",
				_("Export positions in reduced coordinates"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(ab), "angdeg_box",
				_("Export box as lengths and angles"), FALSE);

  return ab;
}

static gboolean writeDataInABINIT(VisuDumpData *format, const char* filename,
                                  VisuData *dataObj, GError **error)
{
  const gchar *nom;
  gchar *prevFile;
  gchar unit[25], tag[25];
  gboolean reduced, angdeg;
  float xyz[3], uvw[3], vertices[8][3], box[6];
  VisuNodeArrayIter iter;
  GString *output;
  ToolFileFormatIter it;
  int znucl;
  VisuBox *boxObj;

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

  reduced = FALSE;
  angdeg  = 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 ABINIT: test property '%s'.\n", it.name);
      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);
    }

  DBG_fprintf(stderr, "Dump ABINIT: begin export of current positions...\n");
  DBG_fprintf(stderr, " | reduced %d ;\n", reduced);
  DBG_fprintf(stderr, " | angdeg  %d ;\n", angdeg);

  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 ABINIT from '%s'\n", prevFile);
      g_free(prevFile);
    }
  else
    {
      g_warning("Can't get the name of the file to export.");
      g_string_append(output, "# V_Sim export to ABINIT\n");
    }

  boxObj = visu_boxed_getBox(VISU_BOXED(dataObj));
  switch (visu_box_getUnit(boxObj))
    {
    case TOOL_UNITS_ANGSTROEM:
      strcpy(unit, "angstroms");
      strcpy(tag, "xangst");
      break;
    default:
      g_warning("Unsupported unit for ABINIT, defaulting to Bohr.");
      /* Falls through. */
    case TOOL_UNITS_UNDEFINED:
    case TOOL_UNITS_BOHR:
      unit[0] = '\0';
      strcpy(tag, "xcart");
      break;
    }
  if (reduced)
    strcpy(tag, "xred");

  visu_box_getVertices(boxObj, vertices, TRUE);
  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]));
  g_string_append_printf(output, "acell  %17.8g %17.8g %17.8g %s\n",
                         box[0], box[1], box[2], unit);
  if (angdeg)
    {
      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;
      g_string_append_printf(output, "angdeg %17.8g %17.8g %17.8g\n", box[3], box[4], box[5]);
    }
  else
    {
      g_string_append_printf(output, "rprim %17.8g %17.8g %17.8g\n",
                             (vertices[1][0] - vertices[0][0]) / box[0],
                             (vertices[1][1] - vertices[0][1]) / box[0],
                             (vertices[1][2] - vertices[0][2]) / box[0]);
      g_string_append_printf(output, "      %17.8g %17.8g %17.8g\n",
                             (vertices[3][0] - vertices[0][0]) / box[1],
                             (vertices[3][1] - vertices[0][1]) / box[1],
                             (vertices[3][2] - vertices[0][2]) / box[1]);
      g_string_append_printf(output, "      %17.8g %17.8g %17.8g\n",
                             (vertices[4][0] - vertices[0][0]) / box[2],
                             (vertices[4][1] - vertices[0][1]) / box[2],
                             (vertices[4][2] - vertices[0][2]) / box[2]);
    }

  visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter);
  g_string_append_printf(output, "ntypat %d\n", iter.nElements);
  g_string_append_printf(output, "natom %d\n", iter.nAllStoredNodes);
  g_string_append(output, "znucl");
  for(visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter); iter.element;
      visu_node_array_iterNextElement(VISU_NODE_ARRAY(dataObj), &iter, FALSE))
    {
      tool_physic_getZFromSymbol(&znucl, (float*)0, (float*)0, iter.element->name);
      g_string_append_printf(output, " %d", znucl);
    }
  g_string_append(output, "\n");
  g_string_append(output, "typat");
  for(visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter); iter.node;
      visu_node_array_iterNext(VISU_NODE_ARRAY(dataObj), &iter))
    if (visu_element_getRendered(iter.element) && iter.node->rendered)
      {
        g_string_append_printf(output, " %d", iter.node->posElement + 1);
        if (iter.node->number % 10 == 9)
          g_string_append(output, "\n");
      }
  g_string_append(output, "\n");
  g_string_append(output, tag);
  for(visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter); iter.node;
      visu_node_array_iterNext(VISU_NODE_ARRAY(dataObj), &iter))
    {
      visu_data_getNodePosition(dataObj, iter.node, xyz);
      if (reduced)
        visu_box_convertXYZtoBoxCoordinates(boxObj, uvw, xyz);
      else
        {
          uvw[0] = xyz[0];
          uvw[1] = xyz[1];
          uvw[2] = xyz[2];
        }
      if (visu_element_getRendered(iter.element) && iter.node->rendered)
        g_string_append_printf(output, " %17.8g %17.8g %17.8g\n", uvw[0], uvw[1], uvw[2]);
    }
  g_string_append_printf(output, "\n");
      
  g_file_set_contents(filename, output->str, -1, error);
  g_string_free(output, TRUE);

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