Salome HOME
Update copyrights
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
index 6cbac63d8612e2c39affccbb6e0b5096570b4aa9..cc623a3364b023b4f840a2667bd7d638a082d563 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2016  CEA/DEN, EDF R&D
+// Copyright (C) 2007-2019  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
 //
 #include "HexoticPlugin_Hexotic.hxx"
 #include "HexoticPlugin_Hypothesis.hxx"
+#include "MG_Hexotic_API.hxx"
 
 #include "utilities.h"
 
-#ifndef WIN32
-#include <sys/sysinfo.h>
-#else
-#include <errno.h>
+#ifdef WIN32
 #include <process.h>
 #endif
 
 #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 <gp_Lin.hxx>
-#include <GCPnts_UniformAbscissa.hxx>
-#include <IntCurvesFace_Intersector.hxx>
-#include <BRepMesh_IncrementalMesh.hxx>
-#include <Poly_Triangulation.hxx>
-#include <gp_Ax3.hxx>
-#include <GeomAdaptor_Curve.hxx>
 
 #include <Basics_Utils.hxx>
-#include "GEOMImpl_Types.hxx"
-#include "GEOM_wrap.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 )
 {
@@ -95,13 +92,13 @@ 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 = "MG-Hexa";
   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
-//   _onlyUnaryInput = false;
+  _onlyUnaryInput = false;
   _requireShape = false;
   _iShape=0;
   _nbShape=0;
@@ -110,17 +107,8 @@ HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen*
 #ifdef WITH_BLSURFPLUGIN
   _blsurfHypo = NULL;
 #endif
-  _compute_canceled = false;
+  _computeCanceled = false;
   
-  // Copy of what is done in BLSURFPLugin TODO : share the code
-  smeshGen_i = SMESH_Gen_i::GetSMESHGen();
-  CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
-  SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
-  
-  myStudy = NULL;
-  myStudy = aStudyMgr->GetStudyByID(_studyId);
-  if (myStudy)
-    MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
 }
 
 //=============================================================================
@@ -139,7 +127,7 @@ HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
                                                    const TopoDS_Shape& aShape )
 {
-  // MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
+  MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
   _blsurfHypo = NULL;
 
   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
@@ -147,7 +135,8 @@ bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
 
   // If a BLSURF hypothesis is applied, get it
   SMESH_HypoFilter blsurfFilter;
-  blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType() ));
+  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 );
 
@@ -155,7 +144,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 == BLSURFPlugin_Hypothesis::GetHypType()) {
+    if (hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
+        hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
+    {
       _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
       ASSERT(_blsurfHypo);
       return true;
@@ -175,7 +166,7 @@ bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&
                                              const TopoDS_Shape&                  aShape,
                                              SMESH_Hypothesis::Hypothesis_Status& aStatus )
 {
-  // MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
+  MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
   _hypothesis = NULL;
 
   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
@@ -184,6 +175,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
   }
@@ -254,21 +249,28 @@ static TopoDS_Shape findShape(SMDS_MeshNode**     t_Node,
 //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;
+static int getNbShape(MG_Hexotic_API* hexaOutput, int iMesh, GmfKwdCod what, int defaultValue=0)
+{
+  int number = hexaOutput->GmfStatKwd( iMesh, what );
+  if ( number > 0 )
+  {
+  // 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;
-    }
+    //   break;
+    // }
   }
-  file.close();
+  else
+  {
+    number = defaultValue;
+  }
+  //file.close();
   return number;
 }
 
@@ -277,9 +279,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() ) {
@@ -296,7 +300,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() ) {
@@ -348,18 +353,81 @@ static void splitQuads(SMESH_Mesh& aMesh)
   spliter.QuadToTri ( elems, /*the13Diag=*/true);
 }
 
+//=======================================================================
+//function : writeInput
+//purpose  : pass a mesh to input of MG-Hexa
+//=======================================================================
+
+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 ));
+  }
+
+  // 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() );
+    }
+  }
+
+  // triangles
+  elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
+  if ( elemIt->more() )
+  {
+    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() );
+    }
+  }
+  theHexaInput->GmfCloseMesh( meshID );
+}
+
 //=======================================================================
 //function : readResult
 //purpose  : Read GMF file in case of a mesh with geometry
 //=======================================================================
 
