Salome HOME
Merge remote branch 'origin/eap/23307'
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
index fa3e87fa5c0e8778b08659f0c81e10fc29d17c91..ca54cf399db7228228ada1e08581c449c731623d 100644 (file)
@@ -1,9 +1,9 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D
+// Copyright (C) 2007-2016  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
@@ -15,6 +15,7 @@
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
 // ---
 // File    : BLSURFPlugin_BLSURF.cxx
@@ -30,7 +31,6 @@
 extern "C"{
 #include <meshgems/meshgems.h>
 #include <meshgems/cadsurf.h>
-#include <meshgems/precad.h>
 }
 
 #include <structmember.h>
@@ -48,6 +48,7 @@ extern "C"{
 #include <SMESH_MesherHelper.hxx>
 #include <StdMeshers_FaceSide.hxx>
 #include <StdMeshers_ViscousLayers2D.hxx>
+#include <SMESH_File.hxx>
 
 #include <utilities.h>
 
@@ -90,116 +91,120 @@ extern "C"{
 #include <gp_XY.hxx>
 #include <gp_XYZ.hxx>
 
-#ifndef WNT
+#ifndef WIN32
 #include <fenv.h>
 #endif
 
+using namespace std;
+
 /* ==================================
  * ===========  PYTHON ==============
  * ==================================*/
 
-typedef struct {
-  PyObject_HEAD
-  int softspace;
-  std::string *out;
-  } PyStdOut;
-
-static void
-PyStdOut_dealloc(PyStdOut *self)
+namespace
 {
-  PyObject_Del(self);
-}
+  typedef struct {
+    PyObject_HEAD
+    int softspace;
+    std::string *out;
+    } PyStdOut;
+
+  static void
+  PyStdOut_dealloc(PyStdOut *self)
+  {
+    PyObject_Del(self);
+  }
 
-static PyObject *
-PyStdOut_write(PyStdOut *self, PyObject *args)
-{
-  char *c;
-  int l;
-  if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
-    return NULL;
+  static PyObject *
+  PyStdOut_write(PyStdOut *self, PyObject *args)
+  {
+    char *c;
+    int l;
+    if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
+      return NULL;
 
-  //std::cerr << c ;
-  *(self->out)=*(self->out)+c;
+    *(self->out)=*(self->out)+c;
 
-  Py_INCREF(Py_None);
-  return Py_None;
-}
+    Py_INCREF(Py_None);
+    return Py_None;
+  }
 
-static PyMethodDef PyStdOut_methods[] = {
-  {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
-    PyDoc_STR("write(string) -> None")},
-  {NULL,    NULL}   /* sentinel */
-};
-
-static PyMemberDef PyStdOut_memberlist[] = {
-  {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
-   (char*)"flag indicating that a space needs to be printed; used by print"},
-  {NULL} /* Sentinel */
-};
-
-static PyTypeObject PyStdOut_Type = {
-  /* The ob_type field must be initialized in the module init function
-   * to be portable to Windows without using C++. */
-  PyObject_HEAD_INIT(NULL)
-  0,                            /*ob_size*/
-  "PyOut",                      /*tp_name*/
-  sizeof(PyStdOut),             /*tp_basicsize*/
-  0,                            /*tp_itemsize*/
-  /* methods */
-  (destructor)PyStdOut_dealloc, /*tp_dealloc*/
-  0,                            /*tp_print*/
-  0,                            /*tp_getattr*/
-  0,                            /*tp_setattr*/
-  0,                            /*tp_compare*/
-  0,                            /*tp_repr*/
-  0,                            /*tp_as_number*/
-  0,                            /*tp_as_sequence*/
-  0,                            /*tp_as_mapping*/
-  0,                            /*tp_hash*/
-  0,                            /*tp_call*/
-  0,                            /*tp_str*/
-  PyObject_GenericGetAttr,      /*tp_getattro*/
-  /* softspace is writable:  we must supply tp_setattro */
-  PyObject_GenericSetAttr,      /* tp_setattro */
-  0,                            /*tp_as_buffer*/
-  Py_TPFLAGS_DEFAULT,           /*tp_flags*/
-  0,                            /*tp_doc*/
-  0,                            /*tp_traverse*/
-  0,                            /*tp_clear*/
-  0,                            /*tp_richcompare*/
-  0,                            /*tp_weaklistoffset*/
-  0,                            /*tp_iter*/
-  0,                            /*tp_iternext*/
-  PyStdOut_methods,             /*tp_methods*/
-  PyStdOut_memberlist,          /*tp_members*/
-  0,                            /*tp_getset*/
-  0,                            /*tp_base*/
-  0,                            /*tp_dict*/
-  0,                            /*tp_descr_get*/
-  0,                            /*tp_descr_set*/
-  0,                            /*tp_dictoffset*/
-  0,                            /*tp_init*/
-  0,                            /*tp_alloc*/
-  0,                            /*tp_new*/
-  0,                            /*tp_free*/
-  0,                            /*tp_is_gc*/
-};
-
-PyObject * newPyStdOut( std::string& out )
-{
-  PyStdOut *self;
-  self = PyObject_New(PyStdOut, &PyStdOut_Type);
-  if (self == NULL)
-    return NULL;
-  self->softspace = 0;
-  self->out=&out;
-  return (PyObject*)self;
+  static PyMethodDef PyStdOut_methods[] = {
+    {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
+      PyDoc_STR("write(string) -> None")},
+    {NULL,    NULL}   /* sentinel */
+  };
+
+  static PyMemberDef PyStdOut_memberlist[] = {
+    {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
+     (char*)"flag indicating that a space needs to be printed; used by print"},
+    {NULL} /* Sentinel */
+  };
+
+  static PyTypeObject PyStdOut_Type = {
+    /* The ob_type field must be initialized in the module init function
+     * to be portable to Windows without using C++. */
+    PyObject_HEAD_INIT(NULL)
+    0,                            /*ob_size*/
+    "PyOut",                      /*tp_name*/
+    sizeof(PyStdOut),             /*tp_basicsize*/
+    0,                            /*tp_itemsize*/
+    /* methods */
+    (destructor)PyStdOut_dealloc, /*tp_dealloc*/
+    0,                            /*tp_print*/
+    0,                            /*tp_getattr*/
+    0,                            /*tp_setattr*/
+    0,                            /*tp_compare*/
+    0,                            /*tp_repr*/
+    0,                            /*tp_as_number*/
+    0,                            /*tp_as_sequence*/
+    0,                            /*tp_as_mapping*/
+    0,                            /*tp_hash*/
+    0,                            /*tp_call*/
+    0,                            /*tp_str*/
+    PyObject_GenericGetAttr,      /*tp_getattro*/
+    /* softspace is writable:  we must supply tp_setattro */
+    PyObject_GenericSetAttr,      /* tp_setattro */
+    0,                            /*tp_as_buffer*/
+    Py_TPFLAGS_DEFAULT,           /*tp_flags*/
+    0,                            /*tp_doc*/
+    0,                            /*tp_traverse*/
+    0,                            /*tp_clear*/
+    0,                            /*tp_richcompare*/
+    0,                            /*tp_weaklistoffset*/
+    0,                            /*tp_iter*/
+    0,                            /*tp_iternext*/
+    PyStdOut_methods,             /*tp_methods*/
+    PyStdOut_memberlist,          /*tp_members*/
+    0,                            /*tp_getset*/
+    0,                            /*tp_base*/
+    0,                            /*tp_dict*/
+    0,                            /*tp_descr_get*/
+    0,                            /*tp_descr_set*/
+    0,                            /*tp_dictoffset*/
+    0,                            /*tp_init*/
+    0,                            /*tp_alloc*/
+    0,                            /*tp_new*/
+    0,                            /*tp_free*/
+    0,                            /*tp_is_gc*/
+  };
+
+  PyObject * newPyStdOut( std::string& out )
+  {
+    PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
+    if (self) {
+      self->softspace = 0;
+      self->out=&out;
+    }
+    return (PyObject*)self;
+  }
 }
 
 
 ////////////////////////END PYTHON///////////////////////////
 
 //////////////////MY MAPS////////////////////////////////////////
+namespace {
 TopTools_IndexedMapOfShape FacesWithSizeMap;
 std::map<int,string> FaceId2SizeMap;
 TopTools_IndexedMapOfShape EdgesWithSizeMap;
@@ -211,9 +216,11 @@ std::map<int,PyObject*> FaceId2PythonSmp;
 std::map<int,PyObject*> EdgeId2PythonSmp;
 std::map<int,PyObject*> VertexId2PythonSmp;
 
+typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
+TId2ClsAttractorVec FaceId2ClassAttractor;
+TId2ClsAttractorVec FaceIndex2ClassAttractor;
 std::map<int,std::vector<double> > FaceId2AttractorCoords;
-std::map<int,BLSURFPlugin_Attractor*> FaceId2ClassAttractor;
-std::map<int,BLSURFPlugin_Attractor*> FaceIndex2ClassAttractor;
+int theNbAttractors;
 
 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
@@ -224,7 +231,7 @@ bool HasSizeMapOnFace=false;
 bool HasSizeMapOnEdge=false;
 bool HasSizeMapOnVertex=false;
 //bool HasAttractorOnFace=false;
-
+}
 //=============================================================================
 /*!
  *
@@ -237,7 +244,7 @@ BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
 {
   MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
 
-  _name = "BLSURF";
+  _name = "MG-CADSurf";//"BLSURF";
   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
   _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
   _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
@@ -254,7 +261,7 @@ BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
 
   myStudy = NULL;
   myStudy = aStudyMgr->GetStudyByID(_studyId);
-  if (myStudy)
+  if ( !myStudy->_is_nil() )
     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
 
   /* Initialize the Python interpreter */
@@ -288,9 +295,7 @@ BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
   EnfVertexCoords2ProjVertex.clear();
   EnfVertexCoords2EnfVertexList.clear();
 
-#ifdef WITH_SMESH_CANCEL_COMPUTE
   _compute_canceled = false;
-#endif
 }
 
 //=============================================================================
@@ -330,7 +335,7 @@ bool BLSURFPlugin_BLSURF::CheckHypothesis
     return true;  // can work with no hypothesis
   }
 
