Salome HOME
Copyright update 2021
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
index c188a4850409eaf4a87133049aff8e560362ebe0..806747783571238042c6950dc6544df95da16933 100644 (file)
@@ -1,9 +1,9 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D
+// Copyright (C) 2007-2021  CEA/DEN, EDF R&D
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
-// version 2.1 of the License.
+// version 2.1 of the License, or (at your option) any later version.
 //
 // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 //
 #include "HexoticPlugin_Hexotic.hxx"
 #include "HexoticPlugin_Hypothesis.hxx"
+#include "MG_Hexotic_API.hxx"
 
 #include "utilities.h"
 
-#ifndef WIN32
-#include <sys/sysinfo.h>
+#ifdef WIN32
+#include <process.h>
 #endif
 
 #ifdef _DEBUG_
 #define DUMP(txt) \
-//  cout << txt
+//  std::cout << txt
 #else
 #define DUMP(txt)
 #endif
 
-#include <SMESHDS_Mesh.hxx>
 #include <SMESHDS_GroupBase.hxx>
+#include <SMESHDS_Mesh.hxx>
 #include <SMESH_ComputeError.hxx>
 #include <SMESH_File.hxx>
 #include <SMESH_Gen.hxx>
 #include <SMESH_HypoFilter.hxx>
 #include <SMESH_MesherHelper.hxx>
 #include <SMESH_subMesh.hxx>
+#include <SMESH_MeshEditor.hxx>
+#include <SMESH_ControlPnt.hxx>
 
 #include <list>
 #include <cstdlib>
-#include <iostream>
 
 #include <Standard_ProgramError.hxx>
 
-#include <BRep_Tool.hxx>
 #include <BRepBndLib.hxx>
 #include <BRepClass3d_SolidClassifier.hxx>
-#include <BRepBuilderAPI_MakeVertex.hxx>
-#include <BRepExtrema_DistShapeShape.hxx>
+#include <BRep_Tool.hxx>
+#include <Bnd_Box.hxx>
 #include <OSD_File.hxx>
 #include <Precision.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopoDS.hxx>
+#include <TopoDS_Vertex.hxx>
+#include <gp_Pnt.hxx>
+
+#include <Basics_Utils.hxx>
+#include <GEOMImpl_Types.hxx>
+#include <GEOM_wrap.hxx>
+
+#define GMFVERSION GmfDouble
+#define GMFDIMENSION 3
+
+using SMESHUtils::ControlPnt;
 
 static void removeFile( const TCollection_AsciiString& fileName )
 {
   try {
     OSD_File( fileName ).Remove();
   }
-  catch ( Standard_ProgramError ) {
+  catch ( Standard_ProgramError& ) {
     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
   }
 }
@@ -80,24 +92,22 @@ static void removeFile( const TCollection_AsciiString& fileName )
  */
 //=============================================================================
 
-HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen* gen)
-  : SMESH_3D_Algo(hypId, studyId, gen)
+HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, SMESH_Gen* gen)
+  : SMESH_3D_Algo(hypId, gen)
 {
-  MESSAGE("HexoticPlugin_Hexotic::HexoticPlugin_Hexotic");
-  _name = "Hexotic_3D";
+  _name = "MG-Hexa";
   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
-//   _onlyUnaryInput = false;
+  _onlyUnaryInput = false;
   _requireShape = false;
   _iShape=0;
   _nbShape=0;
   _hexoticFilesKept=false;
-  _compatibleHypothesis.push_back("Hexotic_Parameters");
+  _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
 #ifdef WITH_BLSURFPLUGIN
   _blsurfHypo = NULL;
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  _compute_canceled = false;
-#endif
+  _computeCanceled = false;
+  
 }
 
 //=============================================================================
@@ -108,7 +118,6 @@ HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen*
 
 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
 {
-  MESSAGE("HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic");
 }
 
 
@@ -116,7 +125,6 @@ HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
                                                    const TopoDS_Shape& aShape )
 {
-  // MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
   _blsurfHypo = NULL;
 
   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
@@ -124,7 +132,8 @@ bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
 
   // If a BLSURF hypothesis is applied, get it
   SMESH_HypoFilter blsurfFilter;
-  blsurfFilter.Init( blsurfFilter.HasName( "BLSURF_Parameters" ));
+  blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(true) ));
+  blsurfFilter.Or  ( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(false)));
   std::list<const SMESHDS_Hypothesis *> appliedHyps;
   aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
 
@@ -132,7 +141,9 @@ bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
     itl = appliedHyps.begin();
     theHyp = (*itl); // use only the first hypothesis
     std::string hypName = theHyp->GetName();