-static bool readResult(std::string         theFile,
-                       HexoticPlugin_Hexotic*  theAlgo,
-                       SMESHDS_Mesh*       theMesh,
-                       const int           nbShape,
-                       const TopoDS_Shape* tabShape,
-                       double**            tabBox)
+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)
 {
+  SMESH_Mesh*     theMesh = theHelper->GetMesh();
+  SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
+
   // ---------------------------------
   // Read generated elements and nodes
   // ---------------------------------
@@ -367,409 +435,209 @@ static bool readResult(std::string         theFile,
   TopoDS_Shape aShape;
   TopoDS_Vertex aVertex;
   std::string token;
-  int EndOfFile = 0, nbElem = 0, nField = 9, nbRef = 0;
-  int aHexoticNodeID = 0, shapeID, hexoticShapeID;
+  int shapeID, hexoticShapeID;
   const int IdShapeRef = 2;
-  int *tabID, *tabRef, *nodeAssigne;
-  bool *tabDummy, hasDummy = false;
+  int *tabID = 0;
   double epsilon = Precision::Confusion();
   std::map <std::string,int> mapField;
   SMDS_MeshNode** HexoticNode;
-  TopoDS_Shape *tabCorner, *tabEdge;
+  TopoDS_Shape *tabCorner;
 
   const int nbDomains = countShape( theMesh, TopAbs_SHELL );
   const int holeID = -1;
 
-  // 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 );
+  if ( nbDomains > 0 )
+  {
+    tabID = new int[nbDomains];
 
-  tabCorner   = new TopoDS_Shape[ nbCorners ];
-  tabEdge     = new TopoDS_Shape[ nbShapeEdge ];
-  nodeAssigne = new int[ nbVertices + 1 ];
-  HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
+    for (int i=0; i<nbDomains; i++)
+      tabID[i] = 0;
+    if ( nbDomains == 1 )
+      tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
+  }
+  else
+  {
+    tabID = new int[1];
+    tabID[0] = 1;
+  }
 
-  getShape(theMesh, TopAbs_VERTEX, tabCorner);
-  getShape(theMesh, TopAbs_EDGE,   tabEdge);
+  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 == 0  ) {
-    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 nbVertices  = getNbShape(theHexaOutput, meshID, GmfVertices );
+  int nbCorners   = getNbShape(theHexaOutput, meshID, GmfCorners, countShape( theMesh, TopAbs_VERTEX ));
+  if ( nbVertices == 0 )
+    return false;
+
+  tabCorner   = new TopoDS_Shape[ nbCorners ];
+  HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
+
+  if ( nbCorners > 0 )
+    getShape(theMeshDS, TopAbs_VERTEX, tabCorner);
+
+  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 < int(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;
-      }
-      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++ ) {
-          if(theAlgo->computeCanceled())
-            {
-              return false;
-            }
-          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++ ) {
-          if(theAlgo->computeCanceled())
-            {
-              return false;
-            }
-          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;
-              }
-              if ( nodeAssigne[ nodeID[0] ] != 0 ) { // because "Edges" go before "Corners"
-                theMesh->UnSetNodeOnShape( node[0] );
-                nodeAssigne[ nodeID[0] ] = 0;
-              }
-              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;
-              shapeID = dummy;
-              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 );
-          }
+  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;
         }
-        delete [] node;
-        delete [] nodeID;
-        break;
-      }
-      case 8: { // "End"
-        EndOfFile = 1;
-        MESSAGE("End of " << theFile << " file");
-        break;
-      }
-      default: {
-        MESSAGE("Unknown Token: " << token);
       }
     }
   }
-  cout << std::endl;
 
-  // remove nodes in holes
-  if ( nbDomains > 1 )
+  int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
+  if ( nbEdges > 0 )
   {
-    SMESHDS_SubMesh* subMesh;
-    for ( int i = 1; i <= nbVertices; ++i )
-      if ( HexoticNode[i]->NbInverseElements() == 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 )
       {
-        subMesh =  HexoticNode[i]->getshapeId() > 0 ? theMesh->MeshElements(HexoticNode[i]->getshapeId() ) : 0;
-        theMesh->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
+        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 );
+    }
   }
-  delete [] tabID;
-  delete [] tabRef;
-  delete [] tabDummy;
-  delete [] tabCorner;
-  delete [] tabEdge;
-  delete [] nodeAssigne;
-  delete [] HexoticNode;
-  return true;
-}
-
-
-//=======================================================================
-//function : readResult
-//purpose  : Read GMF file in case of a mesh w/o geometry
-//=======================================================================
-
-static bool readResult(std::string theFile,
-                       HexoticPlugin_Hexotic*  theAlgo,
-                       SMESH_MesherHelper* theHelper)
-{
-  SMESHDS_Mesh* theMesh = theHelper->GetMeshDS();
-
-  // ---------------------------------
-  // Read generated elements and nodes
-  // ---------------------------------
-
-  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;
-  std::map <std::string,int> mapField;
-  SMDS_MeshNode** HexoticNode;
-
-  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;
 
+  int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
+  if ( nbQuad > 0 )
   {
-    // theMesh->Clear(); -- this does not remove imported mesh
-    SMDS_ElemIteratorPtr eIt = theMesh->elementsIterator();
-    while( eIt->more() )
-      theMesh->RemoveFreeElement( eIt->next(), /*sm=*/0 );
-    SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
-    while ( nIt->more() )
-      theMesh->RemoveFreeNode( nIt->next(), /*sm=*/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 );
+      }
+      aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
+      if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
+        theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
+    }
   }
 