-  for ( itl = hyps.begin(); itl != hyps.end(); ++itl )
+  for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
   {
     theHyp = *itl;
     string hypName = theHyp->GetName();
@@ -345,7 +350,11 @@ bool BLSURFPlugin_BLSURF::CheckHypothesis
     }
     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
     {
-      _haveViscousLayers = true;
+      if ( !_haveViscousLayers )
+      {
+        if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
+          _haveViscousLayers = true;
+      }
     }
     else
     {
@@ -357,18 +366,18 @@ bool BLSURFPlugin_BLSURF::CheckHypothesis
 
 //=============================================================================
 /*!
- * Pass parameters to BLSURF
+ * Pass parameters to MG-CADSurf
  */
 //=============================================================================
 
-inline std::string to_string(double d)
+inline std::string val_to_string(double d)
 {
    std::ostringstream o;
    o << d;
    return o.str();
 }
 
-inline std::string to_string_rel(double d)
+inline std::string val_to_string_rel(double d)
 {
    std::ostringstream o;
    o << d;
@@ -376,14 +385,14 @@ inline std::string to_string_rel(double d)
    return o.str();
 }
 
-inline std::string to_string(int i)
+inline std::string val_to_string(int i)
 {
    std::ostringstream o;
    o << i;
    return o.str();
 }
 
-inline std::string to_string_rel(int i)
+inline std::string val_to_string_rel(int i)
 {
    std::ostringstream o;
    o << i;
@@ -392,12 +401,6 @@ inline std::string to_string_rel(int i)
 }
 
 double _smp_phy_size;
-// #if BLSURF_VERSION_LONG >= "3.1.1"
-// //   sizemap_t *geo_sizemap_e, *geo_sizemap_f;
-//   sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
-// //   sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
-//   sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
-// #endif
 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
@@ -576,7 +579,7 @@ void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction
   double a, b;       // Attractor parameter
   double d = 0.;
   bool createNode=false; // To create a node on attractor projection
-  int pos1, pos2;
+  size_t pos1, pos2;
   const char *sep = ";";
   // atIt->second has the following pattern:
   // ATTRACTOR(xa;ya;za;a;b;True|False;d)
@@ -688,52 +691,183 @@ void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction
 //     MESSAGE("point OK");
 }
 
+// One sub-shape to get ids from
+BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
+    TopAbs_ShapeEnum theShapeType)
+{
+  BLSURFPlugin_BLSURF::TListOfIDs face_ids;
+  TopTools_IndexedMapOfShape anIndices;
+  anIndices.Clear();
+  TopExp::MapShapes(theMainShape, theShapeType, anIndices);
+
+//  Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
+
+  for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
+    {
+      int face_id = anIndices.FindIndex(face_iter.Current());
+      if (face_id == 0)
+        throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
+      face_ids.push_back(face_id);
+//      std::ostringstream o;
+//      o << "face_" << face_id << ".brep";
+//      std::string face_name = o.str();
+//      const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
+//      Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
+    }
+
+  return face_ids;
+}
+
+BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh*      theMesh,
+                                                           TopoDS_Shape     theSubShape,
+                                                           TopAbs_ShapeEnum theShapeType)
+{
+  BLSURFPlugin_BLSURF::TListOfIDs face_ids;
+
+  for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
+  {
+    int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
+    if (face_id == 0)
+      throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
+    face_ids.push_back(face_id);
+  }
+
+  return face_ids;
+}
+
+void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
+{
+  for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
+    {
+      BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
+      MESSAGE("Vertex entry " << theVertexEntry);
+      addCoordsFromVertex(theVertexEntry, theVerticesCoords);
+    }
+}
+
+
+void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
+{
+  if (theVertexEntry!="")
+    {
+      TopoDS_Shape aShape = entryToShape(theVertexEntry);
+
+      gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
+      double theX, theY, theZ;
+      theX = aPnt.X();
+      theY = aPnt.Y();
+      theZ = aPnt.Z();
+
+      theVerticesCoords.push_back(theX);
+      theVerticesCoords.push_back(theY);
+      theVerticesCoords.push_back(theZ);
+    }
+}
+
+/////////////////////////////////////////////////////////
+void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
+{
+  MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity");
+
+  TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
+  TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
+
+  TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
+  TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
+
+  TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
+  preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
+  preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
+
+  MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
+  MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
+
+  addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
+  addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
+
+  MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
+  MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
+
+  _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
+  MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
+  MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity END");
+
+}
+
+/////////////////////////////////////////////////////////
+void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
+{
+  MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity");
+
+  TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
+  TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
+
+  TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
+  TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
+
+  TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
+  preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
+  preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
+
+  addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
+  addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
+
+  _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
+  MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
+  MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity END");
+
+}
+
+
 /////////////////////////////////////////////////////////
 
