/* This file is part of the Neper software package. */
/* Copyright (C) 2003-2014, Romain Quey. */
/* See the COPYING file in the top-level directory. */

#include"net_flatten_.h"

void
net_flatten (struct MTESS MTess, struct TESS *Tess, struct TESS *pFTess)
{
  int i;
  struct TESSE *TessE = calloc (MTess.TessQty + 1, sizeof (struct TESSE));
  struct FLATTEN Flatten;

  neut_flatten_set_zero (&Flatten);

  /*
     FILE* file = NULL;
     char* filename = ut_alloc_1d_char (100);
     for (i = 1; i <= MTess.TessQty; i++)
     {
     sprintf (filename, "tess%d.geo", i);
     file = ut_file_open (filename, "w");
     neut_tess_fprintf_gmsh (file, Tess[i]);
     ut_file_close (file, filename, "w");
     }
   */

  for (i = 1; i <= MTess.TessQty; i++)
    neut_tesse_set_zero (TessE + i);

  if (MTess.LevelQty > 2)
    ut_error_reportbug ();

  net_flatten_gen (Tess, pFTess, &Flatten);

  ut_print_message (0, 2, "0D flattening...\n");
  net_flatten_ver (MTess, Tess, pFTess, TessE, &Flatten);

  ut_print_message (0, 2, "1D flattening...\n");
  net_flatten_edge (MTess, Tess, pFTess, TessE, &Flatten);

  neut_flatten_init_domstuff_fromver (&Flatten, Tess[1]);
  neut_flatten_init_domstuff_fromedge (&Flatten, Tess[1]);

  ut_print_message (0, 2, "2D flattening...\n");
  net_flatten_face (MTess, Tess, pFTess, &TessE, &Flatten);

  neut_flatten_init_domstuff_fromface (&Flatten);

  ut_print_message (0, 2, "3D flattening...\n");
  net_flatten_poly (MTess, Tess, pFTess, &TessE, &Flatten);
  net_flatten_cell (pFTess, Flatten);

  ut_print_message (0, 2, "Domain flattening...\n");
  net_flatten_dom (Tess, pFTess, TessE);

  /*
     strcpy (filename, "tessf.geo");
     file = ut_file_open (filename, "w");
     neut_tess_fprintf_gmsh (file, *pFTess);
     ut_file_close (file, filename, "w");

     strcpy (filename, "tessf.tess");
     file = ut_file_open (filename, "w");
     neut_tess_fprintf (file, *pFTess);
     ut_file_close (file, filename, "w");
   */

#ifdef HAVE_DEBUGGING
  if (neut_tess_test (*pFTess, 0) != 0)
    ut_print_message (2, 2, "The tessellation is not valid.\n");
#endif

  return;
}