-  int nbVertices = getNbShape(theFile, "Vertices");
-  HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
-  nodeAssigne = new int[ nbVertices + 1 ];
-
-  MESSAGE("Read " << theFile << " file");
-  std::ifstream fileRes(theFile.c_str());
-  ASSERT(fileRes);
-
-  while ( !EndOfFile  )
+  int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
+  if ( nbHexa > 0 )
   {
-    int dummy;
-    fileRes >> token;
-
-    if (mapField.count(token)) {
-      nField   = mapField[token];
-      nbRef    = tabRef[nField];
-      hasDummy = tabDummy[nField];
-    }
-    else {
-      nField = -1;
-      nbRef = 0;
-    }
-
-    nbElem = 0;
-    if ( nField < int(mapField.size() - 1) && nField >= 0 )
-      fileRes >> nbElem;
-
-    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[3];
-      SMDS_MeshNode * aHexoticNode;
-
-      for ( int iElem = 0; iElem < nbElem; iElem++ ) {
-        if(theAlgo->computeCanceled())
-          {
-            return false;
-          }
-        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;
-      }
-      break;
-    }
-    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++ )
+    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 )
       {
-        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;
           }
-        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;
 
-  shapeID = theHelper->GetSubShapeID();
-  for ( int i = 0; i < nbVertices; ++i )
-    if ( !nodeAssigne[ i+1 ])
-      theMesh->SetNodeInVolume( HexoticNode[ i+1 ], shapeID );
-
+  // 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 );
+      }
+  }
+  delete [] tabID;
+  delete [] tabCorner;
   delete [] HexoticNode;
-  delete [] nodeAssigne;
   return true;
 }
 
@@ -795,7 +663,7 @@ void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
     _hexoticVerbosity = hyp->GetHexoticVerbosity();
     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
     _hexoticSdMode = hyp->GetHexoticSdMode();
-    _textOptions = hyp->GetTextOptions();
+    _textOptions = hyp->GetAdvancedOption();
     _sizeMaps = hyp->GetSizeMaps();
     _nbLayers = hyp->GetNbLayers();
     _firstLayerSize = hyp->GetFirstLayerSize();
@@ -831,42 +699,6 @@ void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
   }
 }
 
-//=======================================================================
-//function : getTmpDir
-//purpose  :
-//=======================================================================
-
-// static TCollection_AsciiString getTmpDir()
-// {
-//   TCollection_AsciiString aTmpDir;
-
-//   char *Tmp_dir = getenv("SALOME_TMP_DIR");
-// #ifdef WIN32
-//   if(Tmp_dir == NULL) {
-//     Tmp_dir = getenv("TEMP");
-//     if( Tmp_dir== NULL )
-//       Tmp_dir = getenv("TMP");
-//   }
-// #endif
-
-//   if(Tmp_dir != NULL) {
-//     aTmpDir = Tmp_dir;
-// #ifdef WIN32
-//     if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
-// #else
-//     if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
-// #endif
-//   }
-//   else {
-// #ifdef WIN32
-//     aTmpDir = TCollection_AsciiString("C:\\");
-// #else
-//     aTmpDir = TCollection_AsciiString("/tmp/");
-// #endif
-//   }
-//   return aTmpDir;
-// }
-
 //=======================================================================
 //function : getSuffix
 //purpose  : Returns a suffix that will be unique for the current process
@@ -879,7 +711,9 @@ static TCollection_AsciiString getSuffix()
 #ifndef WIN32
   aSuffix += getenv("USER");
 #else
-  aSuffix += getenv("USERNAME");
+  std::string uname = std::string(getenv("USERNAME"));
+  replace(uname.begin(), uname.end(), ' ', '_');
+  aSuffix += uname.c_str();
 #endif
   aSuffix += "_";
   aSuffix += Kernel_Utils::GetHostname().c_str();
@@ -901,7 +735,8 @@ static TCollection_AsciiString getSuffix()
 
 std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
                                                      const TCollection_AsciiString& Hexotic_Out,
-                                                     const TCollection_AsciiString& Hexotic_SizeMap_Prefix) const
+                                                     const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
+                                                     const bool                     forExecutable) const
 {
   cout << std::endl;
   cout << "MG-Hexa execution..." << std::endl;
@@ -944,7 +779,7 @@ std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiStri
     cout << std::endl;
   }
 
-  TCollection_AsciiString run_Hexotic( "mg-hexa.exe" );
+  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 ";
@@ -1030,7 +865,7 @@ std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiStri
   if (_hexoticSharpAngleThreshold > 0)
     run_Hexotic +=  angle + sharpAngle;
   
-  if (_sizeMaps.begin() != _sizeMaps.end())
+  if (_sizeMaps.begin() != _sizeMaps.end() && forExecutable )
     run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
 
   if (_nbLayers       > 0 &&
@@ -1046,7 +881,8 @@ std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiStri
     if (!_imprintedFaces.empty())
       run_Hexotic += comImptintedFaces + imprintedFaces;
   }