-void BLSURFPlugin_BLSURF::SetParameters(
-// #if BLSURF_VERSION_LONG >= "3.1.1"
-//                                         cad_t *                          c,
-// #endif
-                                        const BLSURFPlugin_Hypothesis* hyp,
+void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
                                         cadsurf_session_t *            css,
-                                        precad_session_t *             pcs,
-                                        const TopoDS_Shape&            GeomShape,
-                                        bool *                  use_precad
-                                       )
+                                        const TopoDS_Shape&            theGeomShape
+                                        )
 {
   // rnc : Bug 1457
   // Clear map so that it is not stored in the algorithm with old enforced vertices in it
   EnfVertexCoords2EnfVertexList.clear();
-  
-   double diagonal               = SMESH_Mesh::GetShapeDiagonalSize( GeomShape );
-   double bbSegmentation         = _gen->GetBoundaryBoxSegmentation();
-   int    _physicalMesh          = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
-   int    _geometricMesh         = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
-   double _phySize               = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
-   bool   _phySizeRel            = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
-   double _minSize               = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
-   bool   _minSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
-   double _maxSize               = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
-   bool   _maxSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
-   double _gradation             = BLSURFPlugin_Hypothesis::GetDefaultGradation();
-   bool   _quadAllowed           = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
-   double _angleMesh             = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
-   double _chordalError          = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
-   bool   _anisotropic           = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
-   double _anisotropicRatio      = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
-   bool   _removeTinyEdges       = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
-   double _tinyEdgeLength        = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
-   bool   _badElementRemoval     = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
-   double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
-   bool   _optimizeMesh          = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
-   bool   _quadraticMesh         = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
-   int    _verb                  = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
-   int    _topology              = BLSURFPlugin_Hypothesis::GetDefaultTopology();
+
+  double diagonal               = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
+  double bbSegmentation         = _gen->GetBoundaryBoxSegmentation();
+  int    _physicalMesh          = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
+  int    _geometricMesh         = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
+  double _phySize               = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
+  bool   _phySizeRel            = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
+  double _minSize               = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
+  bool   _minSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
+  double _maxSize               = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
+  bool   _maxSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
+  double _use_gradation         = BLSURFPlugin_Hypothesis::GetDefaultUseGradation();
+  double _gradation             = BLSURFPlugin_Hypothesis::GetDefaultGradation();
+  double _use_volume_gradation  = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeGradation();
+  double _volume_gradation      = BLSURFPlugin_Hypothesis::GetDefaultVolumeGradation();
+  bool   _quadAllowed           = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
+  double _angleMesh             = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
+  double _chordalError          = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
+  bool   _anisotropic           = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
+  double _anisotropicRatio      = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
+  bool   _removeTinyEdges       = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
+  double _tinyEdgeLength        = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
+  bool   _optimiseTinyEdges     = BLSURFPlugin_Hypothesis::GetDefaultOptimiseTinyEdges();
+  double _tinyEdgeOptimisLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeOptimisationLength(diagonal);
+  bool   _correctSurfaceIntersec= BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersection();
+  double _corrSurfaceIntersCost = BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersectionMaxCost();
+  bool   _badElementRemoval     = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
+  double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
+  bool   _optimizeMesh          = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
+  bool   _quadraticMesh         = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
+  int    _verb                  = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
+  //int    _topology              = BLSURFPlugin_Hypothesis::GetDefaultTopology();
 
   // PreCAD
-   int _precadMergeEdges         = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
-   int _precadProcess3DTopology  = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
-   int _precadDiscardInput       = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
+  //int _precadMergeEdges         = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
+  int _precadRemoveTinyUVEdges  = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveTinyUVEdges();
+  //int _precadRemoveDuplicateCADFaces = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveDuplicateCADFaces();
+  int _precadProcess3DTopology  = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
+  //int _precadDiscardInput       = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
 
 
   if (hyp) {
@@ -755,79 +889,84 @@ void BLSURFPlugin_BLSURF::SetParameters(
       // if max size is not explicitly specified, "relative" flag is ignored
       _maxSizeRel    = hyp->IsMaxSizeRel();
     }
-    if (hyp->GetGradation() > 0)
+    _use_gradation = hyp->GetUseGradation();
+    if (hyp->GetGradation() > 0 && _use_gradation)
       _gradation     = hyp->GetGradation();
-    _quadAllowed   = hyp->GetQuadAllowed();
-     if (hyp->GetAngleMesh() > 0)
-     _angleMesh     = hyp->GetAngleMesh();
-     if (hyp->GetChordalError() > 0)
-       _chordalError           = hyp->GetChordalError();
-     _anisotropic            = hyp->GetAnisotropic();
-     if (hyp->GetAnisotropicRatio() >= 0)
-       _anisotropicRatio       = hyp->GetAnisotropicRatio();
-     _removeTinyEdges        = hyp->GetRemoveTinyEdges();
-     if (hyp->GetTinyEdgeLength() > 0)
-       _tinyEdgeLength         = hyp->GetTinyEdgeLength();
-     _badElementRemoval      = hyp->GetBadElementRemoval();
-     if (hyp->GetBadElementAspectRatio() >= 0)
-       _badElementAspectRatio  = hyp->GetBadElementAspectRatio();
-     _optimizeMesh  = hyp->GetOptimizeMesh();
-     _quadraticMesh = hyp->GetQuadraticMesh();
+    _use_volume_gradation    = hyp->GetUseVolumeGradation();
+    if (hyp->GetVolumeGradation() > 0 && _use_volume_gradation )
+      _volume_gradation      = hyp->GetVolumeGradation();
+    _quadAllowed     = hyp->GetQuadAllowed();
+    if (hyp->GetAngleMesh() > 0)
+      _angleMesh     = hyp->GetAngleMesh();
+    if (hyp->GetChordalError() > 0)
+      _chordalError          = hyp->GetChordalError();
+    _anisotropic             = hyp->GetAnisotropic();
+    if (hyp->GetAnisotropicRatio() >= 0)
+      _anisotropicRatio      = hyp->GetAnisotropicRatio();
+    _removeTinyEdges         = hyp->GetRemoveTinyEdges();
+    if (hyp->GetTinyEdgeLength() > 0)
+      _tinyEdgeLength        = hyp->GetTinyEdgeLength();
+    _optimiseTinyEdges       = hyp->GetOptimiseTinyEdges();
+    if (hyp->GetTinyEdgeOptimisationLength() > 0)
+      _tinyEdgeOptimisLength = hyp->GetTinyEdgeOptimisationLength();
+    _correctSurfaceIntersec  = hyp->GetCorrectSurfaceIntersection();
+    if (hyp->GetCorrectSurfaceIntersectionMaxCost() > 0)
+      _corrSurfaceIntersCost = hyp->GetCorrectSurfaceIntersectionMaxCost();
+    _badElementRemoval       = hyp->GetBadElementRemoval();
+    if (hyp->GetBadElementAspectRatio() >= 0)
+      _badElementAspectRatio = hyp->GetBadElementAspectRatio();
+    _optimizeMesh  = hyp->GetOptimizeMesh();
+    _quadraticMesh = hyp->GetQuadraticMesh();
     _verb          = hyp->GetVerbosity();
-     _topology      = (int) hyp->GetTopology();
-     // PreCAD
-     _precadMergeEdges = hyp->GetPreCADMergeEdges();
-     _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
-     _precadDiscardInput = hyp->GetPreCADDiscardInput();
-
-    const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
+    //_topology      = (int) hyp->GetTopology();
+    // PreCAD
+    //_precadMergeEdges        = hyp->GetPreCADMergeEdges();
+    _precadRemoveTinyUVEdges = hyp->GetPreCADRemoveTinyUVEdges();
+    //_precadRemoveDuplicateCADFaces = hyp->GetPreCADRemoveDuplicateCADFaces();
+    _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
+    //_precadDiscardInput      = hyp->GetPreCADDiscardInput();
+
+    const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
       if ( !opIt->second.empty() ) {
         MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
         set_param(css, opIt->first.c_str(), opIt->second.c_str());
       }
-      
-    const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
+
+    const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
+    for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
+      if ( !opIt->second.empty() ) {
+        MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
+        set_param(css, opIt->first.c_str(), opIt->second.c_str());
+     }
+
+    const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
     for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
       if ( !opIt->second.empty() ) {
-        if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
-          MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
-          precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
-        }
+        MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
+        set_param(css, opIt->first.c_str(), opIt->second.c_str());
       }
   }
-//   else {
-//     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
-//     // GetDefaultPhySize() sometimes leads to computation failure
-//     // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
-//     _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
-//     _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
-//     _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
-//     _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
-//     _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
-//     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
-//   }
 