-    if (hypName == "BLSURF_Parameters") {
+    if (hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
+        hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
+    {
       _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
       ASSERT(_blsurfHypo);
       return true;
@@ -152,7 +163,6 @@ bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&
                                              const TopoDS_Shape&                  aShape,
                                              SMESH_Hypothesis::Hypothesis_Status& aStatus )
 {
-  // MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
   _hypothesis = NULL;
 
   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
@@ -161,6 +171,10 @@ bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&
   const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
   int nbHyp = hyps.size();
   if (!nbHyp) {
+    // retrieve BLSURF hypothesis if no hexotic hypothesis has been set
+#ifdef WITH_BLSURFPLUGIN
+    CheckBLSURFHypothesis(aMesh, aShape);
+#endif
     aStatus = SMESH_Hypothesis::HYP_OK;
     return true;  // can work with no hypothesis
   }
@@ -169,7 +183,7 @@ bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&
   theHyp = (*itl); // use only the first hypothesis
 
   std::string hypName = theHyp->GetName();
-  if (hypName == "Hexotic_Parameters") {
+  if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
     _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
     ASSERT(_hypothesis);
     aStatus = SMESH_Hypothesis::HYP_OK;
@@ -226,64 +240,22 @@ static TopoDS_Shape findShape(SMDS_MeshNode**     t_Node,
   return aShape;
 }
 
-//=======================================================================
-//function : findEdge
-//purpose  :
-//=======================================================================
-
-static int findEdge(const SMDS_MeshNode* aNode,
-                    const SMESHDS_Mesh*  aMesh,
-                    const int            nEdge,
-                    const TopoDS_Shape*  t_Edge) {
-
-  TopoDS_Shape aPntShape, foundEdge;
-  TopoDS_Vertex aVertex;
-  gp_Pnt aPnt( aNode->X(), aNode->Y(), aNode->Z() );
-
-  int foundInd, ind;
-  double nearest = RealLast(), *t_Dist;
-  double epsilon = Precision::Confusion();
-
-  t_Dist = new double[ nEdge ];
-  aPntShape = BRepBuilderAPI_MakeVertex( aPnt ).Shape();
-  aVertex   = TopoDS::Vertex( aPntShape );
-
-  for ( ind=0; ind < nEdge; ind++ ) {
-    BRepExtrema_DistShapeShape aDistance ( aVertex, t_Edge[ind] );
-    t_Dist[ind] = aDistance.Value();
-    if ( t_Dist[ind] < nearest ) {
-      nearest   = t_Dist[ind];
-      foundEdge = t_Edge[ind];
-      foundInd  = ind;
-      if ( nearest < epsilon )
-        ind = nEdge;
-    }
-  }
-
-  delete [] t_Dist;
-  return aMesh->ShapeToIndex( foundEdge );
-}
-
 //=======================================================================
 //function : getNbShape
 //purpose  :
 //=======================================================================
 
-static int getNbShape(std::string aFile, std::string aString, int defaultValue=0) {
-  int number = defaultValue;
-  std::string aLine;
-  std::ifstream file(aFile.c_str());
-  while ( !file.eof() ) {
-    getline( file, aLine);
-    if ( aLine == aString ) {
-      getline( file, aLine);
-      std::istringstream stringFlux( aLine );
-      stringFlux >> number;
-      number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
-      break;
-    }
+static int getNbShape(MG_Hexotic_API* hexaOutput, int iMesh, GmfKwdCod what, int defaultValue=0)
+{
+  int number = hexaOutput->GmfStatKwd( iMesh, what );
+  if ( number > 0 )
+  {
+    number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
+  }
+  else
+  {
+    number = defaultValue;
   }
-  file.close();
   return number;
 }
 
@@ -292,9 +264,11 @@ static int getNbShape(std::string aFile, std::string aString, int defaultValue=0
 //purpose  :
 //=======================================================================
 
-template < class Mesh, class Shape >
-static int countShape( Mesh* mesh, Shape shape ) {
-  TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
+static int countShape( SMESH_Mesh* mesh, TopAbs_ShapeEnum shape )
+{
+  if ( !mesh->HasShapeToMesh() )
+    return 0;
+  TopExp_Explorer expShape ( mesh->GetShapeToMesh(), shape );
   TopTools_MapOfShape mapShape;
   int nbShape = 0;
   for ( ; expShape.More(); expShape.Next() ) {
@@ -311,7 +285,8 @@ static int countShape( Mesh* mesh, Shape shape ) {
 //=======================================================================
 
 template < class Mesh, class Shape, class Tab >
-void getShape(Mesh* mesh, Shape shape, Tab *t_Shape) {
+void getShape(Mesh* mesh, Shape shape, Tab *t_Shape)
+{
   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
   TopTools_MapOfShape mapShape;
   for ( int i=0; expShape.More(); expShape.Next() ) {
@@ -329,10 +304,10 @@ void getShape(Mesh* mesh, Shape shape, Tab *t_Shape) {
 //=======================================================================
 
 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
-  cout << std::endl;
-  cout << "WARNING : " << nbExpected << " " << aString << " expected, Hexotic has found " << nbFound << std::endl;
-  cout << "=======" << std::endl;
-  cout << std::endl;
+  std::cout << std::endl;
+  std::cout << "WARNING : " << nbExpected << " " << aString << " expected, MG-Hexa has found " << nbFound << std::endl;
+  std::cout << "=======" << std::endl;
+  std::cout << std::endl;
   return;
 }
 
@@ -341,476 +316,340 @@ static void printWarning(const int nbExpected, std::string aString, const int nb
 //purpose  :
 //=======================================================================
 
-static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out) {
+static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out)
+{
   removeFile( file_In );
   removeFile( file_Out );
 }
 
 //=======================================================================
-//function : readResult
-//purpose  : Read GMF file in case of a mesh with geometry
+//function : splitQuads
+//purpose  : splits all quadrangles into triangles
 //=======================================================================
 
-static bool readResult(std::string         theFile,
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-                       HexoticPlugin_Hexotic*  theAlgo,
-#endif
-                       SMESHDS_Mesh*       theMesh,
-                       const int           nbShape,
-                       const TopoDS_Shape* tabShape,
-                       double**            tabBox)
+static void splitQuads(SMESH_Mesh& aMesh)
 {
-  // ---------------------------------
-  // Optimisation of the plugin ...
-  // Retrieve the correspondance edge --> shape
-  // (which is very costly) only when user
-  // has defined at least one group of edges
-  // which should be rare for a 3d mesh !
-  // ---------------------------------
-  
-  bool retrieve_edges = false;
-  const std::set<SMESHDS_GroupBase*>& aGroups = theMesh->GetGroups();
-  set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin();
-  for (; GrIt != aGroups.end(); GrIt++)
-    {
-      SMESHDS_GroupBase* aGrp = *GrIt;
-      if ( !aGrp )
-        continue;
-      if ( aGrp->GetType() == SMDSAbs_Edge )
-        {
-          retrieve_edges = true;
-          break;
-        }
-    }
-  
-  // ---------------------------------
-  // Read generated elements and nodes
-  // ---------------------------------
-
-  TopoDS_Shape aShape;
-  TopoDS_Vertex aVertex;
-  std::string token;
-  int EndOfFile = 0, nbElem = 0, nField = 9, nbRef = 0;
-  int aHexoticNodeID = 0, shapeID, hexoticShapeID;
-  const int IdShapeRef = 2;
-  int *tabID, *tabRef, *nodeAssigne;
-  bool *tabDummy, hasDummy = false;
-  double epsilon = Precision::Confusion();
-  std::map <std::string,int> mapField;
-  SMDS_MeshNode** HexoticNode;
-  TopoDS_Shape *tabCorner, *tabEdge;
+  SMESH_MeshEditor spliter( &aMesh );
 
-  const int nbDomains = countShape( theMesh, TopAbs_SHELL );
-  const int holeID = -1;
+  TIDSortedElemSet elems;
+  SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
+  while( eIt->more() )
+    elems.insert( elems.end(), eIt->next() );
+  
+  spliter.QuadToTri ( elems, /*the13Diag=*/true);
+}
 
-  // tabID    = new int[nbShape];
-  tabID    = new int[nbDomains];
-  tabRef   = new int[nField];
-  tabDummy = new bool[nField];
-
-  for (int i=0; i<nbDomains; i++)
-    tabID[i] = 0;
-  if ( nbDomains == 1 )
-    tabID[0] = theMesh->ShapeToIndex( tabShape[0] );
-
-  mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
-  mapField["Dimension"]            = 1; tabRef[1] = 0; tabDummy[1] = false;
-  mapField["Vertices"]             = 2; tabRef[2] = 3; tabDummy[2] = true;
-  mapField["Corners"]              = 3; tabRef[3] = 1; tabDummy[3] = false;
-  mapField["Edges"]                = 4; tabRef[4] = 2; tabDummy[4] = true;
-  mapField["Ridges"]               = 5; tabRef[5] = 1; tabDummy[5] = false;
-  mapField["Quadrilaterals"]       = 6; tabRef[6] = 4; tabDummy[6] = true;
-  mapField["Hexahedra"]            = 7; tabRef[7] = 8; tabDummy[7] = true;
-  mapField["End"]                  = 8; tabRef[8] = 0; tabDummy[0] = false;
-
-  SMDS_NodeIteratorPtr itOnHexoticInputNode = theMesh->nodesIterator();
-  while ( itOnHexoticInputNode->more() )
-    theMesh->RemoveNode( itOnHexoticInputNode->next() );
-
-  int nbVertices   = getNbShape(theFile, "Vertices");
-  int nbCorners    = getNbShape(theFile, "Corners", countShape( theMesh, TopAbs_VERTEX ));
-  int nbShapeEdge  = countShape( theMesh, TopAbs_EDGE );
-
-  tabCorner   = new TopoDS_Shape[ nbCorners ];
-  tabEdge     = new TopoDS_Shape[ nbShapeEdge ];
-  nodeAssigne = new int[ nbVertices + 1 ];
-  HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
-
-  getShape(theMesh, TopAbs_VERTEX, tabCorner);
-  getShape(theMesh, TopAbs_EDGE,   tabEdge);
-
-  MESSAGE("Read " << theFile << " file");
-  std::ifstream fileRes(theFile.c_str());
-  ASSERT(fileRes);
-
-  while ( EndOfFile == 0  ) {
-    int dummy;
-    fileRes >> token;
-
-    if (mapField.count(token)) {
-      nField   = mapField[token];
-      nbRef    = tabRef[nField];
-      hasDummy = tabDummy[nField];
-    }
-    else {
-      nField = -1;
-      nbRef = 0;
-    }
+//=======================================================================
+//function : writeInput
+//purpose  : pass a mesh to input of MG-Hexa
+//=======================================================================
 
-    nbElem = 0;
-    if ( nField < (mapField.size() - 1) && nField >= 0 )
-      fileRes >> nbElem;
+static void writeInput(MG_Hexotic_API*     theHexaInput,
+                       const char*         theFile,
+                       const SMESHDS_Mesh* theMeshDS)
+{
+  int meshID = theHexaInput->GmfOpenMesh( theFile, GmfWrite, GMFVERSION, GMFDIMENSION);
+  
+  // nodes
+  int iN = 0, nbNodes = theMeshDS->NbNodes();
+  theHexaInput->GmfSetKwd( meshID, GmfVertices, nbNodes );
+  std::map< const SMDS_MeshNode*, int, TIDCompare > node2IdMap;
+  SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
+  SMESH_TNodeXYZ n;
+  while ( nodeIt->more() )
+  {
+    n.Set( nodeIt->next() );
+    theHexaInput->GmfSetLin( meshID, GmfVertices, n.X(), n.Y(), n.Z(), n._node->getshapeId() );
+    node2IdMap.insert( node2IdMap.end(), std::make_pair( n._node, ++iN ));
+  }
 
-    switch (nField) {
-      case 0: { // "MeshVersionFormatted"
-        MESSAGE(token << " " << nbElem);
-        break;
-      }
-      case 1: { // "Dimension"
-        MESSAGE("Mesh dimension " << nbElem << "D");
-        break;
-      }
-      case 2: { // "Vertices"
-        MESSAGE("Read " << nbElem << " " << token);
-        int aHexoticID;
-        double *coord;
-        SMDS_MeshNode * aHexoticNode;
-
-        coord = new double[nbRef];
-        for ( int iElem = 0; iElem < nbElem; iElem++ ) {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-          if(theAlgo->computeCanceled())
-            {
-              return false;
-            }
-#endif
-          aHexoticID = iElem + 1;
-          for ( int iCoord = 0; iCoord < 3; iCoord++ )
-            fileRes >> coord[ iCoord ];
-          fileRes >> dummy;
-          aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
-          HexoticNode[ aHexoticID ] = aHexoticNode;
-          nodeAssigne[ aHexoticID ] = 0;
-        }
-        delete [] coord;
-        break;
-      }
-      case 3: // "Corners"
-      case 4: // "Edges"
-      case 5: // "Ridges"
-      case 6: // "Quadrilaterals"
-      case 7: { // "Hexahedra"
-        MESSAGE("Read " << nbElem << " " << token);
-        SMDS_MeshNode** node;
-        int nodeDim, *nodeID;
-        SMDS_MeshElement * aHexoticElement = 0;
-
-        node   = new SMDS_MeshNode*[ nbRef ];
-        nodeID = new int[ nbRef ];
-        for ( int iElem = 0; iElem < nbElem; iElem++ ) {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-          if(theAlgo->computeCanceled())
-            {
-              return false;
-            }
-#endif
-          for ( int iRef = 0; iRef < nbRef; iRef++ ) {
-            fileRes >> aHexoticNodeID;                          // read nbRef aHexoticNodeID
-            node[ iRef ]   = HexoticNode[ aHexoticNodeID ];
-            nodeID[ iRef ] = aHexoticNodeID;
-          }
-          if ( hasDummy )
-            fileRes >> dummy;
-          switch (nField) {
-            case 3: { // "Corners"
-              nodeDim = 1;
-              gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
-              for ( int i=0; i<nbElem; i++ ) {
-                aVertex = TopoDS::Vertex( tabCorner[i] );
-                gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
-                if ( aPnt.Distance( HexoticPnt ) < epsilon )
-                  break;
-              }
-              break;
-            }
-            case 4: { // "Edges"
-              nodeDim = 2;
-              aHexoticElement = theMesh->AddEdge( node[0], node[1] );
-              int iNode = 1;
-              if ( nodeAssigne[ nodeID[0] ] == 0 || nodeAssigne[ nodeID[0] ] == 2 )
-                iNode = 0;
-              if(retrieve_edges)
-                shapeID = findEdge( node[iNode], theMesh, nbShapeEdge, tabEdge );
-              else
-                shapeID = 0;
-              break;
-            }
-            case 5: { // "Ridges"
-              break;
-            }
-            case 6: { // "Quadrilaterals"
-              nodeDim = 3;
-              aHexoticElement = theMesh->AddFace( node[0], node[1], node[2], node[3] );
-              shapeID = dummy;
-              break;
-            }
-            case 7: { // "Hexahedra"
-              nodeDim = 4;
-              if ( nbDomains > 1 ) {
-                hexoticShapeID = dummy - IdShapeRef;
-                if ( tabID[ hexoticShapeID ] == 0 ) {
-                  aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
-                  shapeID = aShape.IsNull() ? holeID : theMesh->ShapeToIndex( aShape );
-                  tabID[ hexoticShapeID ] = shapeID;
-                }
-                else
-                  shapeID = tabID[ hexoticShapeID ];
-                if ( iElem == (nbElem - 1) ) {
-                  int shapeAssociated = 0;
-                  for ( int i=0; i<nbDomains; i++ ) {
-                    if (tabID[i] > 0 )
-                      shapeAssociated += 1;
-                  }
-                  if ( shapeAssociated != nbShape )
-                    printWarning(nbShape, "domains", shapeAssociated);
-                }
-              }
-              else {
-                shapeID = tabID[0];
-              }
-              if ( shapeID != holeID )
-                aHexoticElement = theMesh->AddVolume( node[0], node[3], node[2], node[1], node[4], node[7], node[6], node[5] );
-              break;
-            }
-          } // switch (nField)
-
-          if ( token != "Ridges" && ( shapeID > 0 || token == "Corners")) {
-            for ( int i=0; i<nbRef; i++ ) {
-              if ( nodeAssigne[ nodeID[i] ] == 0 ) {
-                if      ( token == "Corners" )        theMesh->SetNodeOnVertex( node[0], aVertex );
-                else if ( token == "Edges" )          theMesh->SetNodeOnEdge( node[i], shapeID );
-                else if ( token == "Quadrilaterals" ) theMesh->SetNodeOnFace( node[i], shapeID );
-                else if ( token == "Hexahedra" )      theMesh->SetNodeInVolume( node[i], shapeID );
-                nodeAssigne[ nodeID[i] ] = nodeDim;
-              }
-            }
-            if ( token != "Corners" && aHexoticElement )
-              theMesh->SetMeshElementOnShape( aHexoticElement, shapeID );
-          }
-        }
-        delete [] node;
-        delete [] nodeID;
-        break;
-      }
-      case 8: { // "End"
-        EndOfFile = 1;
-        MESSAGE("End of " << theFile << " file");
-        break;
-      }
-      default: {
-        MESSAGE("Unknown Token: " << token);
-      }
+  // edges
+  SMDS_ElemIteratorPtr elemIt = theMeshDS->elementsIterator( SMDSAbs_Edge );
+  if ( elemIt->more() )
+  {
+    int nbEdges = theMeshDS->GetMeshInfo().NbElements( SMDSAbs_Edge );
+    theHexaInput->GmfSetKwd(meshID, GmfEdges, nbEdges );
+    for ( int gmfID = 1; elemIt->more(); ++gmfID )
+    {
+      const SMDS_MeshElement* edge = elemIt->next();
+      theHexaInput->GmfSetLin(meshID, GmfEdges, 
+                              node2IdMap[ edge->GetNode( 0 )],
+                              node2IdMap[ edge->GetNode( 1 )],
+                              edge->getshapeId() );
     }
   }
-  cout << std::endl;
 
-  // remove nodes in holes
-  if ( nbDomains > 1 )
+  // triangles
+  elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
+  if ( elemIt->more() )
   {
-    SMESHDS_SubMesh* subMesh;
-    for ( int i = 1; i <= nbVertices; ++i )
-      if ( HexoticNode[i]->NbInverseElements() == 0 )
-      {
-        subMesh =  HexoticNode[i]->getshapeId() > 0 ? theMesh->MeshElements(HexoticNode[i]->getshapeId() ) : 0;
-        theMesh->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
-      }
+    int nbTria = theMeshDS->GetMeshInfo().NbElements( SMDSGeom_TRIANGLE );
+    theHexaInput->GmfSetKwd(meshID, GmfTriangles, nbTria );
+    for ( int gmfID = 1; elemIt->more(); ++gmfID )
+    {
+      const SMDS_MeshElement* tria = elemIt->next();
+      theHexaInput->GmfSetLin(meshID, GmfTriangles, 
+                              node2IdMap[ tria->GetNode( 0 )],
+                              node2IdMap[ tria->GetNode( 1 )],
+                              node2IdMap[ tria->GetNode( 2 )],
+                              tria->getshapeId() );
+    }
   }
-  delete [] tabID;
-  delete [] tabRef;
-  delete [] tabDummy;
-  delete [] tabCorner;
-  delete [] tabEdge;
-  delete [] nodeAssigne;
-  delete [] HexoticNode;
-  return true;
+  theHexaInput->GmfCloseMesh( meshID );
 }
 
-
 //=======================================================================
 //function : readResult
-//purpose  : Read GMF file in case of a mesh w/o geometry
+//purpose  : Read GMF file in case of a mesh with geometry
 //=======================================================================
 
-static bool readResult(std::string theFile,
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-                       HexoticPlugin_Hexotic*  theAlgo,
-#endif
-                       SMESH_MesherHelper* theHelper)
+static bool readResult(MG_Hexotic_API*       theHexaOutput,
+                       const char*           theFile,
+                       HexoticPlugin_Hexotic*theAlgo,
+                       SMESH_MesherHelper*   theHelper,
+                       const int             nbShape = 0,
+                       const TopoDS_Shape*   tabShape = 0,
+                       double**              tabBox = 0)
 {
-  SMESHDS_Mesh* theMesh = theHelper->GetMeshDS();
+  SMESH_Mesh*     theMesh = theHelper->GetMesh();
+  SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
 
   // ---------------------------------
   // Read generated elements and nodes
   // ---------------------------------
 
+  TopoDS_Shape aShape;
+  TopoDS_Vertex aVertex;
   std::string token;
-  const int nbField = 9;
-  int nField, EndOfFile = 0, nbElem = 0, nbRef = 0;
-  int aHexoticNodeID = 0, shapeID;
-  int tabRef[nbField], *nodeAssigne;
-  bool tabDummy[nbField], hasDummy = false;
+  int shapeID, hexoticShapeID;
+  const int IdShapeRef = 2;
+  std::vector< int > tabID;
+  double epsilon = Precision::Confusion();
   std::map <std::string,int> mapField;
-  SMDS_MeshNode** HexoticNode;
+  std::vector< SMDS_MeshNode*> HexoticNode;
+  std::vector< TopoDS_Shape > tabCorner;
 
-  mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
-  mapField["Dimension"]            = 1; tabRef[1] = 0; tabDummy[1] = false;
-  mapField["Vertices"]             = 2; tabRef[2] = 3; tabDummy[2] = true;
-  mapField["Corners"]              = 3; tabRef[3] = 1; tabDummy[3] = false;
-  mapField["Edges"]                = 4; tabRef[4] = 2; tabDummy[4] = true;
-  mapField["Ridges"]               = 5; tabRef[5] = 1; tabDummy[5] = false;
-  mapField["Quadrilaterals"]       = 6; tabRef[6] = 4; tabDummy[6] = true;
-  mapField["Hexahedra"]            = 7; tabRef[7] = 8; tabDummy[7] = true;
-  mapField["End"]                  = 8; tabRef[8] = 0; tabDummy[8] = false;
+  const int nbDomains = countShape( theMesh, TopAbs_SHELL );
+  const int holeID = -1;
 
-  theHelper->GetMesh()->Clear();
+  if ( nbDomains > 0 )
+  {
+    tabID.resize( nbDomains, 0 );
+    if ( nbDomains == 1 )
+      tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
+  }
+  else
+  {
+    tabID.resize( 1, 1 );
+  }
 
-  int nbVertices = getNbShape(theFile, "Vertices");
-  HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
-  nodeAssigne = new int[ nbVertices + 1 ];
+  SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
+  while( eIt->more() )
+    theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
+  SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
+  while ( nIt->more() )
+    theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
 
-  MESSAGE("Read " << theFile << " file");
-  std::ifstream fileRes(theFile.c_str());
-  ASSERT(fileRes);
+  theHelper->SetElementsOnShape( false );
 
-  while ( !EndOfFile  )
-  {
-    int dummy;
-    fileRes >> token;
+  int ver, dim;
+  int meshID = theHexaOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim );
 
-    if (mapField.count(token)) {
-      nField   = mapField[token];
-      nbRef    = tabRef[nField];
-      hasDummy = tabDummy[nField];
-    }
-    else {
-      nField = -1;
-      nbRef = 0;
+  int nbVerticesInShape = countShape( theMesh, TopAbs_VERTEX );
+  int nbVertices  = getNbShape(theHexaOutput, meshID, GmfVertices );
+  int nbCorners   = getNbShape(theHexaOutput, meshID, GmfCorners, nbVerticesInShape);
+  if ( nbVertices == 0 )
+    return false;
+
+  tabCorner.resize( nbCorners );
+  HexoticNode.resize( nbVertices + 1 );
+
+  // get the shape vertices if the mesh lies on a shape (and this shape has corners)
+  if ( nbCorners > 0 && nbVerticesInShape > 0 )
+    getShape( theMeshDS, TopAbs_VERTEX, tabCorner.data() );
+
+  int nbNodes = theHexaOutput->GmfStatKwd( meshID, GmfVertices );
+  if ( nbNodes > 0 )
+  {
+    theHexaOutput->GmfGotoKwd( meshID, GmfVertices );
+    double x,y,z;
+    for ( int aHexoticID = 1; aHexoticID <= nbNodes; ++aHexoticID )
+    {
+      if ( theAlgo->computeCanceled() )
+        return false;
+      theHexaOutput->GmfGetLin( meshID, GmfVertices, &x, &y, &z, &shapeID );
+      HexoticNode[ aHexoticID ] = theHelper->AddNode( x,y,z );
     }
+  }
 
-    nbElem = 0;
-    if ( nField < (mapField.size() - 1) && nField >= 0 )
-      fileRes >> nbElem;
+  int nodeID[8];
+  SMDS_MeshNode* node[8];
+  SMDS_MeshElement * aHexoticElement;
 
-    switch (nField) {
-    case 0: { // "MeshVersionFormatted"
-      MESSAGE(token << " " << nbElem);
-      break;
+  nbCorners = theHexaOutput->GmfStatKwd( meshID, GmfCorners );
+  if ( nbCorners > 0 && nbDomains > 0 )
+  {
+    theHexaOutput->GmfGotoKwd( meshID, GmfCorners );
+    for ( int iElem = 0; iElem < nbCorners; iElem++ )
+    {
+      if ( theAlgo->computeCanceled() )
+        return false;
+      theHexaOutput->GmfGetLin( meshID, GmfCorners, &nodeID[0] );
+      node[0] = HexoticNode[ nodeID[0] ];
+      gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
+      for ( int i = 0; i < nbCorners; i++ )
+      {
+        aVertex = TopoDS::Vertex( tabCorner[i] );
+        gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
+        if ( aPnt.Distance( HexoticPnt ) < epsilon )
+        {
+          theMeshDS->SetNodeOnVertex( node[0], aVertex );
+          break;
+        }
+      }
     }
-    case 1: { // "Dimension"
-      MESSAGE("Mesh dimension " << nbElem << "D");
-      break;
+  }
+
+  int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
+  if ( nbEdges > 0 )
+  {
+    theHexaOutput->GmfGotoKwd( meshID, GmfEdges );
+    for ( int iElem = 0; iElem < nbEdges; iElem++ )
+    {
+      if ( theAlgo->computeCanceled() )
+        return false;
+      theHexaOutput->GmfGetLin( meshID, GmfEdges, &nodeID[0], &nodeID[1], &shapeID );
+      for ( int i = 0; i < 2; ++i )
+      {
+        node[i] = HexoticNode[ nodeID[i]];
+        if ( shapeID > 0 && node[i]->getshapeId() < 1 )
+          theMeshDS->SetNodeOnEdge( node[i], shapeID );
+      }
+      aHexoticElement = theHelper->AddEdge( node[0], node[1] );
+      if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
+        theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
     }
-    case 2: { // "Vertices"
-      MESSAGE("Read " << nbElem << " " << token);
-      int aHexoticID;
-      double coord[3];
-      SMDS_MeshNode * aHexoticNode;
-
-      for ( int iElem = 0; iElem < nbElem; iElem++ ) {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-        if(theAlgo->computeCanceled())
-          {
-            return false;
-          }
-#endif
-        aHexoticID = iElem + 1;
-        for ( int iCoord = 0; iCoord < 3; iCoord++ )
-          fileRes >> coord[ iCoord ];
-        fileRes >> dummy;
-        aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
-        HexoticNode[ aHexoticID ] = aHexoticNode;
-        nodeAssigne[ aHexoticID ] = 0;
+  }
+
+  int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
+  if ( nbQuad > 0 )
+  {
+    theHexaOutput->GmfGotoKwd( meshID, GmfQuadrilaterals );
+    for ( int iElem = 0; iElem < nbQuad; iElem++ )
+    {
+      if ( theAlgo->computeCanceled() )
+        return false;
+      theHexaOutput->GmfGetLin( meshID, GmfQuadrilaterals,
+                                &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3], &shapeID );
+      for ( int i = 0; i < 4; ++i )
+      {
+        node[i] = HexoticNode[ nodeID[i]];
+        if ( shapeID > 0 && node[i]->getshapeId() < 1 )
+          theMeshDS->SetNodeOnFace( node[i], shapeID );
       }
-      break;
+      aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
+      if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
+        theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
     }
-    case 3: // "Corners"
-    case 4: // "Edges"
-    case 5: // "Ridges"
-    case 6: // "Quadrilaterals"
-    case 7: { // "Hexahedra"
-      MESSAGE("Read " << nbElem << " " << token);
-      std::vector< SMDS_MeshNode* > node( nbRef );
-      std::vector< int >          nodeID( nbRef );
-
-      for ( int iElem = 0; iElem < nbElem; iElem++ )
+  }
+
+  int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
+  if ( nbHexa > 0 )
+  {
+    theHexaOutput->GmfGotoKwd( meshID, GmfHexahedra );
+    for ( int iElem = 0; iElem < nbHexa; iElem++ )
+    {
+      if ( theAlgo->computeCanceled() )
+        return false;
+      theHexaOutput->GmfGetLin( meshID, GmfHexahedra,
+                                &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3],
+                                &nodeID[4], &nodeID[5], &nodeID[6], &nodeID[7],
+                                &shapeID );
+      for ( int i = 0; i < 8; ++i )
       {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-        if(theAlgo->computeCanceled())
-          {
-            return false;
+        node[i] = HexoticNode[ nodeID[i]];
+      }
+      if ( nbDomains > 1 ) {
+        hexoticShapeID = shapeID - IdShapeRef;
+        if ( tabID[ hexoticShapeID ] == 0 ) {
+          aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
+          shapeID = aShape.IsNull() ? holeID : theMeshDS->ShapeToIndex( aShape );
+          tabID[ hexoticShapeID ] = shapeID;
+        }
+        else {
+          shapeID = tabID[ hexoticShapeID ];
+        }
+        if ( iElem == ( nbHexa - 1) ) {
+          int shapeAssociated = 0;
+          for ( int i=0; i<nbDomains; i++ ) {
+            if (tabID[i] > 0 )
+              shapeAssociated += 1;
           }
-#endif
-        for ( int iRef = 0; iRef < nbRef; iRef++ )
-        {
-          fileRes >> aHexoticNodeID;                          // read nbRef aHexoticNodeID
-          node  [ iRef ] = HexoticNode[ aHexoticNodeID ];
-          nodeID[ iRef ] = aHexoticNodeID;
+          if ( shapeAssociated != nbShape )
+            printWarning(nbShape, "domains", shapeAssociated);
         }
-        if ( hasDummy )
-          fileRes >> dummy;
-        switch (nField)
+      }
+      else {
+        shapeID = tabID[0];
+      }
+
+      if ( shapeID != holeID )
+      {
+        for ( int i = 0; i < 8; ++i )
         {
-        case 4: // "Edges"
-          theHelper->AddEdge( node[0], node[1] ); break;
-        case 6:  // "Quadrilaterals"
-          theMesh->AddFace( node[0], node[1], node[2], node[3] ); break;
-        case 7: // "Hexahedra"
-          theHelper->AddVolume( node[0], node[3], node[2], node[1],
-                                node[4], node[7], node[6], node[5] ); break;
-        default: continue;
+          if ( node[i]->NbInverseElements( SMDSAbs_Face ) == 0 )
+            theMeshDS->SetNodeInVolume( node[i], shapeID );
         }
-        if ( nField == 6 )
-          for ( int iRef = 0; iRef < nbRef; iRef++ )
-            nodeAssigne[ nodeID[ iRef ]] = 1;
+        aHexoticElement = theHelper->AddVolume( node[0], node[3], node[2], node[1],
+                                                node[4], node[7], node[6], node[5]);
+        if ( aHexoticElement->getshapeId() < 1 )
+          theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
       }
-      break;
-    }
-    case 8: { // "End"
-      EndOfFile = 1;
-      MESSAGE("End of " << theFile << " file");
-      break;
-    }
-    default: {
-      MESSAGE("Unknown Token: " << token);
-    }
     }
   }
-  cout << std::endl;
+  std::cout << std::endl;
+
+  // remove nodes in holes
+  if ( nbDomains > 1 )
+  {
+    SMESHDS_SubMesh* subMesh = 0;
+    for ( int i = 1; i <= nbNodes; ++i )
+      if ( HexoticNode[i]->NbInverseElements() == 0 )
+      {
+        theMeshDS->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
+      }
+  }
 
-  shapeID = theHelper->GetSubShapeID();
-  for ( int i = 0; i < nbVertices; ++i )
-    if ( !nodeAssigne[ i+1 ])
-      theMesh->SetNodeInVolume( HexoticNode[ i+1 ], shapeID );
+  // avoid "Error: No mesh on sub-shape"
+  if ( theMesh->NbVolumes() > 0 )
+  {
+    SMESH_subMesh*         smMain = theMesh->GetSubMesh( theMesh->GetShapeToMesh() );
+    SMESH_subMeshIteratorPtr smIt = smMain->getDependsOnIterator( /*includeSelf=*/true );
+    while ( smIt->more() )
+    {
+      SMESH_subMesh* sm = smIt->next();
+      if ( !sm->IsMeshComputed() )
+        sm->SetIsAlwaysComputed( true );
+    }
+  }
 
-  delete [] HexoticNode;
-  delete [] nodeAssigne;
   return true;
 }
 
 //=============================================================================
 /*!
- * Pass parameters to Hexotic
+ * Pass parameters to MG-Hexa
  */
 //=============================================================================
 
-void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
-
-  MESSAGE("HexoticPlugin_Hexotic::SetParameters");
+void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp)
+{
   if (hyp) {
     _hexesMinLevel = hyp->GetHexesMinLevel();
     _hexesMaxLevel = hyp->GetHexesMaxLevel();
     _hexesMinSize = hyp->GetMinSize();
     _hexesMaxSize = hyp->GetMaxSize();
+    _approxAngle = hyp->GetGeomApproxAngle();
     _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
     _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
     _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
@@ -819,15 +658,27 @@ void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
     _hexoticVerbosity = hyp->GetHexoticVerbosity();
     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
     _hexoticSdMode = hyp->GetHexoticSdMode();
+    _textOptions = hyp->GetAdvancedOption();
+    _sizeMaps = hyp->GetSizeMaps();
+    _nbLayers = hyp->GetNbLayers();
+    _firstLayerSize = hyp->GetFirstLayerSize();
+    _direction = hyp->GetDirection();
+    _growth = hyp->GetGrowth();
+    _facesWithLayers = hyp->GetFacesWithLayers();
+    _imprintedFaces = hyp->GetImprintedFaces();
+    _keepFiles = hyp->GetKeepFiles();
+    _removeLogOnSuccess = hyp->GetRemoveLogOnSuccess();
+    _logInStandardOutput = hyp->GetStandardOutputLog();
   }
   else {
-    cout << std::endl;
-    cout << "WARNING : The Hexotic default parameters are taken into account" << std::endl;
-    cout << "=======" << std::endl;
+    std::cout << std::endl;
+    std::cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
+    std::cout << "=======" << std::endl;
     _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
     _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
     _hexesMinSize = hyp->GetDefaultMinSize();
     _hexesMaxSize = hyp->GetDefaultMaxSize();
+    _approxAngle = hyp->GetDefaultGeomApproxAngle();
     _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
     _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
     _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
@@ -836,83 +687,165 @@ void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
     _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
     _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
     _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
+    _textOptions = hyp->GetDefaultTextOptions();
+    _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
+    _nbLayers = hyp->GetDefaultNbLayers();
+    _firstLayerSize = hyp->GetDefaultFirstLayerSize();
+    _direction = hyp->GetDefaultDirection();
+    _growth = hyp->GetDefaultGrowth();
+    _facesWithLayers = hyp->GetDefaultFacesWithLayers();
+    _imprintedFaces = hyp->GetDefaultImprintedFaces();
+    _keepFiles = hyp->GetDefaultKeepFiles();
+    _removeLogOnSuccess = hyp->GetDefaultRemoveLogOnSuccess();
+    _logInStandardOutput = hyp->GetDefaultStandardOutputLog();
   }
 }
 
 //=======================================================================
-//function : getTmpDir
-//purpose  :
+//function : getSuffix
+//purpose  : Returns a suffix that will be unique for the current process
 //=======================================================================
 
-static TCollection_AsciiString getTmpDir()
+static TCollection_AsciiString getSuffix()
 {
-  TCollection_AsciiString aTmpDir;
-
-  char *Tmp_dir = getenv("SALOME_TMP_DIR");
-  if(Tmp_dir != NULL) {
-    aTmpDir = Tmp_dir;
-    #ifdef WIN32
-    if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
+  TCollection_AsciiString aSuffix = "";
+  aSuffix += "_";
+#ifndef WIN32
+  aSuffix += getenv("USER");
 #else
-    if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
+  std::string uname = std::string(getenv("USERNAME"));
+  replace(uname.begin(), uname.end(), ' ', '_');
+  aSuffix += uname.c_str();
 #endif
-  }
-  else {
-#ifdef WIN32
-    aTmpDir = TCollection_AsciiString("C:\\");
+  aSuffix += "_";
+  aSuffix += Kernel_Utils::GetHostname().c_str();
+  aSuffix += "_";
+#ifndef WIN32
+  aSuffix += getpid();
 #else
-    aTmpDir = TCollection_AsciiString("/tmp/");
+  aSuffix += _getpid();
 #endif
-  }
-  return aTmpDir;
+
+  return aSuffix;
 }
 
 //================================================================================
 /*!
- * \brief Returns a command to run Hexotic mesher
+ * \brief Returns a command to run MG-Hexa mesher
  */
 //================================================================================
 
-std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
-                                                     const TCollection_AsciiString& Hexotic_Out) const
+std::string
+HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
+                                         const TCollection_AsciiString& Hexotic_Out,
+                                         const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
+                                         const bool                     forExecutable) const
 {
-  cout << std::endl;
-  cout << "Hexotic execution..." << std::endl;
-  cout << _name << " parameters :" << std::endl;
-  cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
-  cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
-  cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
-  cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
-  cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
-  cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
-  cout << "    " << "Hexotic can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
-  cout << "    " << "Hexotic authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
-  cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
-  cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
-  cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
-  cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
-
-  TCollection_AsciiString run_Hexotic( "hexotic" );
-
-  TCollection_AsciiString minl = " -minl ", maxl = " -maxl ", angle = " -ra ";
-  TCollection_AsciiString mins = " -mins ", maxs = " -maxs ";
-  TCollection_AsciiString in   = " -in ",   out  = " -out ";
-  TCollection_AsciiString ignoreRidges = " -nr ", invalideElements = " -inv ";
-  TCollection_AsciiString subdom = " -sd ", sharp = " -sharp ";
-  TCollection_AsciiString proc = " -nproc ";
-  TCollection_AsciiString verb = " -v ";
-  TCollection_AsciiString maxmem = " -m ";
-
-  TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory;
-  minLevel = _hexesMinLevel;
-  maxLevel = _hexesMaxLevel;
-  minSize = _hexesMinSize;
-  maxSize = _hexesMaxSize;
+  std::cout << std::endl;
+  std::cout << "MG-Hexa execution..." << std::endl;
+  std::cout << _name << " parameters :" << std::endl;
+  std::cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
+  std::cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
+  std::cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
+  std::cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
+  std::cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
+  std::cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
+  std::cout << "    " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
+  std::cout << "    " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
+  std::cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
+  std::cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
+  std::cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
+  std::cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
+  std::cout << "    " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
+  std::cout << "    " << _name << " Number of layers = " << _nbLayers << std::endl;
+  std::cout << "    " << _name << " Size of the first layer  = " << _firstLayerSize << std::endl;
+  std::cout << "    " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
+  std::cout << "    " << _name << " Growth = " << _growth << std::endl;
+  if (!_facesWithLayers.empty()) {
+    std::cout << "    " << _name << " Faces with layers = ";
+    for (size_t i = 0; i < _facesWithLayers.size(); i++)
+    {
+      std::cout << _facesWithLayers.at(i);
+      if ((i + 1) != _facesWithLayers.size())
+        std::cout << ", ";
+    }
+    std::cout << std::endl;
+  }
+  if (!_imprintedFaces.empty()) {
+    std::cout << "    " << _name << " Imprinted faces = ";
+    for (size_t i = 0; i < _imprintedFaces.size(); i++)
+    {
+      std::cout << _imprintedFaces.at(i);
+      if ((i + 1) != _imprintedFaces.size())
+        std::cout << ", ";
+    }
+    std::cout << std::endl;
+  }
+
+  TCollection_AsciiString run_Hexotic("mg-hexa.exe");
+
+  TCollection_AsciiString minl         = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
+  TCollection_AsciiString mins         = " --min_size ", maxs = " --max_size ";
+  TCollection_AsciiString in           = " --in ",   out  = " --out ";
+  TCollection_AsciiString sizeMap      = " --read_sizemap ";
+  TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
+  TCollection_AsciiString subdom       = " --components ";
+#ifndef WIN32
+  TCollection_AsciiString proc         = " --max_number_of_threads ";
+#endif
+  TCollection_AsciiString verb         = " --verbose ";
+  TCollection_AsciiString maxmem       = " --max_memory ";
+
+  TCollection_AsciiString comNbLayers        = " --number_of_boundary_layers ";
+  TCollection_AsciiString comFirstLayerSize  = " --height_of_the_first_layer ";
+  TCollection_AsciiString comDirection       = " --boundary_layers_subdomain_direction ";
+  TCollection_AsciiString comGrowth          = " --boundary_layers_geometric_progression ";
+  TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
+  TCollection_AsciiString comImptintedFaces  = " --imprinted_surface_ids ";
+
+  TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
+                          textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
+  minLevel   = _hexesMinLevel;
+  maxLevel   = _hexesMaxLevel;
+  minSize    = _hexesMinSize;
+  maxSize    = _hexesMaxSize;
   sharpAngle = _hexoticSharpAngleThreshold;
-  mode = _hexoticSdMode;
-  nbproc = _hexoticNbProc;
-  verbosity = _hexoticVerbosity;
-  maxMemory = _hexoticMaxMemory;
+  // Mode translation for mg-tetra 1.1
+  switch ( _hexoticSdMode )
+  {
+    case 1:
+      mode = "outside_skin_only";
+      break;
+    case 2:
+      mode = "outside_components";
+      break;
+    case 3:
+      mode = "all";
+      break;
+    case 4:
+      mode = "all --manifold_geometry no";
+      break;
+  }
+  nbproc         = _hexoticNbProc;
+  verbosity      = _hexoticVerbosity;
+  maxMemory      = _hexoticMaxMemory;
+  textOptions    = (" " + _textOptions + " ").c_str();
+  nbLayers       = _nbLayers;
+  firstLayerSize = _firstLayerSize;
+  direction      = _direction ? "1" : "-1";
+  growth         = _growth;
+  for (size_t i = 0; i < _facesWithLayers.size(); i++)
+  {
+    facesWithLayers += _facesWithLayers[i];
+    if ((i + 1) != _facesWithLayers.size())
+      facesWithLayers += ",";
+  }
+  for (size_t i = 0; i < _imprintedFaces.size(); i++)
+  {
+    imprintedFaces += _imprintedFaces[i];
+    if ((i + 1) != _imprintedFaces.size())
+      imprintedFaces += ",";
+  }
 
   if (_hexoticIgnoreRidges)
     run_Hexotic +=  ignoreRidges;
@@ -934,60 +867,137 @@ std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiStri
 
   if (_hexoticSharpAngleThreshold > 0)
     run_Hexotic +=  angle + sharpAngle;
+  
+  if (_sizeMaps.begin() != _sizeMaps.end() && forExecutable )
+    run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
 
-  run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
+  if (_nbLayers       > 0 &&
+      _firstLayerSize > 0 &&
+      _growth         > 0 &&
+      !_facesWithLayers.empty())
+  {
+    run_Hexotic += comNbLayers + nbLayers;
+    run_Hexotic += comFirstLayerSize + firstLayerSize;
+    run_Hexotic += comDirection + direction;
+    run_Hexotic += comGrowth + growth;
+    run_Hexotic += comFacesWithLayers + facesWithLayers;
+    if (!_imprintedFaces.empty())
+      run_Hexotic += comImptintedFaces + imprintedFaces;
+  }
+  if ( forExecutable )
+    run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
   run_Hexotic += subdom + mode;
+#ifndef WIN32
   run_Hexotic += proc + nbproc;
+#endif
   run_Hexotic += verb + verbosity;
   run_Hexotic += maxmem + maxMemory;
 
+  if (!_textOptions.empty())
+    run_Hexotic += textOptions;
+
   return run_Hexotic.ToCString();
 }
 
+// TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
+// way to share it
+TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
+{
+  GEOM::GEOM_Object_var aGeomObj;
+  TopoDS_Shape S = TopoDS_Shape();
+  SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
+  if (!aSObj->_is_nil()) {
+    CORBA::Object_var obj = aSObj->GetObject();
+    aGeomObj = GEOM::GEOM_Object::_narrow(obj);
+    aSObj->UnRegister();
+  }
+  if ( !aGeomObj->_is_nil() )
+    S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
+  return S;
+}
+
+//================================================================================
+/*!
+ * \brief Produces a .mesh file with the size maps informations to give to Hexotic
+ */
+//================================================================================
+
+std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
+                                                                  std::string     sizeMapPrefix )
+{
+  HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
+
+  std::vector<ControlPnt> points;
+  // Iterate on the size maps
+  for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
+  {
+    // Step 1 : Get the GEOM object entry and the size 
+    // from the _sizeMaps infos
+    std::string anEntry = it->first;
+    double aLocalSize = it->second;
+    TopoDS_Shape aShape = entryToShape( anEntry );
+    
+    // Step 2 : Create the points
+    createControlPoints( aShape, aLocalSize, points );
+  }
+
+  // Write the .mesh size map file
+
+  std::string myVerticesFile = sizeMapPrefix + ".mesh";
+  std::string      mySolFile = sizeMapPrefix + ".sol";
+  
+  // Open files
+  int verticesFileID =
+    mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );  
+  int solFileID =
+    mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
+  
+  int pointsNumber = points.size();
+  
+  // Vertices Keyword
+  mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
+  // SolAtVertices Keyword
+  int TypTab[] = {GmfSca};
+  mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
+  
+  // Read the control points information from the vector and write it into the files
+  double ValTab[1];
+  std::vector<ControlPnt>::const_iterator points_it;
+  for (points_it = points.begin(); points_it != points.end(); points_it++ )
+  {
+    mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
+    ValTab[0] = points_it->Size();
+    mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
+  }
+
+  // Close Files
+  mgInput->GmfCloseMesh( verticesFileID );
+  mgInput->GmfCloseMesh( solFileID );
+
+  std::vector<std::string> fileNames(2);
+  fileNames[0] = myVerticesFile;
+  fileNames[1] = mySolFile;
+
+  return fileNames;
+}
+
 //=============================================================================
 /*!
- * Here we are going to use the Hexotic mesher
+ * Here we are going to use the MG-Hexa mesher
  */
 //=============================================================================
 
 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
-                                     const TopoDS_Shape& aShape)
+                                    const TopoDS_Shape& /*aShape*/)
 {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  _compute_canceled = false;
-#endif
+  _computeCanceled = false;
   bool Ok = true;
   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
   TCollection_AsciiString hexahedraMessage;
 
-  if (_iShape == 0 && _nbShape == 0) {
-    _nbShape = countShape( meshDS, TopAbs_SOLID );  // we count the number of shapes
-    //_tabNode = new SMDS_MeshNode*[_nbShape];        // we declare the size of the node array
-  }
-
-  // to prevent from displaying error message after computing,
-  // SetIsAlwaysComputed( true ) to empty sub-meshes
-  for ( int i = 0; i < _nbShape; ++i )
-    if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( aShape ))
-    {
-      SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
-                                                               /*complexShapeFirst=*/false);
-      while ( smIt->more() )
-      {
-        sm = smIt->next();
-        if ( !sm->IsMeshComputed() )
-          sm->SetIsAlwaysComputed( true );
-      }
-    }
-
-  _iShape++;
-
-  if (_iShape == _nbShape ) {
-
-    // for (int i=0; i<_nbShape; i++)        // we destroy the (_nbShape - 1) nodes created and used
-    //   meshDS->RemoveNode( _tabNode[i] );  // to simulate successful mesh computing.
-    // delete [] _tabNode;
+  _nbShape = countShape( &aMesh, TopAbs_SOLID );  // we count the number of shapes
 
+  {
     // create bounding box for each shape of the compound
 
     int iShape = 0;
@@ -1014,35 +1024,47 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
 
     SetParameters(_hypothesis);
 
-//     TCollection_AsciiString aTmpDir = getTmpDir();
-    TCollection_AsciiString aTmpDir = TCollection_AsciiString(_hexoticWorkingDirectory.c_str());
+    TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();
+    TCollection_AsciiString aQuote("");
 #ifdef WIN32
+    aQuote = "\"";
     if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
 #else
     if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
 #endif
-    TCollection_AsciiString Hexotic_In(""), Hexotic_Out;
+    TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
     TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
-    TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic.log";    // log
+    TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
 
     std::map <int,int> aSmdsToHexoticIdMap;
     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
 
-    Hexotic_Out = aTmpDir + "Hexotic_Out.mesh";
+    MG_Hexotic_API mgHexa( _computeCanceled, _progress );
+
+    Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
 #ifdef WITH_BLSURFPLUGIN
     bool defaultInputFile = true;
-    if (_blsurfHypo && !_blsurfHypo->GetQuadAllowed()) {
-      Hexotic_In = TCollection_AsciiString(_blsurfHypo->GetGMFFile().c_str());
-      if (Hexotic_In != "")
+    if (_blsurfHypo && _blsurfHypo->GetElementType() == BLSURFPlugin_Hypothesis::Triangles ) {
+      Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
+      if ( !Hexotic_In.IsEmpty() &&
+           SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
+      {
+        MESSAGE("Use output file from blsurf as input file from hexotic: " << Hexotic_In);
+        mgHexa.SetUseExecutable();
         defaultInputFile = false;
+      }
     }
     if (defaultInputFile) {
 #endif
-      Hexotic_In  = aTmpDir + "Hexotic_In.mesh";
+      Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
       removeHexoticFiles(Hexotic_In, Hexotic_Out);
-      cout << std::endl;
-      cout << "Creating Hexotic input mesh file : " << Hexotic_In << std::endl;
-      aMesh.ExportGMF(Hexotic_In.ToCString(), meshDS, true);
+      splitQuads(aMesh); // quadrangles are no longer acceptable as input
+      if ( mgHexa.IsExecutable() )
+      {
+        std::cout << std::endl;
+        std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
+      }
+      writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
 #ifdef WITH_BLSURFPLUGIN
     }
     else {
@@ -1050,70 +1072,94 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
     }
 #endif
     
+    Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
+    std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
+    
+    std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable() );
+    run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
+    mgHexa.SetLogFile( aLogFileName.ToCString() );
+    std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
 
-    std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out);
-    run_Hexotic += std::string(" 1 > ") + aLogFileName.ToCString();  // dump into file
-
-    cout << std::endl;
-    cout << "Hexotic command : " << run_Hexotic << std::endl;
+    std::cout << std::endl;
+    std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
 
-    modeFile_In += Hexotic_In;
-    system( modeFile_In.ToCString() );
+    if ( mgHexa.IsExecutable() )
+    {
+#ifndef WIN32    
+      modeFile_In += Hexotic_In;
+      system( modeFile_In.ToCString() );
+#endif
+    }
     aSmdsToHexoticIdMap.clear();
     aHexoticIdToNodeMap.clear();
 
     MESSAGE("HexoticPlugin_Hexotic::Compute");
 
-    system( run_Hexotic.data() );
+    
+    std::string errStr;
+    Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
+
 
     // --------------
     // read a result
     // --------------
 
-    std::ifstream fileRes( Hexotic_Out.ToCString() );
-    modeFile_Out += Hexotic_Out;
-    system( modeFile_Out.ToCString() );
-    if ( ! fileRes.fail() ) {
-      Ok = readResult( Hexotic_Out.ToCString(),
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-                       this,
+    if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
+    {
+#ifndef WIN32
+      modeFile_Out += Hexotic_Out;
+      system( modeFile_Out.ToCString() );
 #endif
-                       meshDS, _nbShape, tabShape, tabBox );
-      if(Ok)
-/*********************
-// TODO: Detect and remove elements in holes in case of sd mode = 4
-      // Remove previous nodes and elements
-      SMDS_ElemIteratorPtr itElement = meshDS->elementsIterator();
-      SMDS_NodeIteratorPtr itNode = meshDS->nodesIterator();
-    
-      while ( itElement->more() )
-        meshDS->RemoveElement( itElement->next() );
-      while ( itNode->more() )
-        meshDS->RemoveNode( itNode->next() );
-  
-      SMESH_ComputeErrorPtr myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
-      if (myError)
-*/
-        hexahedraMessage = "success";
-      else
-        hexahedraMessage = "failed";
     }
-    else {
-      hexahedraMessage = "failed";
-      cout << "Problem with Hexotic output file " << Hexotic_Out.ToCString() << std::endl;
-      Ok = false;
-      // analyse log file
-      SMESH_File logFile( aLogFileName.ToCString() );
-      if ( !logFile.eof() )
+    SMESH_MesherHelper aHelper( aMesh );
+
+    Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
+                     this,
+                     &aHelper, _nbShape, tabShape, tabBox );
+
+    std::string log = mgHexa.GetLog();
+    hexahedraMessage = "failed";
+    if ( Ok )
+    {
+      hexahedraMessage = "success";
+      if ( _removeLogOnSuccess )
+        removeFile( aLogFileName );
+    }
+    else if ( !log.empty() )
+    {
+      if( _computeCanceled )
+        error( "interruption initiated by user" );
+      else
       {
+        // get problem description from the log file
         char msgLic[] = " Dlim ";
-        const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
+        const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
           error("Licence problems.");
       }
     }
-    cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
-    cout << std::endl;
+    else if ( !errStr.empty() )
+    {
+      // the log file is empty
+      removeFile( aLogFileName );
+      INFOS( "MG-Hexa Error, " << errStr);
+      error(COMPERR_ALGO_FAILED, errStr);
+    }
+
+    if ( !Ok && mgHexa.IsExecutable() )
+      std::cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
+
+    if ( !_keepFiles )
+    {
+      if (! Ok && _computeCanceled )
+        removeFile( aLogFileName );
+      removeFile(Hexotic_Out);
+      removeFile(Hexotic_In);
+      for ( size_t i = 0; i < sizeMapFiles.size(); i++ )
+        removeFile( sizeMapFiles[i].c_str() );
+    }
+    std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
+    std::cout << std::endl;
 
     delete [] tabShape;
     for (int i=0; i<_nbShape; i++)
@@ -1122,10 +1168,7 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
     _nbShape = 0;
     _iShape  = 0;
   }
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  if(_compute_canceled)
-    return error(SMESH_Comment("interruption initiated by user"));
-#endif
+
   return Ok;
 }
 
@@ -1142,117 +1185,106 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
 
 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
 {
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  _compute_canceled = false;
-#endif
-/*
-  SMESH_ComputeErrorPtr myError = SMESH_ComputeError::New();
-*/
+  _computeCanceled = false;
+
   bool Ok = true;
   TCollection_AsciiString hexahedraMessage;
-
+  TCollection_AsciiString aQuote("");
+#ifdef WIN32
+  aQuote = "\"";
+#endif
   SetParameters(_hypothesis);
 
-  TCollection_AsciiString aTmpDir = getTmpDir();
-  TCollection_AsciiString Hexotic_In, Hexotic_Out;
+  TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
+  TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
   TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
-  TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic.log";    // log
+  TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
 
   std::map <int,int> aSmdsToHexoticIdMap;
   std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
 
-  Hexotic_In  = aTmpDir + "Hexotic_In.mesh";
-  Hexotic_Out = aTmpDir + "Hexotic_Out.mesh";
+  Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
+  Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
+  Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
+
+  MG_Hexotic_API mgHexa( _computeCanceled, _progress );
+
+  std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
 
-  std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out);
-  run_Hexotic += std::string(" 1 > ") + aLogFileName.ToCString();  // dump into file
+  std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable());
+  run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
+  mgHexa.SetLogFile( aLogFileName.ToCString() );
+  std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
 
   removeHexoticFiles(Hexotic_In, Hexotic_Out);
 
-  cout << std::endl;
-  cout << "Creating Hexotic input mesh file : " << Hexotic_In << std::endl;
-  aMesh.ExportGMF(Hexotic_In.ToCString(), aHelper->GetMeshDS());
-  modeFile_In += Hexotic_In;
-  system( modeFile_In.ToCString() );
+  splitQuads(aMesh); // quadrangles are no longer acceptable as input
+
+  std::cout << std::endl;
+  std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
+  writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
+  if ( mgHexa.IsExecutable() )
+  {
+#ifndef WIN32    
+    modeFile_In += Hexotic_In;
+    system( modeFile_In.ToCString() );
+#endif
+  }
   aSmdsToHexoticIdMap.clear();
   aHexoticIdToNodeMap.clear();
 
   MESSAGE("HexoticPlugin_Hexotic::Compute");
 
-  cout << std::endl;
-  cout << "Hexotic command : " << run_Hexotic << std::endl;
-  system( run_Hexotic.data() );
+  std::cout << std::endl;
+  std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
+
+  std::string errStr;
+  Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
 
   // --------------
   // read a result
   // --------------
 
-  std::ifstream fileRes( Hexotic_Out.ToCString() );
-  modeFile_Out += Hexotic_Out;
-  system( modeFile_Out.ToCString() );
-  if ( ! fileRes.fail() ) {
-    Ok = readResult( Hexotic_Out.ToCString(),
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-                     this,
-#endif
-                     aHelper );
-    if(Ok)
-/*
-    // Remove previous nodes and elements
-    SMDS_ElemIteratorPtr itElement = aHelper->GetMeshDS()->elementsIterator();
-    SMDS_NodeIteratorPtr itNode = aHelper->GetMeshDS()->nodesIterator();
-    
-    while ( itElement->more() )
-      aHelper->GetMeshDS()->RemoveElement( itElement->next() );
-    while ( itNode->more() )
-      aHelper->GetMeshDS()->RemoveNode( itNode->next() );
-
-    // Import GMF mesh
-    myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
-    
-    itElement = aHelper->GetMeshDS()->elementsIterator();
-    itNode = aHelper->GetMeshDS()->nodesIterator();
+  if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
+  {
+    modeFile_Out += Hexotic_Out;
+    system( modeFile_Out.ToCString() );
+  }
 
-    // Assign nodes and elements to the pseudo shape
-    while ( itNode->more() )
-      aHelper->GetMeshDS()->SetNodeInVolume(itNode->next(), 1);
-    while ( itElement->more() )
-      aHelper->GetMeshDS()->SetMeshElementOnShape(itElement->next(), 1);
+  Ok = Ok && readResult( &mgHexa, Hexotic_Out.ToCString(), this, aHelper );
 
-    if(myError->IsOK())
-*/
-      hexahedraMessage = "success";
-    else
-      hexahedraMessage = "failed";
+  std::string log = mgHexa.GetLog();
+  if ( Ok )
+  {
+    hexahedraMessage = "success";
   }
-  else {
-/*
-    myError->myName = COMPERR_EXCEPTION;
-*/
+  else
+  {
     hexahedraMessage = "failed";
-    cout << "Problem with Hexotic output file " << Hexotic_Out << std::endl;
-    // analyse log file
-    SMESH_File logFile( aLogFileName.ToCString() );
-    if ( !logFile.eof() )
-    {
-      char msgLic[] = " Dlim ";
-      const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
-      if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
-        return error("Licence problems.");
-    }
-    return error(SMESH_Comment("Problem with Hexotic output file ")<<Hexotic_Out);
+    if ( mgHexa.IsExecutable() )
+      std::cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
+
+    if ( log.find( " license " ) != std::string::npos ||
+         log.find( " Dlim "    ) != std::string::npos )
+      error("License problems.");
+
+    if ( !errStr.empty() )
+      error(errStr);
   }
-  cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
-  cout << std::endl;
+  std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
+  std::cout << std::endl;
 
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  if(_compute_canceled)
+  if(_computeCanceled)
     return error(SMESH_Comment("interruption initiated by user"));
-#endif
+  removeFile(Hexotic_Out);
+  removeFile(Hexotic_In);
+  if ( Ok )
+    removeFile(aLogFileName);
+  for( size_t i=0; i<sizeMapFiles.size(); i++)
+  {
+    removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
+  }
   return Ok;
-/*
-  return myError->IsOK();
-*/
 }
 
 //=============================================================================
@@ -1261,9 +1293,9 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHel
  */
 //=============================================================================
 
-bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
+bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh&         aMesh,
                                      const TopoDS_Shape& aShape,
-                                     MapShapeNbElems& aResMap)
+                                     MapShapeNbElems&    aResMap)
 {
   std::vector<int> aResVec(SMDSEntity_Last);
   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
@@ -1276,17 +1308,15 @@ bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
   return true;
 }
 
-#ifdef WITH_SMESH_CANCEL_COMPUTE
 void HexoticPlugin_Hexotic::CancelCompute()
 {
-  _compute_canceled = true;
-#ifdef WNT
+  _computeCanceled = true;
+#ifdef WIN32
 #else
-  TCollection_AsciiString aTmpDir = getTmpDir();
+  TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
   TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
   TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
   cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
   system( cmd.ToCString() );
 #endif
 }
-#endif