-  run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
+  if ( forExecutable )
+    run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
   run_Hexotic += subdom + mode;
 #ifndef WIN32
   run_Hexotic += proc + nbproc;
@@ -1065,16 +901,17 @@ std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiStri
 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
 {
   MESSAGE("HexoticPlugin_Hexotic::entryToShape "<<entry );
+
   GEOM::GEOM_Object_var aGeomObj;
   TopoDS_Shape S = TopoDS_Shape();
-  SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
+  SALOMEDS::SObject_var aSObj = SMESH_Gen_i::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 = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
+    S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
   return S;
 }
 
@@ -1083,15 +920,12 @@ TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
  * \brief Produces a .mesh file with the size maps informations to give to Hexotic
  */
 //================================================================================
-std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( std::string sizeMapPrefix )
+std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
+                                                                  std::string     sizeMapPrefix )
 {
-  HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it ;
-  
-  // The GMF driver will be used to write the size map file
-  DriverGMF_Write aWriter;
-  aWriter.SetSizeMapPrefix( sizeMapPrefix ); 
+  HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
   
-  std::vector<Control_Pnt> points;
+  std::vector<ControlPnt> points;
   // Iterate on the size maps
   for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
   {
@@ -1104,348 +938,45 @@ std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( std::string si
     // Step 2 : Create the points
     createControlPoints( aShape, aLocalSize, points );
   }
-  // Write the .mesh size map file
-  aWriter.PerformSizeMap(points); 
-  return aWriter.GetSizeMapFiles();
-}
-
-//================================================================================
-/*!
- * \brief Fills a vector of points from which a size map input file can be written
- */
-//================================================================================
-void HexoticPlugin_Hexotic::createControlPoints( const TopoDS_Shape& aShape, 
-                                                 const double& theSize, 
-                                                 std::vector<Control_Pnt>& thePoints )
-{ 
-  if ( aShape.ShapeType() == TopAbs_VERTEX )
-  {
-    gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex(aShape) );
-    Control_Pnt aControl_Pnt( aPnt, theSize );
-    thePoints.push_back( aControl_Pnt );
-  }
-  if ( aShape.ShapeType() == TopAbs_EDGE )
-  {
-    createPointsSampleFromEdge( aShape, theSize, thePoints );  
-  }
-  else if ( aShape.ShapeType() == TopAbs_WIRE )
-  {
-    TopExp_Explorer Ex;
-    for (Ex.Init(aShape,TopAbs_EDGE); Ex.More(); Ex.Next()) 
-    {
-      createPointsSampleFromEdge( Ex.Current(), theSize, thePoints );
-    } 
-  }
-  else if ( aShape.ShapeType() ==  TopAbs_FACE )
-  {
-    createPointsSampleFromFace( aShape, theSize, thePoints ); 
-  }
-  else if ( aShape.ShapeType() ==  TopAbs_SOLID )
-  {
-    createPointsSampleFromSolid( aShape, theSize, thePoints ); 
-  }
-  else if ( aShape.ShapeType() == TopAbs_COMPOUND )
-  {
-    TopoDS_Iterator it( aShape );
-    for(; it.More(); it.Next())
-    {
-      createControlPoints( it.Value(), theSize, thePoints );
-    }
-  }
-}
-
-//================================================================================
-/*!
- * \brief Fills a vector of points with point samples approximately 
- * \brief spaced with a given size
- */
-//================================================================================
-void HexoticPlugin_Hexotic::createPointsSampleFromEdge( const TopoDS_Shape& aShape, 
-                                                        const double& theSize, 
-                                                        std::vector<Control_Pnt>& thePoints )
-{
-  double step = theSize;
-  double first, last;  
-  Handle( Geom_Curve ) aCurve = BRep_Tool::Curve( TopoDS::Edge( aShape ), first, last );
-  GeomAdaptor_Curve C ( aCurve );
-  GCPnts_UniformAbscissa DiscretisationAlgo(C, step , first, last, Precision::Confusion());
-  int nbPoints = DiscretisationAlgo.NbPoints();
-  
-  for ( int i = 1; i <= nbPoints; i++ )
-  {
-    double param = DiscretisationAlgo.Parameter( i );
-    Control_Pnt aPnt;
-    aCurve->D0( param, aPnt );
-    aPnt.SetSize(theSize);
-    thePoints.push_back( aPnt );
-  }  
-}
 