-  // PreCAD
-  if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
-    *use_precad = true;
-    precad_set_param(pcs, "verbose",                to_string(_verb).c_str());
-    precad_set_param(pcs, "merge_edges",            _precadMergeEdges ? "1" : "0");
-    precad_set_param(pcs, "process_3d_topology",    _precadProcess3DTopology ? "1" : "0");
-    precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
-  }
+  // PreProcessor (formerly PreCAD) -- commented params are preCADoptions (since 0023307)
+  //set_param(css, "merge_edges",            _precadMergeEdges ? "yes" : "no");
+  set_param(css, "remove_tiny_uv_edges",   _precadRemoveTinyUVEdges ? "yes" : "no");
+  //set_param(css, "remove_duplicate_cad_faces", _precadRemoveDuplicateCADFaces ? "yes" : "no");
+  set_param(css, "process_3d_topology",    _precadProcess3DTopology ? "1" : "0");
+  //set_param(css, "discard_input_topology", _precadDiscardInput ? "1" : "0");
+  //set_param(css, "max_number_of_points_per_patch", "1000000");
   
    bool useGradation = false;
    switch (_physicalMesh)
    {
      case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
        set_param(css, "physical_size_mode", "global");
-       set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
+       set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
        break;
      case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
        set_param(css, "physical_size_mode", "local");
-       set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
+       set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
        useGradation = true;
        break;
      default:
@@ -838,14 +977,14 @@ void BLSURFPlugin_BLSURF::SetParameters(
    {
      case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
        set_param(css, "geometric_size_mode", "global");
-       set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
-       set_param(css, "chordal_error", to_string(_chordalError).c_str());
+       set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
+       set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
        useGradation = true;
        break;
      case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
        set_param(css, "geometric_size_mode", "local");
-       set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
-       set_param(css, "chordal_error", to_string(_chordalError).c_str());
+       set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
+       set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
        useGradation = true;
        break;
      default:
@@ -859,42 +998,52 @@ void BLSURFPlugin_BLSURF::SetParameters(
      double mins = _minSizeRel ? _minSize * diagonal : _minSize;
      // - min size should not be greater than user size
      if ( _phySize < mins )
-       set_param(css, "min_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
+       set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
      else
-       set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
+       set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
      // - compute absolute max size
      double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
      // - max size should not be less than user size
      if ( _phySize > maxs )
-       set_param(css, "max_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
+       set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
      else
-       set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
+       set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
    }
    else {
      // user size is not explicitly specified
      // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
-     set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
+     set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
      // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
-     set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
+     set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
    }
-  
-  if ( useGradation )
-     set_param(css, "gradation",                         to_string(_gradation).c_str());
+   // anisotropic and quadrangle mesh requires disabling gradation
+   if ( _anisotropic && _quadAllowed )
+     useGradation = false; // limitation of V1.3
+   if ( useGradation && _use_gradation )
+     set_param(css, "gradation",                       val_to_string(_gradation).c_str());
+   if ( useGradation && _use_volume_gradation )
+     set_param(css, "volume_gradation",                val_to_string(_volume_gradation).c_str());
    set_param(css, "element_generation",                _quadAllowed ? "quad_dominant" : "triangle");
 
 
    set_param(css, "metric",                            _anisotropic ? "anisotropic" : "isotropic");
    if ( _anisotropic )
-     set_param(css, "anisotropic_ratio",                 to_string(_anisotropicRatio).c_str());
+     set_param(css, "anisotropic_ratio",                 val_to_string(_anisotropicRatio).c_str());
    set_param(css, "remove_tiny_edges",                 _removeTinyEdges ? "1" : "0");
    if ( _removeTinyEdges )
-     set_param(css, "tiny_edge_length",                  to_string(_tinyEdgeLength).c_str());
+     set_param(css, "tiny_edge_length",                  val_to_string(_tinyEdgeLength).c_str());
+   set_param(css, "optimise_tiny_edges",               _optimiseTinyEdges ? "1" : "0");
+   if ( _optimiseTinyEdges )
+     set_param(css, "tiny_edge_optimisation_length",   val_to_string(_tinyEdgeOptimisLength).c_str());
+   set_param(css, "correct_surface_intersections",     _correctSurfaceIntersec ? "1" : "0");
+   if ( _correctSurfaceIntersec )
+     set_param(css, "surface_intersections_processing_max_cost", val_to_string(_corrSurfaceIntersCost ).c_str());
    set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
    if ( _badElementRemoval )
-     set_param(css, "bad_surface_element_aspect_ratio",  to_string(_badElementAspectRatio).c_str());
+     set_param(css, "bad_surface_element_aspect_ratio",  val_to_string(_badElementAspectRatio).c_str());
    set_param(css, "optimisation",                      _optimizeMesh ? "yes" : "no");
    set_param(css, "element_order",                     _quadraticMesh ? "quadratic" : "linear");
-   set_param(css, "verbose",                           to_string(_verb).c_str());
+   set_param(css, "verbose",                           val_to_string(_verb).c_str());
 
    _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
    if ( _verb > 0 )
@@ -918,7 +1067,7 @@ void BLSURFPlugin_BLSURF::SetParameters(
         MESSAGE("Geomtype is " << GeomType);
         int key = -1;
         // Group Management
-        if (GeomType == TopAbs_COMPOUND){
+        if (GeomType == TopAbs_COMPOUND) {
           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
             // Group of faces
             if (it.Value().ShapeType() == TopAbs_FACE){
@@ -1062,6 +1211,7 @@ void BLSURFPlugin_BLSURF::SetParameters(
     //  - build the map here for each face with an attractor set and only if the attractor shape as changed since the last call to _buildmap()
     //  -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap()  OK
 
+      theNbAttractors = 0;
     const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
     int key=-1;
     BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
@@ -1069,6 +1219,8 @@ void BLSURFPlugin_BLSURF::SetParameters(
       if ( !AtIt->second->Empty() ) {
        // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
         GeomShape = entryToShape(AtIt->first);
+        if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
+          continue;
         AttShape = AtIt->second->GetAttractorShape();
         GeomType  = GeomShape.ShapeType();
         // Group Management
@@ -1088,15 +1240,10 @@ void BLSURFPlugin_BLSURF::SetParameters(
            || AttShape.ShapeType() == TopAbs_COMPOUND) ){
             HasSizeMapOnFace = true;
 
-            if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape)) ) {
-                key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
-            }
-            else {
-              key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
-//                 MESSAGE("Face with key " << key << " already in map");
-            }
+            key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
 
-            FaceId2ClassAttractor[key] = AtIt->second;
+            FaceId2ClassAttractor[key].push_back( AtIt->second );
+            ++theNbAttractors;
         }
         else{
           MESSAGE("Wrong shape type !!")
@@ -1139,7 +1286,7 @@ void BLSURFPlugin_BLSURF::SetParameters(
       std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
       MESSAGE("Setting Internal Enforced Vertices");
       gp_Pnt aPnt;
-      TopExp_Explorer exp (GeomShape, TopAbs_FACE);
+      TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
       for (; exp.More(); exp.Next()){
         MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
         TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
@@ -1166,38 +1313,42 @@ void BLSURFPlugin_BLSURF::SetParameters(
     }
 
     MESSAGE("Setting Size Map on FACES ");
-// #if BLSURF_VERSION_LONG < "3.1.1"
-    cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
-// #else
-//     if (*use_precad)
-//       iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
-//     else
-//       clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
-// #endif
+    cadsurf_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
 
     if (HasSizeMapOnEdge){
       MESSAGE("Setting Size Map on EDGES ");
-// #if BLSURF_VERSION_LONG < "3.1.1"
-      cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
-// #else
-//       if (*use_precad)
-//         iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
-//       else
-//         clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
-// #endif
+      cadsurf_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
     }
     if (HasSizeMapOnVertex){
       MESSAGE("Setting Size Map on VERTICES ");
-// #if BLSURF_VERSION_LONG < "3.1.1"
-      cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
-// #else
-//       if (*use_precad)
-//         iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
-//       else
-//         clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
-// #endif
+      cadsurf_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
     }
   }
+
+  // PERIODICITY
+
+   // reset vectors
+   _preCadFacesIDsPeriodicityVector.clear();
+   _preCadEdgesIDsPeriodicityVector.clear();
+
+  MESSAGE("SetParameters preCadFacesPeriodicityVector");
+  const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
+
+  for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
+    MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
+    createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
+  }
+  MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
+
+  MESSAGE("SetParameters preCadEdgesPeriodicityVector");
+  const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
+
+  for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
+    MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
+    createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
+  }
+  MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
+
 }
 
 //================================================================================
@@ -1231,7 +1382,7 @@ namespace
 {
   // --------------------------------------------------------------------------
   /*!
-   * \brief Class correctly terminating usage of BLSURF library at destruction
+   * \brief Class correctly terminating usage of MG-CADSurf library at destruction
    */
   class BLSURF_Cleaner
   {
@@ -1300,13 +1451,15 @@ namespace
   {
     // sort nodes by position in the following order:
     // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
-    int operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
+    bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
     {
-      SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
-      SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
-      if ( pos1 == pos2 ) return 0;
-      if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
-      return -1;
+      // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
+      return n1->getIdInShape() < n2->getIdInShape();
+      // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
+      // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
+      // if ( pos1 == pos2 ) return 0;
+      // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
+      // return -1;
     }
     // sort sub-meshes in order: EDGE, VERTEX
     bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
@@ -1321,7 +1474,7 @@ namespace
 
   //================================================================================
   /*!
-   * \brief Fills groups on nodes to be merged
+   * \brief Fills groups of nodes to be merged
    */
   //================================================================================
 
@@ -1351,7 +1504,11 @@ namespace
       }
       if ( u2node.size() < 2 ) return;
 
-      double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
+      //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
+      Standard_Real f,l;
+      BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
+      double tol = (( l - f ) / 20.) / u2node.size();
+
       std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
       for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
       {
@@ -1368,7 +1525,7 @@ namespace
             }
           }
           // make nodes created on the boundary of viscous layer replace nodes created
-          // by BLSURF as their SMDS_Position is more correct
+          // by MG-CADSurf as their SMDS_Position is more correct
           nodes.sort( ShapeTypeCompare() );
           nodeGroupsToMerge.push_back( nodes );
         }
@@ -1439,13 +1596,14 @@ namespace
           continue;
 
         BRepBuilderAPI_MakePolygon wire;
-        for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
+        const size_t i0 = tmpVertex.size();
+        for ( size_t iN = 0; iN < wirePoints.size(); ++iN )
         {
           wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
           origNodes.push_back( wirePoints[ iN ].node );
           tmpVertex.push_back( wire.LastVertex() );
         }
-        tmpVertex[0] = wire.FirstVertex();
+        tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
         wire.Close();
         if ( !wire.IsDone() )
           throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
@@ -1466,7 +1624,7 @@ namespace
       //_proxyFace = TopoDS::Face( fExp.Current() );
 
 
-      // Make input mesh for BLSURF: segments on EDGE's of newFace
+      // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
 
       // make nodes and fill in _tmp2origNN
       //
@@ -1498,7 +1656,7 @@ namespace
 
     //--------------------------------------------------------------------------------
     /*!
-     * \brief Fill in the origMesh with faces computed by BLSURF in this tmp mesh
+     * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
      */
     //--------------------------------------------------------------------------------
 
@@ -1509,6 +1667,9 @@ namespace
       helper.SetSubShape( origFace );
       helper.SetElementsOnShape( true );
 
+      SMESH_MesherHelper tmpHelper( *this );
+      tmpHelper.SetSubShape( _proxyFace );
+
       // iterate over tmp faces and copy them in origMesh
       const SMDS_MeshNode* nodes[27];
       const SMDS_MeshNode* nullNode = 0;
@@ -1522,19 +1683,19 @@ namespace
         for ( ; nIt->more(); ++nbN )
         {
           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
-          TN2NMap::iterator n2nIt = 
+          TN2NMap::iterator n2nIt =
             _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
           if ( !n2nIt->second ) {
             n->GetXYZ( xyz );
-            gp_XY uv = helper.GetNodeUV( _proxyFace, n );
+            gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
             n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
           }
           nodes[ nbN ] = n2nIt->second;
         }
         switch( nbN ) {
         case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
-        // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
-        //                         nodes[3], nodes[4], nodes[5]); break;
+          // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
+          //                         nodes[3], nodes[4], nodes[5]); break;
         case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
         // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
         //                         nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
@@ -1552,9 +1713,9 @@ namespace
   {
     std::string * _error;
     int           _verbosity;
+    double *      _progress;
   };
 
-
 } // namespace
 
 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
@@ -1576,10 +1737,17 @@ bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
   // Fix problem with locales
   Kernel_Utils::Localizer aLocalizer;
 
-  if ( !compute( aMesh, aShape ))
-    return false;
+  this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
+
+  bool viscousLayersMade =
+    ( aShape.ShapeType() == TopAbs_FACE &&
+      StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( aShape ), aMesh ));
+
+  if ( !viscousLayersMade )
+    if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
+      return false;
 
-  if ( _haveViscousLayers )
+  if ( _haveViscousLayers || viscousLayersMade )
   {
     // Compute viscous layers
 
@@ -1592,19 +1760,19 @@ bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
       if ( !viscousMesh )
         return false; // error in StdMeshers_ViscousLayers2D::Compute()
 
-      // Compute BLSURF mesh on viscous layers
+      // Compute MG-CADSurf mesh on viscous layers
 
       if ( viscousMesh->NbProxySubMeshes() > 0 )
       {
         TmpMesh tmpMesh;
         const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
-        if ( !compute( tmpMesh, proxyFace ))
+        if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
           return false;
         tmpMesh.FillInOrigMesh( aMesh, F );
       }
     }
 
-    // Re-compute BLSURF mesh on the rest faces if the mesh was cleared
+    // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
 
     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
     {
@@ -1612,7 +1780,7 @@ bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
       SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
       if ( fSM->IsMeshComputed() ) continue;
 
-      if ( !compute( aMesh, aShape ))
+      if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
         return false;
       break;
     }
@@ -1627,11 +1795,13 @@ bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
 //=============================================================================
 
 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
-                                  const TopoDS_Shape& aShape)
+                                  const TopoDS_Shape& aShape,
+                                  bool                allowSubMeshClearing)
 {
   /* create a distene context (generic object) */
   status_t status = STATUS_ERROR;
 
+  myMesh = &aMesh;
   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
   SMESH_MesherHelper helper( aMesh );
   // do not call helper.IsQuadraticSubMesh() because sub-meshes
@@ -1643,12 +1813,10 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   TSubMeshSet edgeSubmeshes;
   TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
 
-  TopTools_IndexedMapOfShape fmap;
-  TopTools_IndexedMapOfShape emap;
-  TopTools_IndexedMapOfShape pmap;
+  TopTools_IndexedMapOfShape pmap, emap, fmap;
 
   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
-#ifndef WNT
+#ifndef WIN32
   feclearexcept( FE_ALL_EXCEPT );
   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
 #endif
@@ -1658,6 +1826,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   /* Set the message callback in the working context */
   message_cb_user_data mcud;
   mcud._error     = & this->SMESH_Algo::_comment;
+  mcud._progress  = & this->SMESH_Algo::_progress;
   mcud._verbosity =
     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
   context_set_message_callback(ctx, message_cb, &mcud);
@@ -1685,10 +1854,6 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
    */
 
   // PreCAD
-  // If user requests it, send the CAD through Distene preprocessor : PreCAD
-  cad_t *cleanc = NULL; // preprocessed cad
-  precad_session_t *pcs = precad_session_new(ctx);
-  precad_data_set_cad(pcs, c);
 
   cadsurf_session_t *css = cadsurf_session_new(ctx);
 
@@ -1696,14 +1861,11 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   BLSURF_Cleaner cleaner( ctx,css,c,dcad );
 
   MESSAGE("BEGIN SetParameters");
-  bool use_precad = false;
-  SetParameters(
-                // #if BLSURF_VERSION_LONG >= "3.1.1"
-                //     c,
-                // #endif
-                _hypothesis, css, pcs, aShape, &use_precad);
+  SetParameters(_hypothesis, css, aShape);
   MESSAGE("END SetParameters");
 
+  MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
+
   haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
   helper.SetIsQuadratic( haveQuadraticSubMesh );
 
@@ -1721,7 +1883,6 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   vector<Handle(Geom2d_Curve)> curves;
   vector<Handle(Geom_Surface)> surfaces;
 
-  fmap.Clear();
   emap.Clear();
   pmap.Clear();
   FaceId2PythonSmp.clear();
@@ -1740,7 +1901,6 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
 
   assert(Py_IsInitialized());
   PyGILState_STATE gstate;
-  gstate = PyGILState_Ensure();
 
   string theSizeMapStr;
 
@@ -1748,13 +1908,18 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   {
     TopoDS_Face f = TopoDS::Face(face_iter.Current());
 
+    SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
+    if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
+
     // make INTERNAL face oriented FORWARD (issue 0020993)
     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
       f.Orientation(TopAbs_FORWARD);
 
-    if (fmap.FindIndex(f) > 0)
-      continue;
     iface = fmap.Add(f);
+//    std::string aFileName = "fmap_face_";
+//    aFileName.append(val_to_string(iface));
+//    aFileName.append(".brep");
+//    BRepTools::Write(f,aFileName.c_str());
 
     surfaces.push_back(BRep_Tool::Surface(f));
 
@@ -1764,11 +1929,16 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
      * (For this face, it will be called by cadsurf with your_face_object_ptr
      * as last parameter.
      */
+#if OCC_VERSION_MAJOR < 7
     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
+#else
+    cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back().get());
+#endif
 
     /* by default a face has no tag (color).
-       The following call sets it to the same value as the face_id : */
-    cad_face_set_tag(fce, iface);
+       The following call sets it to the same value as the Geom module ID : */
+    const int faceTag = meshDS->ShapeToIndex(f);
+    cad_face_set_tag(fce, faceTag);
 
     /* Set face orientation (optional if you want a well oriented output mesh)*/
     if(f.Orientation() != TopAbs_FORWARD)
@@ -1776,7 +1946,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     else
       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
 
-    if (HasSizeMapOnFace && !use_precad)
+    if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
     {
       // -----------------
       // Classic size map
@@ -1785,12 +1955,13 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
 
 
       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
-        MESSAGE("A size map is defined on face :"<<faceKey)
-          theSizeMapStr = FaceId2SizeMap[faceKey];
+        MESSAGE("A size map is defined on face :"<<faceKey);
+        theSizeMapStr = FaceId2SizeMap[faceKey];
         // check if function ends with "return"
         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
           continue;
         // Expr To Python function, verification is performed at validation in GUI
+        gstate = PyGILState_Ensure();
         PyObject * obj = NULL;
         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
         Py_DECREF(obj);
@@ -1798,6 +1969,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
         func = PyObject_GetAttrString(main_mod, "f");
         FaceId2PythonSmp[iface]=func;
         FaceId2SizeMap.erase(faceKey);
+        PyGILState_Release(gstate);
       }
 
       // Specific size map = Attractor
@@ -1844,11 +2016,17 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       // -----------------
       // Class Attractors
       // -----------------
-      std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
+      TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
       if (clAttractor_iter != FaceId2ClassAttractor.end()){
         MESSAGE("Face indice: " << iface);
         MESSAGE("Adding attractor");
-        FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
+        std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
+        for ( size_t i = 0; i < attVec.size(); ++i )
+          if ( !attVec[i]->IsMapBuilt() ) {
+            std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
+            attVec[i]->BuildMap();
+          }
+        FaceIndex2ClassAttractor[iface].swap( attVec );
         FaceId2ClassAttractor.erase(clAttractor_iter);
       }
     } // if (HasSizeMapOnFace && !use_precad)
@@ -1884,21 +2062,22 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
           MESSAGE("Point is out of face: node is not created");
           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
             EnfVertexCoords2ProjVertex.erase(xyzCoords);
-            EnfVertexCoords2EnfVertexList.erase(xyzCoords);
+            // isssue 22783. Do not erase as this point can be IN other face of a group
+            //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
           }
         }
         if ( result == TopAbs_UNKNOWN ) {
           MESSAGE("Point position on face is unknown: node is not created");
           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
             EnfVertexCoords2ProjVertex.erase(xyzCoords);
-            EnfVertexCoords2EnfVertexList.erase(xyzCoords);
+            //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
           }
         }
         if ( result == TopAbs_ON ) {
           MESSAGE("Point is on border of face: node is not created");
           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
             EnfVertexCoords2ProjVertex.erase(xyzCoords);
-            EnfVertexCoords2EnfVertexList.erase(xyzCoords);
+            //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
           }
         }
         if ( result == TopAbs_IN )
@@ -1922,8 +2101,8 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
               SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
               vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
               mergeSubmeshes.insert( vSM->GetSubMeshDS() );
-              //if ( tag != pmap.Extent() )
-              needMerge = true;
+              // //if ( tag != pmap.Extent() )
+              // needMerge = true;
             }
           }
           if ( tag == 0 ) tag = ienf;