-//================================================================================
-/*!
- * \brief Fills a vector of points with point samples approximately 
- * \brief spaced with a given size
- */
-//================================================================================
-void HexoticPlugin_Hexotic::createPointsSampleFromFace( const TopoDS_Shape& aShape, 
-                                                        const double& theSize, 
-                                                        std::vector<Control_Pnt>& thePoints )
-{
-  BRepMesh_IncrementalMesh M(aShape, 0.01, Standard_True);
-  TopLoc_Location aLocation;
-  TopoDS_Face aFace = TopoDS::Face(aShape);
-
-  // Triangulate the face
-  Handle(Poly_Triangulation) aTri = BRep_Tool::Triangulation (aFace, aLocation);
-  
-  // Get the transformation associated to the face location
-  gp_Trsf aTrsf = aLocation.Transformation();
-  
-  // Get triangles
-  int nbTriangles = aTri->NbTriangles();
-  Poly_Array1OfTriangle triangles(1,nbTriangles);
-  triangles=aTri->Triangles();
-  
-  // GetNodes
-  int nbNodes = aTri->NbNodes();
-  TColgp_Array1OfPnt nodes(1,nbNodes);
-  nodes = aTri->Nodes();
-
-  // Iterate on triangles and subdivide them
-  for(int i=1; i<=nbTriangles; i++)
-  {
-     Poly_Triangle aTriangle = triangles.Value(i);
-     gp_Pnt p1 = nodes.Value(aTriangle.Value(1));
-     gp_Pnt p2 = nodes.Value(aTriangle.Value(2));
-     gp_Pnt p3 = nodes.Value(aTriangle.Value(3));
-     
-     p1.Transform(aTrsf);
-     p2.Transform(aTrsf);
-     p3.Transform(aTrsf);
-     
-     subdivideTriangle(p1, p2, p3, theSize, thePoints);  
-  }
-}
+  // Write the .mesh size map file
 
-//================================================================================
-/*!
- * \brief Fills a vector of points with point samples approximately 
- * \brief spaced with a given size
- */
-//================================================================================
-void HexoticPlugin_Hexotic::createPointsSampleFromSolid( const TopoDS_Shape& aShape, 
-                                                         const double& theSize, 
-                                                         std::vector<Control_Pnt>& thePoints )
-{
-  // Compute the bounding box
-  double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
-  Bnd_Box B;               
-  BRepBndLib::Add(aShape, B);
-  B.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
+  std::string myVerticesFile = sizeMapPrefix + ".mesh";
+  std::string      mySolFile = sizeMapPrefix + ".sol";
   
-  // Create the points
-  double step = theSize;
+  // Open files
+  int verticesFileID =
+    mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );  
+  int solFileID =
+    mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
   
-  for ( double x=Xmin; x-Xmax<Precision::Confusion(); x=x+step )
-  {
-    for ( double y=Ymin; y-Ymax<Precision::Confusion(); y=y+step )
-    {
-      // Step1 : generate the Zmin -> Zmax line
-      gp_Pnt startPnt(x, y, Zmin);
-      gp_Pnt endPnt(x, y, Zmax);
-      gp_Vec aVec(startPnt, endPnt);
-      gp_Lin aLine(startPnt, aVec);
-      double endParam = Zmax - Zmin;
-      
-      // Step2 : for each face of aShape:
-      std::set<double> intersections;
-      std::set<double>::iterator it = intersections.begin();
-      
-      TopExp_Explorer Ex;
-      for (Ex.Init(aShape,TopAbs_FACE); Ex.More(); Ex.Next()) 
-      { 
-        // check if there is an intersection
-        IntCurvesFace_Intersector anIntersector(TopoDS::Face(Ex.Current()), Precision::Confusion());
-        anIntersector.Perform(aLine, 0, endParam);
-        
-        // get the intersection's parameter and store it
-        int nbPoints = anIntersector.NbPnt();
-        for(int i = 0 ; i < nbPoints ; i++ )
-        {
-          it = intersections.insert( it, anIntersector.WParameter(i+1) );
-        }
-      }
-      // Step3 : go through the line chunk by chunk 
-      if ( intersections.begin() != intersections.end() )
-      {
-        std::set<double>::iterator intersectionsIterator=intersections.begin();
-        double first = *intersectionsIterator;
-        intersectionsIterator++;
-        bool innerPoints = true; 
-        for ( ; intersectionsIterator!=intersections.end() ; intersectionsIterator++ )
-        {
-          double second = *intersectionsIterator;
-          if ( innerPoints )
-          {
-            // If the last chunk was outside of the shape or this is the first chunk
-            // add the points in the range [first, second] to the points vector
-            double localStep = (second -first) / ceil( (second - first) / step );
-            for ( double z = Zmin + first; z < Zmin + second; z = z + localStep )
-            {
-              thePoints.push_back(Control_Pnt( x, y, z, theSize ));
-            }
-            thePoints.push_back(Control_Pnt( x, y, Zmin + second, theSize ));
-          }
-          first = second;
-          innerPoints = !innerPoints;
-        }
-      }
-    }
-  }
-}
-
-//================================================================================
-/*!
- * \brief Subdivides a triangle until it reaches a certain size (recursive function)
- */
-//================================================================================
-void HexoticPlugin_Hexotic::subdivideTriangle( const gp_Pnt& p1, 
-                                               const gp_Pnt& p2, 
-                                               const gp_Pnt& p3, 
-                                               const double& theSize, 
-                                               std::vector<Control_Pnt>& thePoints)
-{
-  // Size threshold to stop subdividing
-  // This value ensures that two control points are distant no more than 2*theSize
-  // as shown below
-  //
-  // The greater distance D of the mass center M to each Edge is 1/3 * Median 
-  // and Median < sqrt(3/4) * a  where a is the greater side (by using Apollonius' thorem). 
-  // So D < 1/3 * sqrt(3/4) * a and if a < sqrt(3) * S then D < S/2
-  // and the distance between two mass centers of two neighbouring triangles 
-  // sharing an edge is < 2 * 1/2 * S = S
-  // If the traingles share a Vertex and no Edge the distance of the mass centers 
-  // to the Vertices is 2*D < S so the mass centers are distant of less than 2*S 
+  int pointsNumber = points.size();
   
-  double threshold = sqrt( 3. ) * theSize;
+  // Vertices Keyword
+  mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
+  // SolAtVertices Keyword
+  int TypTab[] = {GmfSca};
+  mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
   
-  if ( (p1.Distance(p2) > threshold ||
-        p2.Distance(p3) > threshold ||
-        p3.Distance(p1) > threshold))
-  { 
-    std::vector<gp_Pnt> midPoints = computePointsForSplitting(p1, p2, p3);
-    subdivideTriangle( midPoints[0], midPoints[1], midPoints[2], theSize, thePoints );
-    subdivideTriangle( midPoints[0], p2, midPoints[1], theSize, thePoints );
-    subdivideTriangle( midPoints[2], midPoints[1], p3, theSize, thePoints );
-    subdivideTriangle( p1, midPoints[0], midPoints[2], theSize, thePoints );
-  }
-  else
+  // 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++ )
   {
-    double x = (p1.X() + p2.X() + p3.X()) / 3 ;
-    double y = (p1.Y() + p2.Y() + p3.Y()) / 3 ;
-    double z = (p1.Z() + p2.Z() + p3.Z()) / 3 ;
-    
-    Control_Pnt massCenter( x ,y ,z, theSize );
-    thePoints.push_back( massCenter );
+    mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
+    ValTab[0] = points_it->Size();
+    mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
   }
-}
 