@@ -1946,6 +2125,11 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       if (ic <= 0)
         ic = emap.Add(e);
 
+//      std::string aFileName = "fmap_edge_";
+//      aFileName.append(val_to_string(ic));
+//      aFileName.append(".brep");
+//      BRepTools::Write(e,aFileName.c_str());
+
       double tmin,tmax;
       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
 
@@ -1957,6 +2141,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
             continue;
           // Expr To Python function, verification is performed at validation in GUI
+          gstate = PyGILState_Ensure();
           PyObject * obj = NULL;
           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
           Py_DECREF(obj);
@@ -1964,6 +2149,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
           func = PyObject_GetAttrString(main_mod, "f");
           EdgeId2PythonSmp[ic]=func;
           EdgeId2SizeMap.erase(edgeKey);
+          PyGILState_Release(gstate);
         }
       }
       /* data of nodes existing on the edge */
@@ -1971,10 +2157,11 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       SMESH_subMesh* sm = aMesh.GetSubMesh( e );
       if ( !sm->IsEmpty() )
       {
-        SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
-                                                                     /*complexFirst=*/false);
-        while ( subsmIt->more() )
-          edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
+        // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
+        //                                                              /*complexFirst=*/false);
+        // while ( subsmIt->more() )
+        //   edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
+        edgeSubmeshes.insert( sm->GetSubMeshDS() );
 
         nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
                                                  /*ignoreMedium=*/haveQuadraticSubMesh));