-//================================================================================
-/*!
- * \brief Returns the appropriate points for splitting a triangle
- * \brief the tangency points of the incircle are used in order to have mostly
- * \brief well-shaped sub-triangles
- */
-//================================================================================
-std::vector<gp_Pnt> HexoticPlugin_Hexotic::computePointsForSplitting( const gp_Pnt& p1, 
-                                                                      const gp_Pnt& p2, 
-                                                                      const gp_Pnt& p3 )
-{
-  std::vector<gp_Pnt> midPoints;
-  //Change coordinates
-  gp_Trsf Trsf_1;            // Identity transformation
-  gp_Ax3 reference_system(gp::Origin(), gp::DZ(), gp::DX());   // OXY
-  gp_Vec Vx(p1, p3);
-  gp_Vec Vaux(p1, p2);
-  gp_Dir Dx(Vx);
-  gp_Dir Daux(Vaux);
-  gp_Dir Dz = Dx.Crossed(Daux);
-  gp_Ax3 current_system(p1, Dz, Dx);
-  
-  Trsf_1.SetTransformation( reference_system, current_system );
-  
-  gp_Pnt A = p1.Transformed(Trsf_1);
-  gp_Pnt B = p2.Transformed(Trsf_1);
-  gp_Pnt C = p3.Transformed(Trsf_1);
-  
-  double a =  B.Distance(C) ;
-  double b =  A.Distance(C) ;
-  double c =  B.Distance(A) ;
-  
-  // Incenter coordinates
-  // see http://mathworld.wolfram.com/Incenter.html
-  double Xi = ( b*B.X() + c*C.X() ) / ( a + b + c );
-  double Yi = ( b*B.Y() ) / ( a + b + c );
-  gp_Pnt Center(Xi, Yi, 0);
-  
-  // Calculate the tangency points of the incircle
-  gp_Pnt T1 = tangencyPoint( A, B, Center);
-  gp_Pnt T2 = tangencyPoint( B, C, Center);
-  gp_Pnt T3 = tangencyPoint( C, A, Center);
-  
-  gp_Pnt p1_2 = T1.Transformed(Trsf_1.Inverted());
-  gp_Pnt p2_3 = T2.Transformed(Trsf_1.Inverted());
-  gp_Pnt p3_1 = T3.Transformed(Trsf_1.Inverted());
+  // Close Files
+  mgInput->GmfCloseMesh( verticesFileID );
+  mgInput->GmfCloseMesh( solFileID );
 
-  midPoints.push_back(p1_2);
-  midPoints.push_back(p2_3);
-  midPoints.push_back(p3_1);
-  
-  return midPoints;
-}
+  std::vector<std::string> fileNames(2);
+  fileNames[0] = myVerticesFile;
+  fileNames[1] = mySolFile;
 