@@ -2001,7 +2188,11 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       }
 
       /* attach the edge to the current cadsurf face */
+#if OCC_VERSION_MAJOR < 7
       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
+#else
+      cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back().get());
+#endif
 
       /* by default an edge has no tag (color).
          The following call sets it to the same value as the edge_id : */
@@ -2016,7 +2207,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       if (e.Orientation() == TopAbs_INTERNAL)
         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
 
-      // pass existing nodes of sub-meshes to BLSURF
+      // pass existing nodes of sub-meshes to MG-CADSurf
       if ( nodeData )
       {
         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
@@ -2067,10 +2258,16 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
         *ip = pmap.FindIndex(v);
         if(*ip <= 0) {
           *ip = pmap.Add(v);
-          SMESH_subMesh* sm = aMesh.GetSubMesh(v);
-          if ( sm->IsMeshComputed() )
-            edgeSubmeshes.insert( sm->GetSubMeshDS() );
+          // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
+          // if ( sm->IsMeshComputed() )
+          //   edgeSubmeshes.insert( sm->GetSubMeshDS() );
         }
+
+//        std::string aFileName = "fmap_vertex_";
+//        aFileName.append(val_to_string(*ip));
+//        aFileName.append(".brep");
+//        BRepTools::Write(v,aFileName.c_str());
+
         if (HasSizeMapOnVertex){
           vertexKey = VerticesWithSizeMap.FindIndex(v);
           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
@@ -2079,6 +2276,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
               continue;
             // Expr To Python function, verification is performed at validation in GUI
+            gstate = PyGILState_Ensure();
             PyObject * obj = NULL;
             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
             Py_DECREF(obj);
@@ -2086,6 +2284,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
             func = PyObject_GetAttrString(main_mod, "f");
             VertexId2PythonSmp[*ip]=func;
             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
+            PyGILState_Release(gstate);
           }
         }
       }
@@ -2120,7 +2319,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
       const SMDS_MeshNode* n = nIt->next();
       if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
       {
-        needMerge = true;
+        needMerge = true; // to correctly sew with viscous mesh
         // add existing medium nodes to helper
         if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
         {
@@ -2131,61 +2330,141 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
         continue;
       }
     }
+    if ( allowSubMeshClearing )
     {
       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
-      while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), smDS );
+      while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
-      while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), smDS );
+      while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
+      smDS->Clear();
+    }
+    else
+    {
+      needMerge = true;
     }
   }
 
-
-  if (use_precad) {
-    /* Now launch the PreCAD process */
-    status = precad_process(pcs);
-    if(status != STATUS_OK){
-      cout << "PreCAD processing failed with error code " << status << "\n";
+  ///////////////////////
+  // PERIODICITY       //
+  ///////////////////////
+
+  MESSAGE("BEFORE PERIODICITY");
+  MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
+  if (! _preCadFacesIDsPeriodicityVector.empty()) {
+    MESSAGE("INTO PRECAD FACES PERIODICITY");
+    for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
+      std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
+      std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
+      int* theFace1_ids_c = &theFace1_ids[0];
+      int* theFace2_ids_c = &theFace2_ids[0];
+      std::ostringstream o;
+      o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
+      for (std::size_t j=0; j < theFace1_ids.size(); j++)
+        o << theFace1_ids[j] << ", ";
+      o << "], [";
+      for (std::size_t j=0; j < theFace2_ids.size(); j++)
+        o << theFace2_ids[j] << ", ";
+      o << "]";
+      MESSAGE(o.str());
+      MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
+      MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
+      if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
+        {
+          // If no source points, call peridoicity without transformation function
+          MESSAGE("periodicity without transformation function");
+          meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
+          status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
+              theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
+          if(status != STATUS_OK)
+            cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
+        }
+      else
+        {
+          // get the transformation vertices
+          MESSAGE("periodicity with transformation vertices");
+          double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
+          double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
+          int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
+          int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
+
+          MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
+
+          status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
+              theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
+          if(status != STATUS_OK)
+            cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
+        }
     }
-    else {
-      // retrieve the pre-processed CAD object
-      cleanc = precad_new_cad(pcs);
-      if(!cleanc){
-        cout << "Unable to retrieve PreCAD result \n";
-      }
-      cout << "PreCAD processing successfull \n";
-
-      // #if BLSURF_VERSION_LONG >= "3.1.1"
-      //       /* We can now get the updated sizemaps (if any) */
-      // //       if(geo_sizemap_e)
-      // //         clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
-      // // 
-      // //       if(geo_sizemap_f)
-      // //         clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
-      //
-      //       if(iso_sizemap_p)
-      //         clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
-      //
-      //       if(iso_sizemap_e)
-      //         clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
-      //
-      //       if(iso_sizemap_f)
-      //         clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
-      // #endif
+
+    MESSAGE("END PRECAD FACES PERIODICITY");
+  }
+
+  MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
+  if (! _preCadEdgesIDsPeriodicityVector.empty()) {
+    MESSAGE("INTO PRECAD EDGES PERIODICITY");
+    for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
+      std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
+      std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
+      // Use the address of the first element of the vector to initialise the array
+      int* theEdge1_ids_c = &theEdge1_ids[0];
+      int* theEdge2_ids_c = &theEdge2_ids[0];
+
+      std::ostringstream o;
+      o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
+      for (std::size_t j=0; j < theEdge1_ids.size(); j++)
+        o << theEdge1_ids[j] << ", ";
+      o << "], [";
+      for (std::size_t j=0; j < theEdge2_ids.size(); j++)
+        o << theEdge2_ids[j] << ", ";
+      o << "]";
+      MESSAGE(o.str());
+      MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
+      MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
+
+      if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
+        {
+          // If no source points, call peridoicity without transformation function
+          MESSAGE("periodicity without transformation function");
+          meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
+          status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
+              theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
+          if(status != STATUS_OK)
+            cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
+        }
+      else
+        {
+          // get the transformation vertices
+          MESSAGE("periodicity with transformation vertices");
+          double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
+          double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
+          int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
+          int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
+
+          MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
+
+          status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
+              theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
+          if(status != STATUS_OK)
+            cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
+          else
+            MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
+        }
     }
-    // Now we can delete the PreCAD session
-    precad_session_delete(pcs);
-  }
 
-  cadsurf_data_set_dcad(css, dcad);
-  if (cleanc) {
-    // Give the pre-processed CAD object to the current BLSurf session
-    cadsurf_data_set_cad(css, cleanc);
-  }
-  else {
-    // Use the original one
-    cadsurf_data_set_cad(css, c);
+    MESSAGE("END PRECAD EDGES PERIODICITY");
   }
 
+  
+  // TODO: be able to use a mesh in input.
+  // See imsh usage in Products/templates/mg-cadsurf_template_common.cpp
+  // => cadsurf_set_mesh
+    
+  // Use the original dcad
+  cadsurf_set_dcad(css, dcad);
+
+  // Use the original cad
+  cadsurf_set_cad(css, c);
+
   std::cout << std::endl;
   std::cout << "Beginning of Surface Mesh generation" << std::endl;
   std::cout << std::endl;
@@ -2210,22 +2489,16 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     if ( _comment.empty() )
       _comment = "Exception in cadsurf_compute_mesh()";
   }