-//================================================================================
-/*!
- * \brief Computes the tangency points of the circle of center Center with
- * \brief the straight line (p1 p2)
- */
-//================================================================================
-gp_Pnt HexoticPlugin_Hexotic::tangencyPoint(const gp_Pnt& p1,
-                                            const gp_Pnt& p2,
-                                            const gp_Pnt& Center)
-{
-  double Xt = 0;
-  double Yt = 0;
-  
-  // The tangency point is the intersection of the straight line (p1 p2)
-  // and the straight line (Center T) which is orthogonal to (p1 p2)
-  if ( fabs(p1.X() - p2.X()) <= Precision::Confusion() )
-  {
-    Xt=p1.X();     // T is on (p1 p2)
-    Yt=Center.Y(); // (Center T) is orthogonal to (p1 p2)
-  }
-  else if ( fabs(p1.Y() - p2.Y()) <= Precision::Confusion() )
-  {
-    Yt=p1.Y();     // T is on (p1 p2) 
-    Xt=Center.X(); // (Center T) is orthogonal to (p1 p2)
-  }
-  else
-  {
-    // First straight line coefficients (equation y=a*x+b)
-    double a = (p2.Y() - p1.Y()) / (p2.X() - p1.X())  ;
-    double b = p1.Y() - a*p1.X();         // p1 is on this straight line
-    
-    // Second straight line coefficients (equation y=c*x+d)
-    double c = -1 / a;                    // The 2 lines are orthogonal
-    double d = Center.Y() - c*Center.X(); // Center is on this straight line
-    
-    Xt = (d - b) / (a - c);
-    Yt = a*Xt + b;
-  }
-  
-  return gp_Pnt( Xt, Yt, 0 );
+  return fileNames;
 }
 
 //=============================================================================