-  if ( status != STATUS_OK) {
-    // There was an error while meshing
-    error(_comment);
-  }
-
-  PyGILState_Release(gstate);
 
   std::cout << std::endl;
   std::cout << "End of Surface Mesh generation" << std::endl;
   std::cout << std::endl;
 
   mesh_t *msh = NULL;
-  cadsurf_data_get_mesh(css, &msh);
+  cadsurf_get_mesh(css, &msh);
   if(!msh){
     /* release the mesh object */
-    cadsurf_data_regain_mesh(css, msh);
+    cadsurf_regain_mesh(css, msh);
     return error(_comment);
   }
 
@@ -2233,8 +2506,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   if (_hypothesis)
     GMFFileName = _hypothesis->GetGMFFile();
   if (GMFFileName != "") {
-    //     bool GMFFileMode = _hypothesis->GetGMFFileMode();
-    bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
+    bool asciiFound  = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
     if (!asciiFound && !binaryFound)
       GMFFileName.append(".mesh");
@@ -2242,8 +2514,8 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   }
 
   /* retrieve mesh data (see meshgems/mesh.h) */
-  integer nv, ne, nt, nq, vtx[4], tag;
-  integer *evedg, *evtri, *evquad, type;
+  integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
+  integer *evedg, *evtri, *evquad, *tags_buff, type;
   real xyz[3];
 
   mesh_get_vertex_count(msh, &nv);
@@ -2254,15 +2526,17 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   evedg  = (integer *)mesh_calloc_generic_buffer(msh);
   evtri  = (integer *)mesh_calloc_generic_buffer(msh);
   evquad = (integer *)mesh_calloc_generic_buffer(msh);
+  tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
 
-  SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
-  bool* tags = new bool[nv+1];
+  std::vector<const SMDS_MeshNode*> nodes(nv+1);
+  std::vector<bool>                  tags(nv+1);
 
   /* enumerated vertices */
   for(int iv=1;iv<=nv;iv++) {
     mesh_get_vertex_coordinates(msh, iv, xyz);
     mesh_get_vertex_tag(msh, iv, &tag);
     // Issue 0020656. Use vertex coordinates
+    nodes[iv] = NULL;
     if ( tag > 0 && tag <= pmap.Extent() ) {
       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
       double tol = BRep_Tool::Tolerance( v );
@@ -2271,8 +2545,10 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
       else
         tag = 0; // enforced or attracted vertex
+      nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
     }
-    nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
+    if ( !nodes[iv] )
+      nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
 
     // Create group of enforced vertices if requested
     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
@@ -2345,6 +2621,20 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     mesh_get_edge_vertices(msh, it, vtx);
     mesh_get_edge_extra_vertices(msh, it, &type, evedg);
     mesh_get_edge_tag(msh, it, &tag);
+
+    // If PreCAD performed some cleaning operations (remove tiny edges,
+    // merge edges ...) an output tag can indeed represent several original tags.
+    // Get the initial tags corresponding to the output tag and redefine the tag as 
+    // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
+    mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
+    if(nb_tag > 1)  
+      tag=tags_buff[nb_tag-1];
+    if ( tag < 1 || tag > emap.Extent() )
+    {
+      std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
+                << " does not point to a CAD edge (nb edges " << emap.Extent() << ")" << std::endl;
+      continue;
+    }
     if (tags[vtx[0]]) {
       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
       tags[vtx[0]] = false;
@@ -2374,29 +2664,29 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
     mesh_get_triangle_tag(msh, it, &tag);
     if (tags[vtx[0]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
       tags[vtx[0]] = false;
     };
     if (tags[vtx[1]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
       tags[vtx[1]] = false;
     };
     if (tags[vtx[2]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
       tags[vtx[2]] = false;
     };
     if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
       // QUADRATIC TRIANGLE
       if (tags[evtri[0]]) {
-        meshDS->SetNodeOnFace(nodes[evtri[0]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
         tags[evtri[0]] = false;
       }
       if (tags[evtri[1]]) {
-        meshDS->SetNodeOnFace(nodes[evtri[1]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
         tags[evtri[1]] = false;
       }
       if (tags[evtri[2]]) {
-        meshDS->SetNodeOnFace(nodes[evtri[2]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
         tags[evtri[2]] = false;
       }
       tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
@@ -2405,7 +2695,7 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     else {
       tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
     }
-    meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
+    meshDS->SetMeshElementOnShape(tri, tag);
   }
 
   /* enumerate quadrangles */
@@ -2415,42 +2705,42 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
     mesh_get_quadrangle_tag(msh, it, &tag);
     if (tags[vtx[0]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
       tags[vtx[0]] = false;
     };
     if (tags[vtx[1]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
       tags[vtx[1]] = false;
     };
     if (tags[vtx[2]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
       tags[vtx[2]] = false;
     };
     if (tags[vtx[3]]) {
-      meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
+      meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
       tags[vtx[3]] = false;
     };
     if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
       // QUADRATIC QUADRANGLE
       std::cout << "This is a quadratic quadrangle" << std::endl;
       if (tags[evquad[0]]) {
-        meshDS->SetNodeOnFace(nodes[evquad[0]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
         tags[evquad[0]] = false;
       }
       if (tags[evquad[1]]) {
-        meshDS->SetNodeOnFace(nodes[evquad[1]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
         tags[evquad[1]] = false;
       }
       if (tags[evquad[2]]) {
-        meshDS->SetNodeOnFace(nodes[evquad[2]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
         tags[evquad[2]] = false;
       }
       if (tags[evquad[3]]) {
-        meshDS->SetNodeOnFace(nodes[evquad[3]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
         tags[evquad[3]] = false;
       }
       if (tags[evquad[4]]) {
-        meshDS->SetNodeOnFace(nodes[evquad[4]], TopoDS::Face(fmap(tag)));
+        meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
         tags[evquad[4]] = false;
       }
       quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
@@ -2460,27 +2750,21 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
     else {
       quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
     }
-    meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
+    meshDS->SetMeshElementOnShape(quad, tag);
   }
 
   /* release the mesh object, the rest is released by cleaner */
-  cadsurf_data_regain_mesh(css, msh);
+  cadsurf_regain_mesh(css, msh);
 
-  delete [] nodes;
-  delete [] tags;
-
-  if ( needMerge ) // sew mesh computed by BLSURF with pre-existing mesh
+  if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
   {
     SMESH_MeshEditor editor( &aMesh );
     SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
     TIDSortedElemSet segementsOnEdge;
-    TIDSortedNodeSet nodesOnEdge;
     TSubMeshSet::iterator smIt;
     SMESHDS_SubMesh* smDS;
-    typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > TNodeIterator;
-    double tol;
 
-    // merge nodes on EDGE's with ones computed by BLSURF
+    // merge nodes on EDGE's with ones computed by MG-CADSurf
     for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
     {
       if (! (smDS = *smIt) ) continue;
@@ -2517,7 +2801,6 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
   }
 
   // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
-  TopLoc_Location loc; double f,l;
   for (int i = 1; i <= emap.Extent(); i++)
     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
       sm->SetIsAlwaysComputed( true );
@@ -2527,16 +2810,33 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
         sm->SetIsAlwaysComputed( true );
 
   // Set error to FACE's w/o elements
-  for ( int i = 1; i <= fmap.Extent(); ++i )
+  SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
+  if ( _comment.empty() && status == STATUS_OK )
   {
-    SMESH_subMesh* sm = aMesh.GetSubMesh( fmap(i) );
+    err      = COMPERR_WARNING;
+    _comment = "No mesh elements assigned to a face";
+  }
+  bool badFaceFound = false;
+  for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
+  {
+    TopoDS_Face f = TopoDS::Face(face_iter.Current());
+    SMESH_subMesh* sm = aMesh.GetSubMesh( f );
     if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
-      sm->GetComputeError().reset
-        ( new SMESH_ComputeError( COMPERR_ALGO_FAILED, _comment, this ));
+    {
+      sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
+      badFaceFound = true;
+    }
+  }
+  if ( err == COMPERR_WARNING )
+  {
+    _comment.clear();
+  }
+  if ( status != STATUS_OK && !badFaceFound ) {
+    error(_comment);
   }
 
   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
-#ifndef WNT
+#ifndef WIN32
   if ( oldFEFlags > 0 )
     feenableexcept( oldFEFlags );
   feclearexcept( FE_ALL_EXCEPT );
@@ -2563,12 +2863,10 @@ bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
  */
 //================================================================================
 
-#ifdef WITH_SMESH_CANCEL_COMPUTE
 void BLSURFPlugin_BLSURF::CancelCompute()
 {
   _compute_canceled = true;
 }
-#endif
 
 //=============================================================================
 /*!
@@ -2576,7 +2874,7 @@ void BLSURFPlugin_BLSURF::CancelCompute()
  */
 //=============================================================================
 
-void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
+void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
   const TopoDS_Edge edge = TopoDS::Edge(ed);
 
   gp_Pnt pnt(node->X(), node->Y(), node->Z());
@@ -2585,6 +2883,12 @@ void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* no
   Standard_Real p1 = 1.0;
   TopLoc_Location loc;
   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
+  if ( curve.IsNull() )
+  {
+    // issue 22499. Node at a sphere apex
+    meshDS->SetNodeOnEdge(node, edge, p0);
+    return;
+  }
 
   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
@@ -2603,9 +2907,6 @@ void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* no
       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
     }
   }
-//   GProp_GProps LProps;
-//   BRepGProp::LinearProperties(ed, LProps);
-//   double lg = (double)LProps.Mass();
 
   meshDS->SetNodeOnEdge(node, edge, pa);
 }
@@ -2620,14 +2921,14 @@ void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* no
 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
 {
   /* t is given. It contains the t (time) 1D parametric coordintaes
-     of the point PreCAD/BLSurf is querying on the curve */
+     of the point PreCAD/MG-CADSurf is querying on the curve */
 
-  /* user_data identifies the edge PreCAD/BLSurf is querying
+  /* user_data identifies the edge PreCAD/MG-CADSurf is querying
    * (see cad_edge_new later in this example) */
   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
 
   if (uv){
-   /* BLSurf is querying the function evaluation */
+   /* MG-CADSurf is querying the function evaluation */
     gp_Pnt2d P;
     P=pargeo->Value(t);
     uv[0]=P.X(); uv[1]=P.Y();
@@ -2661,9 +2962,9 @@ status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
                   real *duu, real *duv, real *dvv, void *user_data)
 {
   /* uv[2] is given. It contains the u,v coordinates of the point
-   * PreCAD/BLSurf is querying on the surface */
+   * PreCAD/MG-CADSurf is querying on the surface */
 
-  /* user_data identifies the face PreCAD/BLSurf is querying (see
+  /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
    * cad_face_new later in this example)*/
   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
 
@@ -2700,15 +3001,12 @@ status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
 
 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
 {
-  //MESSAGE("size_on_surface")
+  TId2ClsAttractorVec::iterator f2attVec;
   if (FaceId2PythonSmp.count(face_id) != 0){
-    //MESSAGE("A size map is used to calculate size on face : "<<face_id)
-    PyObject * pyresult = NULL;
-    PyObject* new_stderr = NULL;
     assert(Py_IsInitialized());
     PyGILState_STATE gstate;
     gstate = PyGILState_Ensure();
-    pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
+    PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
     real result;
     if ( pyresult != NULL) {
       result = PyFloat_AsDouble(pyresult);
@@ -2718,10 +3016,12 @@ status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
     else{
       fflush(stderr);
       string err_description="";
-      new_stderr = newPyStdOut(err_description);
+      PyObject* new_stderr = newPyStdOut(err_description);
+      PyObject* old_stderr = PySys_GetObject((char*)"stderr");
+      Py_INCREF(old_stderr);
       PySys_SetObject((char*)"stderr", new_stderr);
       PyErr_Print();
-      PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
+      PySys_SetObject((char*)"stderr", old_stderr);
       Py_DECREF(new_stderr);
       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
       result = *((real*)user_data);
@@ -2729,11 +3029,19 @@ status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
     *size = result;
     PyGILState_Release(gstate);
   }
-  else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
+  else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
 //    MESSAGE("attractor used on face :"<<face_id)
     // MESSAGE("List of attractor is not empty")
     // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
-    real result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
+    real result = 0;
+    result = 1e100;
+    std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
+    for ( size_t i = 0; i < attVec.size(); ++i )
+    {
+      //result += attVec[i]->GetSize(uv[0],uv[1]);
+      result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
+    }
+    //*size = result / attVec.size(); // mean of sizes defined by all attractors
     *size = result;
   }
   else {
@@ -2747,12 +3055,10 @@ status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
 {
   if (EdgeId2PythonSmp.count(edge_id) != 0){
-    PyObject * pyresult = NULL;
-    PyObject* new_stderr = NULL;
     assert(Py_IsInitialized());
     PyGILState_STATE gstate;
     gstate = PyGILState_Ensure();
-    pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
+    PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
     real result;
     if ( pyresult != NULL) {
       result = PyFloat_AsDouble(pyresult);
@@ -2762,10 +3068,12 @@ status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
     else{
       fflush(stderr);
       string err_description="";
-      new_stderr = newPyStdOut(err_description);
+      PyObject* new_stderr = newPyStdOut(err_description);
+      PyObject* old_stderr = PySys_GetObject((char*)"stderr");
+      Py_INCREF(old_stderr);
       PySys_SetObject((char*)"stderr", new_stderr);
       PyErr_Print();
-      PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
+      PySys_SetObject((char*)"stderr", old_stderr);
       Py_DECREF(new_stderr);
       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
       result = *((real*)user_data);
@@ -2782,12 +3090,10 @@ status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
 status_t size_on_vertex(integer point_id, real *size, void *user_data)
 {
   if (VertexId2PythonSmp.count(point_id) != 0){
-    PyObject * pyresult = NULL;
-    PyObject* new_stderr = NULL;
     assert(Py_IsInitialized());
     PyGILState_STATE gstate;
     gstate = PyGILState_Ensure();
-    pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
+    PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
     real result;
     if ( pyresult != NULL) {
       result = PyFloat_AsDouble(pyresult);
@@ -2797,10 +3103,12 @@ status_t size_on_vertex(integer point_id, real *size, void *user_data)
     else {
       fflush(stderr);
       string err_description="";
-      new_stderr = newPyStdOut(err_description);
+      PyObject* new_stderr = newPyStdOut(err_description);
+      PyObject* old_stderr = PySys_GetObject((char*)"stderr");
+      Py_INCREF(old_stderr);
       PySys_SetObject((char*)"stderr", new_stderr);
       PyErr_Print();
-      PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
+      PySys_SetObject((char*)"stderr", old_stderr);
       Py_DECREF(new_stderr);
       MESSAGE("Can't evaluate f()" << " error is " << err_description);
       result = *((real*)user_data);
@@ -2815,7 +3123,7 @@ status_t size_on_vertex(integer point_id, real *size, void *user_data)
 }
 
 /*
- * The following function will be called for PreCAD/BLSurf message
+ * The following function will be called for PreCAD/MG-CADSurf message
  * printing.  See context_set_message_callback (later in this
  * template) for how to set user_data.
  */
@@ -2827,36 +3135,41 @@ status_t message_cb(message_t *msg, void *user_data)
   message_get_description(msg, &desc);
   string err( desc );
   message_cb_user_data * mcud = (message_cb_user_data*)user_data;
-  if ( errnumber < 0 || err.find("license") != string::npos ) {
+  // Get all the error message and some warning messages related to license and periodicity
+  if ( errnumber < 0 ||
+       err.find("license"    ) != string::npos ||
+       err.find("periodicity") != string::npos )
+  {
     // remove ^A from the tail
     int len = strlen( desc );
     while (len > 0 && desc[len-1] != '\n')
       len--;
     mcud->_error->append( desc, len );
   }
-  else if ( mcud->_verbosity > 0 ) {
-    std::cout << desc << std::endl;
+  else {
+    if ( errnumber == 3009001 )
+      * mcud->_progress = atof( desc + 11 ) / 100.;
+    if ( mcud->_verbosity > 0 )
+      std::cout << desc << std::endl;
   }
   return STATUS_OK;
 }
 
-/* This is the interrupt callback. PreCAD/BLSurf will call this
+/* This is the interrupt callback. PreCAD/MG-CADSurf will call this
  * function regularily. See the file meshgems/interrupt.h
  */
 status_t interrupt_cb(integer *interrupt_status, void *user_data)
 {
   integer you_want_to_continue = 1;
-#ifdef WITH_SMESH_CANCEL_COMPUTE
   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
   you_want_to_continue = !tmp->computeCanceled();
-#endif
 
   if(you_want_to_continue)
   {
     *interrupt_status = INTERRUPT_CONTINUE;
     return STATUS_OK;
   }
-  else /* you want to stop BLSurf */
+  else /* you want to stop MG-CADSurf */
   {
     *interrupt_status = INTERRUPT_STOP;
     return STATUS_ERROR;