@@ -1457,38 +988,14 @@ gp_Pnt HexoticPlugin_Hexotic::tangencyPoint(const gp_Pnt& p1,
 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
                                     const TopoDS_Shape& aShape)
 {
-  _compute_canceled = false;
+  _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
-  }
-
-  // to prevent from displaying error message after computing,
-  // SetIsAlwaysComputed( true ) to empty sub-meshes
-  std::vector< SMESH_subMesh* > subMeshesAlwaysComp;
-  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 );
-          subMeshesAlwaysComp.push_back( sm );
-        }
-      }
-    }
-
-  _iShape++;
-
-  if (_iShape == _nbShape ) {
+  _nbShape = countShape( &aMesh, TopAbs_SOLID );  // we count the number of shapes
 
+  {
     // create bounding box for each shape of the compound
 
     int iShape = 0;
@@ -1515,36 +1022,47 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
 
     SetParameters(_hypothesis);
 
-//     TCollection_AsciiString aTmpDir = getTmpDir();
     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, Hexotic_SizeMap_Prefix;
-    TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );    TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
+    TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
+    TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
 
     std::map <int,int> aSmdsToHexoticIdMap;
     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
 
+    MG_Hexotic_API mgHexa( _computeCanceled, _progress );
+
     Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
 #ifdef WITH_BLSURFPLUGIN
     bool defaultInputFile = true;
-    if (_blsurfHypo && !_blsurfHypo->GetQuadAllowed()) {
+    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"+getSuffix()+"_In.mesh";
       removeHexoticFiles(Hexotic_In, Hexotic_Out);
       splitQuads(aMesh); // quadrangles are no longer acceptable as input
-      cout << std::endl;
-      cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
-      aMesh.ExportGMF(Hexotic_In.ToCString(), meshDS, true);
+      if ( mgHexa.IsExecutable() )
+      {
+        cout << std::endl;
+        cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
+      }
+      writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
 #ifdef WITH_BLSURFPLUGIN
     }
     else {
@@ -1553,98 +1071,84 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
 #endif
     
     Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
-    std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
+    std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
     
-    std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
-    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() );
+    cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
 
     cout << std::endl;
     cout << "MG-Hexa command : " << run_Hexotic << std::endl;
 
+    if ( mgHexa.IsExecutable() )
+    {
 #ifndef WIN32    
-    modeFile_In += Hexotic_In;
-    system( modeFile_In.ToCString() );
+      modeFile_In += Hexotic_In;
+      system( modeFile_In.ToCString() );
 #endif
+    }
     aSmdsToHexoticIdMap.clear();
     aHexoticIdToNodeMap.clear();
 
     MESSAGE("HexoticPlugin_Hexotic::Compute");
 
-    int status = system( run_Hexotic.data() );
+    
+    std::string errStr;
+    Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
+
 
     // --------------
     // read a result
     // --------------
 
-    std::ifstream fileRes( Hexotic_Out.ToCString() );
-#ifndef WIN32  
-    modeFile_Out += Hexotic_Out;
-    system( modeFile_Out.ToCString() );
+    if ( mgHexa.IsExecutable() )
+    {
+#ifndef WIN32
+      modeFile_Out += Hexotic_Out;
+      system( modeFile_Out.ToCString() );
 #endif
-    if ( ! fileRes.fail() ) {
-      Ok = readResult( Hexotic_Out.ToCString(),
-                       this,
-                       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";
-        #ifndef _DEBUG_
-        removeFile(Hexotic_Out);
-        removeFile(Hexotic_In);
-        removeFile(aLogFileName);
-        for( int i=0; i<sizeMapFiles.size(); i++)
-        {
-          removeFile( TCollection_AsciiString( sizeMapFiles[i].c_str() ) );
-        }
-        #endif
-      }
-      else {
-        hexahedraMessage = "failed"; 
+    }
+    SMESH_MesherHelper aHelper( aMesh );
+
+    Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
+                     this,
+                     &aHelper, _nbShape, tabShape, tabBox );
+
+    std::string log = mgHexa.GetLog();
+    if ( Ok )
+    {
+      hexahedraMessage = "success";
+#ifndef _DEBUG_
+      removeFile(Hexotic_Out);
+      removeFile(Hexotic_In);
+      //removeFile(aLogFileName);
+      for( size_t i=0; i<sizeMapFiles.size(); i++)
+      {
+        removeFile( TCollection_AsciiString( sizeMapFiles[i].c_str() ) );
       }
+#endif
     }
-    else {
+    else
+    {
       hexahedraMessage = "failed";
-      cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
-      Ok = false;
+      if ( mgHexa.IsExecutable() )
+        cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
       // analyse log file
-      SMESH_File logFile( aLogFileName.ToCString() );
-      if ( !logFile.eof() )
+      if ( !log.empty() )
       {
         char msgLic[] = " Dlim ";
-        const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
+        std::string log = mgHexa.GetLog();
+        const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
           error("Licence problems.");
       }
-#ifndef WIN32
-      if ( status > 0 && WEXITSTATUS(status) == 127 )
-        error("mg-hexa.exe: command not found");
-#else
-      int err = errno;
-      if ( status == 0 && err == ENOENT ) {
-        error("mg-hexa.exe: command not found");
-      }
-#endif
+      if ( !errStr.empty() )
+        error(errStr);
     }
     cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
     cout << std::endl;
 
-    // restore "always computed" flag of sub-meshes (0022127)
-    for  ( size_t iSM = 0; iSM < subMeshesAlwaysComp.size(); ++iSM )
-      subMeshesAlwaysComp[ iSM ]->SetIsAlwaysComputed( false );
-
     delete [] tabShape;
     for (int i=0; i<_nbShape; i++)
       delete [] tabBox[i];
@@ -1652,8 +1156,10 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
     _nbShape = 0;
     _iShape  = 0;
   }
-  if(_compute_canceled)
+
+  if(_computeCanceled)
     return error(SMESH_Comment("interruption initiated by user"));
+
   return Ok;
 }
 
@@ -1670,13 +1176,16 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
 
 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
 {
-  _compute_canceled = false;
+  _computeCanceled = false;
 /*
   SMESH_ComputeErrorPtr myError = SMESH_ComputeError::New();
 */
   bool Ok = true;
   TCollection_AsciiString hexahedraMessage;
-
+  TCollection_AsciiString aQuote("");
+#ifdef WIN32
+    aQuote = "\"";
+#endif
   SetParameters(_hypothesis);
 
   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
@@ -1691,11 +1200,14 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHel
   Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
   Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
  
-  
-  std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
+  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, Hexotic_SizeMap_Prefix);
-  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() );
+  cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
 
   removeHexoticFiles(Hexotic_In, Hexotic_Out);
 
@@ -1703,11 +1215,14 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHel
 
   cout << std::endl;
   cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
-  aMesh.ExportGMF(Hexotic_In.ToCString(), aHelper->GetMeshDS());
+  writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
+  if ( mgHexa.IsExecutable() )
+  {
 #ifndef WIN32    
-  modeFile_In += Hexotic_In;
-  system( modeFile_In.ToCString() );
+    modeFile_In += Hexotic_In;
+    system( modeFile_In.ToCString() );
 #endif
+  }
   aSmdsToHexoticIdMap.clear();
   aHexoticIdToNodeMap.clear();
 
@@ -1715,81 +1230,54 @@ bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHel
 
   cout << std::endl;
   cout << "MG-Hexa command : " << run_Hexotic << std::endl;
-  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(),
-                     this,
-                     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() )
+  {
+    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 MG-Hexa 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 MG-Hexa output file ")<<Hexotic_Out);
+    if ( mgHexa.IsExecutable() )
+      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;
 
-  if(_compute_canceled)
+  if(_computeCanceled)
     return error(SMESH_Comment("interruption initiated by user"));
   removeFile(Hexotic_Out);
   removeFile(Hexotic_In);
-  removeFile(aLogFileName);
+  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();
-*/
 }
 
 //=============================================================================
@@ -1798,9 +1286,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;
@@ -1815,7 +1303,7 @@ bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
 
 void HexoticPlugin_Hexotic::CancelCompute()
 {
-  _compute_canceled = true;
+  _computeCanceled = true;
 #ifdef WIN32
 #else
   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();