0030897: Modeling Algorithms - Crash in UnifySameDomain [Regression]
[occt.git] / src / ShapeUpgrade / ShapeUpgrade_UnifySameDomain.cxx
index 7181894..6489c4e 100644 (file)
 
 
 #include <BRep_Builder.hxx>
-#include <BRep_CurveRepresentation.hxx>
-#include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
-#include <BRep_TEdge.hxx>
 #include <BRep_Tool.hxx>
 #include <BRepLib.hxx>
 #include <BRepLib_MakeEdge.hxx>
+#include <BRepLib_MakeFace.hxx>
 #include <BRepTopAdaptor_TopolTool.hxx>
 #include <GC_MakeCircle.hxx>
 #include <Geom2d_Line.hxx>
+#include <GCE2d_MakeLine.hxx>
 #include <Geom2d_TrimmedCurve.hxx>
 #include <Geom2dConvert.hxx>
 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
@@ -34,6 +33,7 @@
 #include <Geom_ElementarySurface.hxx>
 #include <Geom_Line.hxx>
 #include <Geom_OffsetSurface.hxx>
+#include <Geom_Plane.hxx>
 #include <Geom_RectangularTrimmedSurface.hxx>
 #include <Geom_Surface.hxx>
 #include <Geom_SurfaceOfLinearExtrusion.hxx>
 #include <ShapeAnalysis_WireOrder.hxx>
 #include <ShapeBuild_Edge.hxx>
 #include <ShapeBuild_ReShape.hxx>
-#include <ShapeExtend_CompositeSurface.hxx>
-#include <ShapeFix_ComposeShell.hxx>
 #include <ShapeFix_Edge.hxx>
 #include <ShapeFix_Face.hxx>
-#include <ShapeFix_SequenceOfWireSegment.hxx>
 #include <ShapeFix_Shell.hxx>
 #include <ShapeFix_Wire.hxx>
-#include <ShapeFix_WireSegment.hxx>
-#include <ShapeUpgrade_RemoveLocations.hxx>
 #include <ShapeUpgrade_UnifySameDomain.hxx>
 #include <Standard_Type.hxx>
 #include <TColGeom2d_Array1OfBSplineCurve.hxx>
 #include <TColGeom2d_HArray1OfBSplineCurve.hxx>
 #include <TColGeom2d_SequenceOfBoundedCurve.hxx>
+#include <TColGeom2d_SequenceOfCurve.hxx>
 #include <TColGeom_Array1OfBSplineCurve.hxx>
 #include <TColGeom_HArray1OfBSplineCurve.hxx>
-#include <TColGeom_HArray2OfSurface.hxx>
 #include <TColGeom_SequenceOfSurface.hxx>
 #include <TColStd_Array1OfReal.hxx>
 #include <TColStd_MapOfInteger.hxx>
 #include <TopTools_SequenceOfShape.hxx>
 #include <gp_Circ.hxx>
 #include <BRepAdaptor_Curve.hxx>
-#include <BRepClass_FaceClassifier.hxx>
+#include <BRepAdaptor_Curve2d.hxx>
+#include <BRepAdaptor_Surface.hxx>
+#include <gp_Vec2d.hxx>
+#include <Extrema_ExtPS.hxx>
+#include <BRepTools.hxx>
+#include <BRepTopAdaptor_FClass2d.hxx>
 
-IMPLEMENT_STANDARD_RTTIEXT(ShapeUpgrade_UnifySameDomain,MMgt_TShared)
+IMPLEMENT_STANDARD_RTTIEXT(ShapeUpgrade_UnifySameDomain,Standard_Transient)
 
 struct SubSequenceOfEdges
 {
@@ -95,6 +95,664 @@ struct SubSequenceOfEdges
   TopoDS_Edge UnionEdges;
 };
 
+static Standard_Real TrueValueOfOffset(const Standard_Real theValue,
+                                       const Standard_Real thePeriod)
+{
+  if (theValue > 0.)
+    return thePeriod;
+
+  return (-thePeriod);
+}
+
+//=======================================================================
+//function : UpdateBoundaries
+//purpose  : auxilary
+//=======================================================================
+static void UpdateBoundaries(const Handle(Geom2d_Curve)& thePCurve,
+                             const Standard_Real         theFirst,
+                             const Standard_Real         theLast,
+                             Standard_Real& theUfirst,
+                             Standard_Real& theUlast)
+{
+  const Standard_Integer NbSamples = 4;
+  Standard_Real Delta = (theLast - theFirst)/NbSamples;
+
+  for (Standard_Integer i = 0; i <= NbSamples; i++)
+  {
+    Standard_Real aParam = theFirst + i*Delta;
+    gp_Pnt2d aPoint = thePCurve->Value(aParam);
+    if (aPoint.X() < theUfirst)
+      theUfirst = aPoint.X();
+    if (aPoint.X() > theUlast)
+      theUlast  = aPoint.X();
+  }
+}
+
+static void RemoveEdgeFromMap(const TopoDS_Edge& theEdge,
+                              TopTools_IndexedDataMapOfShapeListOfShape& theVEmap)
+{
+  TopoDS_Vertex VV [2];
+  TopExp::Vertices(theEdge, VV[0], VV[1]);
+  for (Standard_Integer i = 0; i < 2; i++)
+  {
+    TopTools_ListOfShape& Elist = theVEmap.ChangeFromKey(VV[i]);
+    TopTools_ListIteratorOfListOfShape itl(Elist);
+    while (itl.More())
+    {
+      const TopoDS_Shape& anEdge = itl.Value();
+      if (anEdge.IsSame(theEdge))
+        Elist.Remove(itl);
+      else
+        itl.Next();
+    }
+  }
+}
+
+static Standard_Real ComputeMinEdgeSize(const TopTools_SequenceOfShape& theEdges,
+                                        const TopoDS_Face&              theRefFace,
+                                        TopTools_MapOfShape&            theEdgesMap)
+{
+  Standard_Real MinSize = RealLast();
+  
+  for (Standard_Integer ind = 1; ind <= theEdges.Length(); ind++)
+  {
+    const TopoDS_Edge& anEdge = TopoDS::Edge(theEdges(ind));
+    theEdgesMap.Add(anEdge);
+    TopoDS_Vertex V1, V2;
+    TopExp::Vertices(anEdge, V1, V2);
+    BRepAdaptor_Curve2d BAcurve2d(anEdge, theRefFace);
+    gp_Pnt2d FirstP2d = BAcurve2d.Value(BAcurve2d.FirstParameter());
+    gp_Pnt2d LastP2d  = BAcurve2d.Value(BAcurve2d.LastParameter());
+    Standard_Real aSqDist;
+    if (V1.IsSame(V2) &&
+        !BRep_Tool::Degenerated(anEdge))
+    {
+      gp_Pnt2d MidP2d = BAcurve2d.Value((BAcurve2d.FirstParameter()+BAcurve2d.LastParameter())/2);
+      aSqDist = FirstP2d.SquareDistance(MidP2d);
+    }
+    else
+      aSqDist = FirstP2d.SquareDistance(LastP2d);
+    if (aSqDist < MinSize)
+      MinSize = aSqDist;
+  }
+  MinSize = Sqrt(MinSize);
+  return MinSize;
+}
+
+static void FindFaceWithMaxUbound(const TopTools_SequenceOfShape& theFaces,
+                                  const TopoDS_Face&              theRefFace,
+                                  const TopTools_MapOfShape&      theEdgesMap,
+                                  Standard_Real&                  theUmax,
+                                  Standard_Integer&               theIndFaceMax)
+{
+  theUmax = RealFirst();
+  theIndFaceMax = 0;
+  for (Standard_Integer ii = 1; ii <= theFaces.Length(); ii++)
+  {
+    const TopoDS_Face& face_ii = TopoDS::Face(theFaces(ii));
+    Standard_Real Ufirst = RealLast(), Ulast = RealFirst();
+    TopExp_Explorer Explo(face_ii, TopAbs_EDGE);
+    for (; Explo.More(); Explo.Next())
+    {
+      const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
+      if (!theEdgesMap.Contains(anEdge))
+        continue;
+      Standard_Real fpar, lpar;
+      Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, theRefFace, fpar, lpar);
+      UpdateBoundaries(aPCurve, fpar, lpar, Ufirst, Ulast);
+    }
+    if (Ulast > theUmax)
+    {
+      theUmax = Ulast;
+      theIndFaceMax = ii;
+    }
+  }
+}
+
+static void RelocatePCurvesToNewUorigin(const TopTools_SequenceOfShape& theEdges,
+                                        const TopoDS_Shape&             theFirstFace,
+                                        const TopoDS_Face&              theRefFace,
+                                        const Standard_Real             theCoordTol,
+                                        const Standard_Real             theUperiod,
+                                        TopTools_IndexedDataMapOfShapeListOfShape& theVEmap,
+                                        NCollection_DataMap<TopoDS_Shape, Handle(Geom2d_Curve)>& theEdgeNewPCurve,
+                                        TopTools_MapOfShape&      theUsedEdges)
+{
+  TopTools_MapOfShape EdgesOfFirstFace;
+  TopExp::MapShapes(theFirstFace, EdgesOfFirstFace);
+  
+  for (;;) //walk by contours
+  {
+    //try to find the start edge that:
+    //1. belongs to outer edges of first face;
+    //2. has minimum U-coord of its start point
+    TopoDS_Edge StartEdge;
+    TopAbs_Orientation anOr = TopAbs_FORWARD;
+    Standard_Real anUmin = RealLast();
+    for (Standard_Integer ii = 1; ii <= theEdges.Length(); ii++)
+    {
+      const TopoDS_Edge& anEdge = TopoDS::Edge(theEdges(ii));
+      if (theUsedEdges.Contains(anEdge))
+        continue;
+      if (EdgesOfFirstFace.Contains(anEdge))
+      {
+        if (StartEdge.IsNull())
+        {
+          StartEdge = anEdge;
+          BRepAdaptor_Curve2d StartBAcurve(StartEdge, theRefFace);
+          Standard_Real aFirstParam, aLastParam;
+          if (StartEdge.Orientation() == TopAbs_FORWARD)
+          {
+            aFirstParam = StartBAcurve.FirstParameter();
+            aLastParam  = StartBAcurve.LastParameter();
+          }
+          else
+          {
+            aFirstParam = StartBAcurve.LastParameter();
+            aLastParam  = StartBAcurve.FirstParameter();
+          }
+          gp_Pnt2d aFirstPoint = StartBAcurve.Value(aFirstParam);
+          gp_Pnt2d aLastPoint  = StartBAcurve.Value(aLastParam);
+          if (aFirstPoint.X() < aLastPoint.X())
+          {
+            anUmin = aFirstPoint.X();
+            anOr = TopAbs_FORWARD;
+          }
+          else
+          {
+            anUmin = aLastPoint.X();
+            anOr = TopAbs_REVERSED;
+          }
+        }
+        else
+        {
+          BRepAdaptor_Curve2d aBAcurve(anEdge, theRefFace);
+          Standard_Real aFirstParam, aLastParam;
+          if (anEdge.Orientation() == TopAbs_FORWARD)
+          {
+            aFirstParam = aBAcurve.FirstParameter();
+            aLastParam  = aBAcurve.LastParameter();
+          }
+          else
+          {
+            aFirstParam = aBAcurve.LastParameter();
+            aLastParam  = aBAcurve.FirstParameter();
+          }
+          gp_Pnt2d aFirstPoint = aBAcurve.Value(aFirstParam);
+          gp_Pnt2d aLastPoint  = aBAcurve.Value(aLastParam);
+          if (aFirstPoint.X() < anUmin)
+          {
+            StartEdge = anEdge;
+            anUmin = aFirstPoint.X();
+            anOr = TopAbs_FORWARD;
+          }
+          if (aLastPoint.X() < anUmin)
+          {
+            StartEdge = anEdge;
+            anUmin = aLastPoint.X();
+            anOr = TopAbs_REVERSED;
+          }
+        }
+      } //if (EdgesOfFirstFace.Contains(anEdge))
+    } //for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+    
+    if (StartEdge.IsNull()) //all contours are passed
+      break;
+    
+    TopoDS_Vertex StartVertex = (anOr == TopAbs_FORWARD)?
+      TopExp::FirstVertex(StartEdge, Standard_True) : TopExp::LastVertex(StartEdge, Standard_True);
+    TopoDS_Edge CurEdge = StartEdge;
+    Standard_Real fpar, lpar;
+    Handle(Geom2d_Curve) CurPCurve = BRep_Tool::CurveOnSurface(CurEdge, theRefFace, fpar, lpar);
+    CurPCurve = new Geom2d_TrimmedCurve(CurPCurve, fpar, lpar);
+    theEdgeNewPCurve.Bind(CurEdge, CurPCurve);
+    if (CurEdge.Orientation() == TopAbs_REVERSED)
+    { Standard_Real tmp = fpar; fpar = lpar; lpar = tmp; }
+    //Standard_Real StartParam = (anOr == TopAbs_FORWARD)? fpar : lpar;
+    Standard_Real CurParam = (anOr == TopAbs_FORWARD)? lpar : fpar;
+    //gp_Pnt2d StartPoint = CurPCurve->Value(StartParam);
+    gp_Pnt2d CurPoint = CurPCurve->Value(CurParam);
+    for (;;) //collect pcurves of a contour
+    {
+      RemoveEdgeFromMap(CurEdge, theVEmap);
+      theUsedEdges.Add(CurEdge);
+      TopoDS_Vertex CurVertex = (anOr == TopAbs_FORWARD)?
+        TopExp::LastVertex(CurEdge, Standard_True) : TopExp::FirstVertex(CurEdge, Standard_True);
+      
+      const TopTools_ListOfShape& Elist = theVEmap.FindFromKey(CurVertex);
+      if (Elist.IsEmpty())
+        break; //end of contour in 3d
+      
+      TopTools_ListIteratorOfListOfShape itl(Elist);
+      for (; itl.More(); itl.Next())
+      {
+        const TopoDS_Edge& anEdge = TopoDS::Edge(itl.Value());
+        if (anEdge.IsSame(CurEdge))
+          continue;
+        TopoDS_Vertex aFirstVertex = (anOr == TopAbs_FORWARD)?
+          TopExp::FirstVertex(anEdge, Standard_True) : TopExp::LastVertex(anEdge, Standard_True);
+        if (!aFirstVertex.IsSame(CurVertex)) //may be if CurVertex is deg.vertex
+          continue;
+        
+        Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, theRefFace, fpar, lpar);
+        aPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
+        if (anEdge.Orientation() == TopAbs_REVERSED)
+        { Standard_Real tmp = fpar; fpar = lpar; lpar = tmp; }
+        Standard_Real aParam = (anOr == TopAbs_FORWARD)? fpar : lpar;
+        gp_Pnt2d aPoint = aPCurve->Value(aParam);
+        Standard_Real anOffset = CurPoint.X() - aPoint.X();
+        if (!(Abs(anOffset) < theCoordTol ||
+              Abs(Abs(anOffset) - theUperiod) < theCoordTol))
+          continue; //may be if CurVertex is deg.vertex
+        
+        if (Abs(anOffset) > theUperiod/2)
+        {
+          anOffset = TrueValueOfOffset(anOffset, theUperiod);
+          gp_Vec2d aVec(anOffset, 0.);
+          Handle(Geom2d_Curve) aNewPCurve = Handle(Geom2d_Curve)::DownCast(aPCurve->Copy());
+          aNewPCurve->Translate(aVec);
+          aPCurve = aNewPCurve;
+        }
+        theEdgeNewPCurve.Bind(anEdge, aPCurve);
+        CurEdge = anEdge;
+        TopAbs_Orientation CurOr = TopAbs::Compose(anOr, CurEdge.Orientation());
+        CurParam = (CurOr == TopAbs_FORWARD)?
+          aPCurve->LastParameter() : aPCurve->FirstParameter();
+        CurPoint = aPCurve->Value(CurParam);
+        break;
+      }
+    } //for (;;) (collect pcurves of a contour)
+  } //for (;;) (walk by contours)
+}
+
+static void InsertWiresIntoFaces(const TopTools_SequenceOfShape& theWires,
+                                 const TopTools_SequenceOfShape& theFaces,
+                                 const TopoDS_Face&              theRefFace)
+{
+  BRep_Builder BB;
+  for (Standard_Integer ii = 1; ii <= theWires.Length(); ii++)
+  {
+    const TopoDS_Wire& aWire = TopoDS::Wire(theWires(ii));
+    TopoDS_Iterator iter(aWire);
+    const TopoDS_Edge& anEdge = TopoDS::Edge(iter.Value());
+    BRepAdaptor_Curve2d BAcurve2d(anEdge, theRefFace);
+    gp_Pnt2d aPnt2d = BAcurve2d.Value((BAcurve2d.FirstParameter() + BAcurve2d.LastParameter())/2.);
+    TopoDS_Shape RequiredFace;
+    for (Standard_Integer jj = 1; jj <= theFaces.Length(); jj++)
+    {
+      const TopoDS_Face& aFace = TopoDS::Face(theFaces(jj));
+      BRepTopAdaptor_FClass2d Classifier(aFace, Precision::Confusion());
+      TopAbs_State aStatus = Classifier.Perform(aPnt2d);
+      if (aStatus == TopAbs_IN)
+      {
+        RequiredFace = aFace.Oriented (TopAbs_FORWARD);
+        break;
+      }
+    }
+    if (!RequiredFace.IsNull())
+    {
+      BB.Add(RequiredFace, aWire);
+    }
+    else
+    {
+      Standard_ASSERT_INVOKE ("ShapeUpgrade_UnifySameDomain: wire remains unclassified");
+    }
+  }
+}
+
+static TopoDS_Face FindCommonFace(const TopoDS_Edge&  theEdge1,
+                                  const TopoDS_Edge&  theEdge2,
+                                  const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap,
+                                  TopAbs_Orientation& theOrOfE1OnFace,
+                                  TopAbs_Orientation& theOrOfE2OnFace)
+{
+  TopoDS_Vertex aVertex;
+  TopExp::CommonVertex(theEdge1, theEdge2, aVertex);
+  const TopTools_ListOfShape& Flist = theVFmap.FindFromKey(aVertex);
+  TopTools_ListIteratorOfListOfShape itl(Flist);
+  for (; itl.More(); itl.Next())
+  {
+    TopoDS_Face aFace = TopoDS::Face(itl.Value());
+    aFace.Orientation(TopAbs_FORWARD);
+    Standard_Boolean e1found = Standard_False, e2found = Standard_False;
+    TopExp_Explorer Explo(aFace, TopAbs_EDGE);
+    for (; Explo.More(); Explo.Next())
+    {
+      const TopoDS_Shape& anEdge = Explo.Current();
+      if (anEdge.IsSame(theEdge1))
+      {
+        e1found = Standard_True;
+        theOrOfE1OnFace = anEdge.Orientation();
+      }
+      if (anEdge.IsSame(theEdge2))
+      {
+        e2found = Standard_True;
+        theOrOfE2OnFace = anEdge.Orientation();
+      }
+      if (e1found && e2found)
+        return aFace;
+    }
+  }
+
+  TopoDS_Face NullFace;
+  return NullFace;
+}
+
+static Standard_Boolean FindClosestPoints(const TopoDS_Edge& theEdge1,
+                                          const TopoDS_Edge& theEdge2,
+                                          const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap,
+                                          TopoDS_Face& theCommonFace,
+                                          Standard_Real& theMinSqDist,
+                                          TopAbs_Orientation& OrOfE1OnFace,
+                                          TopAbs_Orientation& OrOfE2OnFace,
+                                          Standard_Integer& theIndOnE1,
+                                          Standard_Integer& theIndOnE2,
+                                          gp_Pnt2d* PointsOnEdge1,
+                                          gp_Pnt2d* PointsOnEdge2)
+                                
+{
+  theCommonFace = FindCommonFace(theEdge1, theEdge2, theVFmap, OrOfE1OnFace, OrOfE2OnFace);
+  if (theCommonFace.IsNull())
+    return Standard_False;
+  
+  Standard_Real fpar1, lpar1, fpar2, lpar2;
+  Handle(Geom2d_Curve) PCurve1 = BRep_Tool::CurveOnSurface(theEdge1, theCommonFace, fpar1, lpar1);
+  Handle(Geom2d_Curve) PCurve2 = BRep_Tool::CurveOnSurface(theEdge2, theCommonFace, fpar2, lpar2);
+  PointsOnEdge1[0] = PCurve1->Value(fpar1);
+  PointsOnEdge1[1] = PCurve1->Value(lpar1);
+  PointsOnEdge2[0] = PCurve2->Value(fpar2);
+  PointsOnEdge2[1] = PCurve2->Value(lpar2);
+  theMinSqDist = RealLast();
+  theIndOnE1 = -1;
+  theIndOnE2 = -1;
+  for (Standard_Integer ind1 = 0; ind1 < 2; ind1++)
+    for (Standard_Integer ind2 = 0; ind2 < 2; ind2++)
+    {
+      Standard_Real aSqDist = PointsOnEdge1[ind1].SquareDistance(PointsOnEdge2[ind2]);
+      if (aSqDist < theMinSqDist)
+      {
+        theMinSqDist = aSqDist;
+        theIndOnE1 = ind1; theIndOnE2 = ind2;
+      }
+    }
+  return Standard_True;
+}
+
+//=======================================================================
+//function : ReconstructMissedSeam
+//purpose  : auxilary
+//=======================================================================
+static void ReconstructMissedSeam(const TopTools_SequenceOfShape& theEdges,
+                                  const TopTools_MapOfShape&      theUsedEdges,
+                                  const TopoDS_Face&              theFrefFace,
+                                  const TopoDS_Vertex&            theCurVertex,
+                                  const gp_Pnt2d&                 theCurPoint,
+                                  const Standard_Real             theUperiod,
+                                  const Standard_Real             theFaceUmin,
+                                  const Standard_Real             theCoordTol,
+                                  TopoDS_Edge&                    theNextEdge,
+                                  TopoDS_Wire&                    theNewWire,
+                                  gp_Pnt2d&                       theNextPoint,
+                                  gp_Pnt2d&                       theStartOfNextEdge,
+                                  TopoDS_Vertex&                  theLastVertexOfSeam,
+                                  TopTools_IndexedDataMapOfShapeListOfShape& theVEmap)
+                                  
+{
+  Handle(Geom_Surface) RefSurf = BRep_Tool::Surface(theFrefFace);
+  GeomAbs_Shape aContinuity = (RefSurf->IsUPeriodic())? GeomAbs_CN : GeomAbs_C0;
+  
+  Standard_Real Ydir = 1.; //up
+  if (Abs(theCurPoint.X() - theFaceUmin) <= theCoordTol)
+    Ydir = -1.; //down
+
+  //Consider as the candidate to be next edge:
+  //only the edge that has first point with X-coordinate close to X-coordinate of theCurPoint
+  //Choose from candidates the edge that is closest to theCurPoint in the defined direction Ydir
+  Standard_Real MinDeltaY = RealLast();
+  for (Standard_Integer ind = 1; ind <= theEdges.Length(); ind++)
+  {
+    const TopoDS_Edge& aCandidate = TopoDS::Edge(theEdges(ind));
+    if (theUsedEdges.Contains(aCandidate))
+      continue;
+    BRepAdaptor_Curve2d BAcurve2d(aCandidate, theFrefFace);
+    Standard_Real CandParam = (aCandidate.Orientation() == TopAbs_FORWARD)?
+      BAcurve2d.FirstParameter() : BAcurve2d.LastParameter();
+    gp_Pnt2d CandPoint = BAcurve2d.Value(CandParam);
+    Standard_Real DeltaX = Abs(CandPoint.X() - theCurPoint.X());
+    if (DeltaX > theCoordTol)
+      continue;
+    
+    Standard_Real DeltaY = CandPoint.Y() - theCurPoint.Y();
+    DeltaY *= Ydir;
+    if (DeltaY < 0.) //on the other side from CurPoint
+      continue;
+    if (DeltaY < MinDeltaY)
+    {
+      MinDeltaY = DeltaY;
+      theNextEdge = aCandidate;
+      theStartOfNextEdge = CandPoint;
+    }
+  }
+  
+  //Build missed seam edge
+  theLastVertexOfSeam = TopExp::FirstVertex(theNextEdge, Standard_True); //with orientation
+  Standard_Real CurTol  = BRep_Tool::Tolerance(theCurVertex);
+  Standard_Real LastTol = BRep_Tool::Tolerance(theLastVertexOfSeam);
+  Standard_Real anU = (CurTol < LastTol)? theCurPoint.X() : theStartOfNextEdge.X();
+  Handle(Geom_Curve) Uiso = RefSurf->UIso(anU);
+  TopoDS_Vertex V1, V2;
+  Standard_Real Param1, Param2;
+  if (Ydir > 0)
+  {
+    V1 = theCurVertex; V2 = theLastVertexOfSeam;
+    Param1 = theCurPoint.Y(); Param2 = theStartOfNextEdge.Y();
+  }
+  else
+  {
+    V1 = theLastVertexOfSeam; V2 = theCurVertex;
+    Param1 = theStartOfNextEdge.Y(); Param2 = theCurPoint.Y();
+  }
+  TopoDS_Edge MissedSeam = BRepLib_MakeEdge(Uiso, V1, V2, Param1, Param2);
+  Standard_Real Vorigin = 0.;
+  //Correct Param1 and Param2 if needed:
+  //when Uiso-curve is periodic and Param1 and Param2 do not fit into V-range of surface,
+  //BRepLib_MakeEdge may shift Param1 and Param2
+  Standard_Real InitialParam1 = Param1, InitialParam2 = Param2;
+  Handle(Geom_Curve) MissedCurve = BRep_Tool::Curve(MissedSeam, Param1, Param2);
+  if ((Param1 != InitialParam1 || Param2 != InitialParam2) &&
+      MissedCurve->IsPeriodic())
+  {
+    //Vorigin = -(MissedCurve->Period());
+    Vorigin = -(Param1 - InitialParam1);
+  }
+  /////////////////////////////////////
+  Handle(Geom2d_Line) PC1 = new Geom2d_Line(gp_Pnt2d(anU, Vorigin), gp_Dir2d(0., 1.));
+  gp_Vec2d Offset(theUperiod, 0.);
+  if (Ydir > 0)
+    Offset *= -1;
+  Handle(Geom2d_Curve) PC2 = Handle(Geom2d_Curve)::DownCast(PC1->Copy());
+  PC2->Translate(Offset);
+  
+  BRep_Builder BB;
+  if (Ydir > 0)
+    BB.UpdateEdge(MissedSeam, PC1, PC2, theFrefFace, 0.);
+  else
+    BB.UpdateEdge(MissedSeam, PC2, PC1, theFrefFace, 0.);
+  BB.Continuity(MissedSeam, theFrefFace, theFrefFace, aContinuity);
+  if (Ydir < 0)
+    MissedSeam.Reverse();
+
+  BB.Add(theNewWire, MissedSeam);
+  //add newly created edge into VEmap
+  MissedSeam.Reverse();
+  TopExp::MapShapesAndUniqueAncestors(MissedSeam, TopAbs_VERTEX, TopAbs_EDGE, theVEmap);
+                  
+  BRepAdaptor_Curve2d BAcurve2d(theNextEdge, theFrefFace);
+  Standard_Real ParamOfNextPoint = (theNextEdge.Orientation() == TopAbs_FORWARD)?
+    BAcurve2d.LastParameter() : BAcurve2d.FirstParameter();
+  theNextPoint = BAcurve2d.Value(ParamOfNextPoint);
+}
+
+//=======================================================================
+//function : TransformPCurves
+//purpose  : auxilary
+//=======================================================================
+static void TransformPCurves(const TopoDS_Face& theRefFace,
+                             const TopoDS_Face& theFace,
+                             TopTools_MapOfShape& theMapEdgesWithTemporaryPCurves)
+{
+  BRepAdaptor_Surface BAsurf(theFace, Standard_False);
+
+  Standard_Real Uperiod = 0., Vperiod = 0.;
+  Handle(Geom_Surface) RefSurf = BRep_Tool::Surface(theRefFace);
+  if (RefSurf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface)))
+    RefSurf = (Handle(Geom_RectangularTrimmedSurface)::DownCast(RefSurf))->BasisSurface();
+  if (RefSurf->IsUPeriodic())
+    Uperiod = RefSurf->UPeriod();
+  if (RefSurf->IsVPeriodic())
+    Vperiod = RefSurf->VPeriod();
+
+  GeomAdaptor_Surface RefGAsurf(RefSurf);
+
+  Standard_Real Ufirst = BAsurf.FirstUParameter(),
+    Ulast = BAsurf.LastUParameter(),
+    Vfirst = BAsurf.FirstVParameter(),
+    Vlast = BAsurf.LastVParameter();
+
+  Standard_Real u_mid = (Ufirst + Ulast)/2, v_mid = (Vfirst + Vlast)/2;
+  gp_Pnt MidPoint = BAsurf.Value(u_mid, v_mid);
+  Extrema_ExtPS ProjPS(MidPoint, RefGAsurf,
+                       Precision::PConfusion(), Precision::PConfusion());
+  Standard_Integer indmin = 1;
+  for (Standard_Integer iext = 2; iext <= ProjPS.NbExt(); iext++)
+    if (ProjPS.SquareDistance(iext) < ProjPS.SquareDistance(indmin))
+      indmin = iext;
+  
+  Standard_Real uu, vv;
+  ProjPS.Point(indmin).Parameter(uu,vv);
+  //Check uu and vv
+  if (Abs(u_mid + Uperiod - uu) <= Precision::PConfusion())
+    uu = u_mid;
+  if (Abs(u_mid - uu) <= Precision::PConfusion())
+    uu = u_mid;
+  if (Abs(v_mid + Vperiod - vv) <= Precision::PConfusion())
+    vv = v_mid;
+  if (Abs(v_mid - vv) <= Precision::PConfusion())
+    vv = v_mid;
+  gp_Vec2d Translation(uu - u_mid, vv - v_mid);
+
+  Standard_Boolean X_Reverse = Standard_False, Y_Reverse = Standard_False;
+  Standard_Real u_dx, v_dx, u_dy, v_dy;
+
+  Standard_Real Delta = (Precision::IsInfinite(Ufirst) || Precision::IsInfinite(Ulast))?
+    1. : (Ulast - Ufirst)/4;
+  Standard_Real Offset = (Uperiod == 0.)? Delta : Min(Uperiod/8, Delta);
+  Standard_Real u1 = u_mid + Offset, v1 = v_mid;
+  gp_Pnt DX = BAsurf.Value(u1, v1);
+  ProjPS.Perform(DX);
+  indmin = 1;
+  for (Standard_Integer iext = 2; iext <= ProjPS.NbExt(); iext++)
+    if (ProjPS.SquareDistance(iext) < ProjPS.SquareDistance(indmin))
+      indmin = iext;
+
+  ProjPS.Point(indmin).Parameter(u_dx, v_dx);
+  if (Uperiod != 0. &&
+      Abs(uu - u_dx) > Uperiod/2)
+  {
+    if (uu   < Uperiod/2 &&
+        u_dx > Uperiod/2)
+      X_Reverse = Standard_True;
+  }
+  else if (u_dx < uu)
+    X_Reverse = Standard_True;
+
+  Delta = (Precision::IsInfinite(Vfirst) || Precision::IsInfinite(Vlast))?
+    1. : (Vlast - Vfirst)/4;
+  Offset = (Vperiod == 0.)? Delta : Min(Vperiod/8, Delta);
+  Standard_Real u2 = u_mid, v2 = v_mid + Offset;
+  gp_Pnt DY = BAsurf.Value(u2, v2);
+  ProjPS.Perform(DY);
+  indmin = 1;
+  for (Standard_Integer iext = 2; iext <= ProjPS.NbExt(); iext++)
+    if (ProjPS.SquareDistance(iext) < ProjPS.SquareDistance(indmin))
+      indmin = iext;
+  
+  ProjPS.Point(indmin).Parameter(u_dy, v_dy);
+  if (Vperiod != 0. &&
+      Abs(vv - v_dy) > Vperiod/2)
+  {
+    if (vv   < Vperiod/2 &&
+        v_dy > Vperiod/2)
+      Y_Reverse = Standard_True;
+  }
+  else if (v_dy < vv)
+    Y_Reverse = Standard_True;
+    
+  gp_Trsf2d aTrsf;
+  if (X_Reverse && Y_Reverse)
+    aTrsf.SetMirror(gp::Origin2d());
+  else if (X_Reverse)
+    aTrsf.SetMirror(gp::OY2d());
+  else if (Y_Reverse)
+    aTrsf.SetMirror(gp::OX2d());
+
+  aTrsf.SetTranslationPart(Translation);
+
+  BRep_Builder BB;
+  TopExp_Explorer Explo(theFace, TopAbs_EDGE);
+  for (; Explo.More(); Explo.Next())
+  {
+    const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
+    if (BRep_Tool::Degenerated(anEdge) &&
+        aTrsf.Form() != gp_Identity)
+      continue;
+    if (BRepTools::IsReallyClosed(anEdge, theFace))
+      continue;
+
+    Standard_Real fpar, lpar;
+    Handle(Geom2d_Curve) PCurveOnRef = BRep_Tool::CurveOnSurface(anEdge, theRefFace, fpar, lpar);
+    if (!PCurveOnRef.IsNull())
+      continue;
+
+    Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, theFace, fpar, lpar);
+    Handle(Geom2d_Curve) aNewPCurve = Handle(Geom2d_Curve)::DownCast(aPCurve->Copy());
+    if (aTrsf.Form() != gp_Identity)
+      aNewPCurve->Transform(aTrsf);
+
+    Standard_Real tmp_first, tmp_last;
+    Handle(Geom2d_Curve) aPCurveOnRefFace = BRep_Tool::CurveOnSurface(anEdge, theRefFace,
+                                                                      tmp_first, tmp_last);
+    if (aPCurveOnRefFace.IsNull())
+      theMapEdgesWithTemporaryPCurves.Add(anEdge);
+    
+    BB.UpdateEdge(anEdge, aNewPCurve, theRefFace, 0.);
+    BB.Range(anEdge, fpar, lpar);
+  }
+}
+                             
+//=======================================================================
+//function : AddPCurves
+//purpose  : auxilary
+//=======================================================================
+static void AddPCurves(const TopTools_SequenceOfShape& theFaces,
+                       const TopoDS_Face&              theRefFace,
+                       TopTools_MapOfShape& theMapEdgesWithTemporaryPCurves)
+{
+  BRepAdaptor_Surface RefBAsurf(theRefFace, Standard_False);
+
+  GeomAbs_SurfaceType aType = RefBAsurf.GetType();
+  if (aType == GeomAbs_Plane)
+    return;
+
+  for (Standard_Integer i = 1; i <= theFaces.Length(); i++)
+  {
+    const TopoDS_Face& aFace = TopoDS::Face(theFaces(i));
+    if (aFace.IsSame(theRefFace))
+      continue;
+
+    TransformPCurves(theRefFace, aFace, theMapEdgesWithTemporaryPCurves);
+  }
+}
 
 //=======================================================================
 //function : AddOrdinaryEdges
@@ -113,14 +771,7 @@ static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
     TopoDS_Shape edge = exp.Current();
     if(aNewEdges.Contains(edge))
-    {
-      //aNewEdges.Remove(edge);
-      TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
-      aNewEdges.RemoveLast();
-      if (aNewEdges.FindIndex(edge) != 0)
-        aNewEdges.Substitute(aNewEdges.FindIndex(edge), LastEdge);
-      /////////////////////////
-    }
+      aNewEdges.RemoveKey(edge);
     else
       aNewEdges.Add(edge);
   }
@@ -132,12 +783,7 @@ static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
     TopoDS_Shape current = edges(i);
     if(aNewEdges.Contains(current)) {
 
-      //aNewEdges.Remove(current);
-      TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
-      aNewEdges.RemoveLast();
-      if (aNewEdges.FindIndex(current) != 0)
-        aNewEdges.Substitute(aNewEdges.FindIndex(current), LastEdge);
-      /////////////////////////
+      aNewEdges.RemoveKey(current);
       edges.Remove(i);
       i--;
 
@@ -148,7 +794,7 @@ static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
     }
   }
 
-  //add edges to the sequemce
+  //add edges to the sequence
   for (i = 1; i <= aNewEdges.Extent(); i++)
     edges.Append(aNewEdges(i));
 
@@ -228,12 +874,57 @@ static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
   return aSurface;
 }
 
+//=======================================================================
+//function : GetNormalToSurface
+//purpose  : Gets the normal to surface by the given parameter on edge.
+//           Returns True if normal was computed.
+//=======================================================================
+static Standard_Boolean GetNormalToSurface(const TopoDS_Face& theFace,
+                                           const TopoDS_Edge& theEdge,
+                                           const Standard_Real theP,
+                                           gp_Dir& theNormal)
+{
+  Standard_Real f, l;
+  // get 2d curve to get point in 2d
+  const Handle(Geom2d_Curve)& aC2d = BRep_Tool::CurveOnSurface(theEdge, theFace, f, l);
+  if (aC2d.IsNull()) {
+    return Standard_False;
+  }
+  //
+  // 2d point
+  gp_Pnt2d aP2d;
+  aC2d->D0(theP, aP2d);
+  //
+  // get D1
+  gp_Vec aDU, aDV;
+  gp_Pnt aP3d;
+  TopLoc_Location aLoc;
+  const Handle(Geom_Surface)& aS = BRep_Tool::Surface(theFace, aLoc);
+  aS->D1(aP2d.X(), aP2d.Y(), aP3d, aDU, aDV);
+  //
+  // compute normal
+  gp_Vec aVNormal = aDU.Crossed(aDV);
+  if (aVNormal.Magnitude() < Precision::Confusion()) {
+    return Standard_False;
+  }
+  //
+  if (theFace.Orientation() == TopAbs_REVERSED) {
+    aVNormal.Reverse();
+  }
+  //
+  aVNormal.Transform(aLoc.Transformation());
+  theNormal = gp_Dir(aVNormal);
+  return Standard_True;
+}
+
 //=======================================================================
 //function : IsSameDomain
 //purpose  : 
 //=======================================================================
 static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
-                                     const TopoDS_Face& aCheckedFace)
+                                     const TopoDS_Face& aCheckedFace,
+                                     const Standard_Real theLinTol,
+                                     const Standard_Real theAngTol)
 {
   //checking the same handles
   TopLoc_Location L1, L2;
@@ -245,9 +936,6 @@ static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
   if (S1 == S2 && L1 == L2)
     return Standard_True;
 
-  // planar and cylindrical cases (IMP 20052)
-  Standard_Real aPrec = Precision::Confusion();
-
   S1 = BRep_Tool::Surface(aFace);
   S2 = BRep_Tool::Surface(aCheckedFace);
 
@@ -260,6 +948,22 @@ static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
 
+  // case of two planar surfaces:
+  // all kinds of surfaces checked, including b-spline and bezier
+  GeomLib_IsPlanarSurface aPlanarityChecker1(S1, theLinTol);
+  if (aPlanarityChecker1.IsPlanar()) {
+    GeomLib_IsPlanarSurface aPlanarityChecker2(S2, theLinTol);
+    if (aPlanarityChecker2.IsPlanar()) {
+      gp_Pln aPln1 = aPlanarityChecker1.Plan();
+      gp_Pln aPln2 = aPlanarityChecker2.Plan();
+
+      if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), theAngTol) &&
+        aPln1.Distance(aPln2) < theLinTol) {
+        return Standard_True;
+      }
+    }
+  }
+
   // case of two elementary surfaces: use OCCT tool
   // elementary surfaces: ConicalSurface, CylindricalSurface,
   //                      Plane, SphericalSurface and ToroidalSurface
@@ -273,33 +977,17 @@ static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
 
     try {
-      IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
+      IntPatch_ImpImpIntersection anIIInt(aGA1, aTT1, aGA2, aTT2, theLinTol, theLinTol);
       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
         return Standard_False;
 
       return anIIInt.TangentFaces();
     }
-    catch (Standard_Failure) {
+    catch (Standard_Failure const&) {
       return Standard_False;
     }
   }
 
-  // case of two planar surfaces:
-  // all kinds of surfaces checked, including b-spline and bezier
-  GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
-  if (aPlanarityChecker1.IsPlanar()) {
-    GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
-    if (aPlanarityChecker2.IsPlanar()) {
-      gp_Pln aPln1 = aPlanarityChecker1.Plan();
-      gp_Pln aPln2 = aPlanarityChecker2.Plan();
-
-      if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(),Precision::Angular()) &&
-          aPln1.Distance(aPln2) < aPrec) {
-        return Standard_True;
-      }
-    }
-  }
-
   // case of two cylindrical surfaces, at least one of which is a swept surface
   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
@@ -309,14 +997,14 @@ static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
   {
     gp_Cylinder aCyl1, aCyl2;
     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
-      if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
+      if (fabs(aCyl1.Radius() - aCyl2.Radius()) < theLinTol) {
         gp_Dir aDir1 = aCyl1.Position().Direction();
         gp_Dir aDir2 = aCyl2.Position().Direction();
         if (aDir1.IsParallel(aDir2, Precision::Angular())) {
           gp_Pnt aLoc1 = aCyl1.Location();
           gp_Pnt aLoc2 = aCyl2.Location();
           gp_Vec aVec12 (aLoc1, aLoc2);
-          if (aVec12.SquareMagnitude() < aPrec*aPrec ||
+          if (aVec12.SquareMagnitude() < theLinTol*theLinTol ||
               aVec12.IsParallel(aDir1, Precision::Angular())) {
             return Standard_True;
           }
@@ -329,38 +1017,17 @@ static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
 }
 
 //=======================================================================
-//function : MovePCurves
+//function : UpdateMapOfShapes
 //purpose  :
 //=======================================================================
-static void MovePCurves(TopoDS_Face& aTarget,
-                        const TopoDS_Face& aSource)
+static void UpdateMapOfShapes(TopTools_MapOfShape& theMapOfShapes,
+                              Handle(ShapeBuild_ReShape)& theContext)
 {
-  BRep_Builder B;
-  for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
-    Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
-                                                  aTarget, Precision::Confusion());
-    sfw->FixReorder();
-    Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
-    sfw->FixEdgeCurves();
-    if(isReoredFailed)
-      continue;
-
-    sfw->FixShifted();
-    sfw->FixDegenerated();
-
-    // remove degenerated edges from not degenerated points
-    ShapeAnalysis_Edge sae;
-    Handle(ShapeExtend_WireData) sewd = sfw->WireData();
-    for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
-      TopoDS_Edge E = sewd->Edge(i);
-      if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
-        sewd->Remove(i);
-        i--;
-      }
-    }
-
-    TopoDS_Wire ResWire = sfw->Wire();
-    B.Add(aTarget,ResWire);
+  for (TopTools_MapIteratorOfMapOfShape it(theMapOfShapes); it.More(); it.Next()) {
+    const TopoDS_Shape& aShape = it.Value();
+    TopoDS_Shape aContextShape = theContext->Apply(aShape);
+    if (!aContextShape.IsSame(aShape))
+      theMapOfShapes.Add(aContextShape);
   }
 }
 
@@ -376,24 +1043,21 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
   Standard_Integer i, j;
 
   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
-  //TColGeom2d_SequenceOfCurve PCurveSeq;
   TColGeom_SequenceOfSurface SurfSeq;
-  //TopTools_SequenceOfShape LocSeq;
+  NCollection_Sequence<TopLoc_Location> LocSeq;
   
-  BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
-  for (; itr.More(); itr.Next())
+  for (int aCurveIndex = 0;; aCurveIndex++)
   {
-    Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
-    if (CurveRep->IsCurveOnSurface())
-    {
-      //PCurveSeq.Append(CurveRep->PCurve());
-      SurfSeq.Append(CurveRep->Surface());
-      /*
-      TopoDS_Shape aLocShape;
-      aLocShape.Location(CurveRep->Location());
-      LocSeq.Append(aLocShape);
-      */
-    }
+    Handle(Geom2d_Curve) aCurve;
+    Handle(Geom_Surface) aSurface;
+    TopLoc_Location aLocation;
+    Standard_Real aFirst, aLast;
+    BRep_Tool::CurveOnSurface (FirstEdge, aCurve, aSurface, aLocation, aFirst, aLast, aCurveIndex);
+    if (aCurve.IsNull())
+      break;
+
+    SurfSeq.Append(aSurface);
+    LocSeq.Append(aLocation);
   }
 
   Standard_Real fpar, lpar;
@@ -442,11 +1106,12 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
   }
   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
+  Standard_Boolean closed_flag = Standard_False;
   GeomConvert::ConcatC1(tab_c3d,
                         tabtolvertex,
                         ArrayOfIndices,
                         concatcurve,
-                        Standard_False,
+                        closed_flag,
                         Precision::Confusion());   //C1 concatenation
   
   if (concatcurve->Length() > 1)
@@ -461,14 +1126,12 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
   
   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
-  TopLoc_Location aLoc;
   for (j = 1; j <= SurfSeq.Length(); j++)
   {
     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
     
     PrevVertex = FirstVertex;
     PrevEdge = FirstEdge;
-    //TopLoc_Location theLoc = LocSeq(j).Location();
     for (i = 1; i <= nb_curve; i++)
     {
       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
@@ -476,12 +1139,10 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
       TopExp::Vertices(anEdge, VF, VL);
       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
 
-      /*
       Handle(Geom2d_Curve) aPCurve =
-        BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
-      */
-      Handle(Geom2d_Curve) aPCurve =
-        BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
+        BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), LocSeq(j), fpar, lpar);
+      if (aPCurve.IsNull())
+        continue;
       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
@@ -492,11 +1153,12 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
     }
     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
+    closed_flag = Standard_False;
     Geom2dConvert::ConcatC1(tab_c2d,
                             tabtolvertex,
                             ArrayOfInd2d,
                             concatc2d,
-                            Standard_False,
+                            closed_flag,
                             Precision::Confusion());   //C1 concatenation
     
     if (concatc2d->Length() > 1)
@@ -519,8 +1181,8 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
   BB.SameParameter(ResEdge, Standard_False);
   for (j = 1; j <= ResPCurves.Length(); j++)
   {
-    BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
-    BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
+    BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), LocSeq(j), MaxTol);
+    BB.Range(ResEdge, SurfSeq(j), LocSeq(j), ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
   }
 
   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
@@ -533,7 +1195,13 @@ static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
 //purpose  : Merges a sequence of edges into one edge if possible
 //=======================================================================
 
-static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, TopoDS_Edge& OutEdge, double Tol, Standard_Boolean ConcatBSplines) 
+static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& theChain,
+                                    const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap,
+                                    TopoDS_Edge& OutEdge, 
+                                    double theAngTol, 
+                                    Standard_Boolean ConcatBSplines,
+                                    Standard_Boolean isSafeInputMode,
+                                    Handle(ShapeBuild_ReShape)& theContext)
 {
   ShapeAnalysis_Edge sae;
   BRep_Builder B;
@@ -543,12 +1211,57 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
   Standard_Boolean IsUnionOfLinesPossible = Standard_True;
   Standard_Boolean IsUnionOfCirclesPossible = Standard_True;
   Handle(Geom_Curve) c3d1, c3d2;
-  for(j=1; j<aChain.Length(); j++) 
+  for(j = 1; j < theChain.Length(); j++) 
   {
-    TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
-    c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
+    TopoDS_Edge edge1 = TopoDS::Edge(theChain.Value(j));
+    TopoDS_Edge edge2 = TopoDS::Edge(theChain.Value(j+1));
+
+    if (BRep_Tool::Degenerated(edge1) &&
+        BRep_Tool::Degenerated(edge2))
+    {
+      //Find the closest points in 2d
+      TopoDS_Edge edgeFirst = TopoDS::Edge(theChain.First());
+      TopoDS_Edge edgeLast  = TopoDS::Edge(theChain.Last());
+      TopoDS_Face CommonFace;
+      Standard_Real MinSqDist;
+      TopAbs_Orientation OrOfE1OnFace, OrOfE2OnFace;
+      Standard_Integer IndOnE1, IndOnE2;
+      gp_Pnt2d PointsOnEdge1 [2], PointsOnEdge2 [2];
+      if (!FindClosestPoints(edgeFirst, edgeLast, theVFmap, CommonFace,
+                             MinSqDist, OrOfE1OnFace, OrOfE2OnFace,
+                             IndOnE1, IndOnE2, PointsOnEdge1, PointsOnEdge2))
+        return Standard_False;
+      
+      //Define indices corresponding to extremities of future edge
+      IndOnE1 = 1 - IndOnE1;
+      IndOnE2 = 1 - IndOnE2;
+
+      //Construct new degenerated edge
+      gp_Pnt2d StartPoint = PointsOnEdge1[IndOnE1];
+      gp_Pnt2d EndPoint   = PointsOnEdge2[IndOnE2];
+      if ((OrOfE1OnFace == TopAbs_FORWARD  && IndOnE1 == 1) ||
+          (OrOfE1OnFace == TopAbs_REVERSED && IndOnE1 == 0))
+      { gp_Pnt2d Tmp = StartPoint; StartPoint = EndPoint; EndPoint = Tmp; }
+      
+      Handle(Geom2d_Line) aLine = GCE2d_MakeLine(StartPoint, EndPoint);
 
-    TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
+      TopoDS_Vertex aVertex = TopExp::FirstVertex(edgeFirst);
+      TopoDS_Vertex StartVertex = aVertex, EndVertex = aVertex;
+      StartVertex.Orientation(TopAbs_FORWARD);
+      EndVertex.Orientation(TopAbs_REVERSED);
+      
+      TopoDS_Edge NewEdge;
+      B.MakeEdge(NewEdge);
+      B.UpdateEdge(NewEdge, aLine, CommonFace, Precision::Confusion());
+      B.Range(NewEdge, 0., StartPoint.Distance(EndPoint));
+      B.Add (NewEdge, StartVertex);
+      B.Add (NewEdge, EndVertex);
+      B.Degenerated(NewEdge, Standard_True);
+      OutEdge = NewEdge;
+      return Standard_True;
+    }
+    
+    c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
     c3d2 = BRep_Tool::Curve(edge2,fp2,lp2);
 
     if(c3d1.IsNull() || c3d2.IsNull()) 
@@ -569,7 +1282,7 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
       gp_Dir Dir1 = L1->Position().Direction();
       gp_Dir Dir2 = L2->Position().Direction();
-      if(!Dir1.IsParallel(Dir2,Tol))  
+      if(!Dir1.IsParallel(Dir2,theAngTol))  
         IsUnionOfLinesPossible = Standard_False;
     }
     else
@@ -591,19 +1304,31 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
   //union of lines is possible
   if (IsUnionOfLinesPossible)
   {
-    TopoDS_Vertex V1 = sae.FirstVertex(TopoDS::Edge(aChain.First()));
-    gp_Pnt PV1 = BRep_Tool::Pnt(V1);
-    TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
-    gp_Pnt PV2 = BRep_Tool::Pnt(V2);
+    TopoDS_Vertex V[2];
+    V[0] = sae.FirstVertex(TopoDS::Edge(theChain.First()));
+    gp_Pnt PV1 = BRep_Tool::Pnt(V[0]);
+    V[1] = sae.LastVertex(TopoDS::Edge(theChain.Last()));
+    gp_Pnt PV2 = BRep_Tool::Pnt(V[1]);
     gp_Vec Vec(PV1, PV2);
+    if (isSafeInputMode) {
+      for (int k = 0; k < 2; k++) {
+        if (!theContext->IsRecorded(V[k])) {
+          TopoDS_Vertex Vcopy = TopoDS::Vertex(V[k].EmptyCopied());
+          theContext->Replace(V[k], Vcopy);
+          V[k] = Vcopy;
+        }
+        else
+          V[k] = TopoDS::Vertex(theContext->Apply(V[k]));
+      }
+    }
     Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
     Standard_Real dist = PV1.Distance(PV2);
     Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
     TopoDS_Edge E;
     B.MakeEdge (E, tc ,Precision::Confusion());
-    B.Add (E,V1);  B.Add (E,V2);
-    B.UpdateVertex(V1, 0., E, 0.);
-    B.UpdateVertex(V2, dist, E, 0.);
+    B.Add (E,V[0]);  B.Add (E,V[1]);
+    B.UpdateVertex(V[0], 0., E, 0.);
+    B.UpdateVertex(V[1], dist, E, 0.);
     OutEdge = E;
     return Standard_True;
   }
@@ -611,7 +1336,7 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
   if (IsUnionOfCirclesPossible)
   {
     double f,l;
-    TopoDS_Edge FE = TopoDS::Edge(aChain.First());
+    TopoDS_Edge FE = TopoDS::Edge(theChain.First());
     Handle(Geom_Curve) c3d = BRep_Tool::Curve(FE,f,l);
 
     while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
@@ -621,10 +1346,11 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
     }
     Handle(Geom_Circle) Cir = Handle(Geom_Circle)::DownCast(c3d);
 
-    TopoDS_Vertex V1 = sae.FirstVertex(FE);
-    TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
+    TopoDS_Vertex V[2];
+    V[0] = sae.FirstVertex(FE);
+    V[1] = sae.LastVertex(TopoDS::Edge(theChain.Last()));
     TopoDS_Edge E;
-    if (V1.IsSame(V2)) {
+    if (V[0].IsSame(V[1])) {
       // closed chain
       BRepAdaptor_Curve adef(FE);
       Handle(Geom_Circle) Cir1;
@@ -641,11 +1367,11 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
       }
       if (Abs(FP) < Precision::PConfusion())
       {
-      B.MakeEdge (E,Cir,Precision::Confusion());
-      B.Add(E,V1);
-      B.Add(E,V2);
-      E.Orientation(FE.Orientation());
-    }
+        B.MakeEdge (E,Cir, Precision::Confusion());
+        B.Add(E,V[0]);
+        B.Add(E,V[1]);
+        E.Orientation(FE.Orientation());
+      }
       else
       {
         GC_MakeCircle MC1 (adef.Value(FP), adef.Value((FP + LP) * 0.5), adef.Value(LP));
@@ -654,13 +1380,24 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
         else
           return Standard_False;
         B.MakeEdge (E, Cir1, Precision::Confusion());
-        B.Add(E,V1);
-        B.Add(E,V2);
+        B.Add(E,V[0]);
+        B.Add(E,V[1]);
       }
     }
     else {
-      gp_Pnt PV1 = BRep_Tool::Pnt(V1);
-      gp_Pnt PV2 = BRep_Tool::Pnt(V2);
+      if (isSafeInputMode) {
+        for (int k = 0; k < 2; k++) {
+          if (!theContext->IsRecorded(V[k])) {
+            TopoDS_Vertex Vcopy = TopoDS::Vertex(V[k].EmptyCopied());
+            theContext->Replace(V[k], Vcopy);
+            V[k] = Vcopy;
+          }
+          else
+            V[k] = TopoDS::Vertex(theContext->Apply(V[k]));
+        }
+      }
+      gp_Pnt PV1 = BRep_Tool::Pnt(V[0]);
+      gp_Pnt PV2 = BRep_Tool::Pnt(V[1]);
       TopoDS_Vertex VM = sae.LastVertex(FE);
       gp_Pnt PVM = BRep_Tool::Pnt(VM);
       GC_MakeCircle MC (PV1,PVM,PV2);
@@ -687,24 +1424,24 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
       if (lpar < fpar) lpar += 2*M_PI;
       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
       B.MakeEdge (E,tc,Precision::Confusion());
-      B.Add(E,V1);
-      B.Add(E,V2);
-      B.UpdateVertex(V1, fpar, E, 0.);
-      B.UpdateVertex(V2, lpar, E, 0.);
+      B.Add(E,V[0]);
+      B.Add(E,V[1]);
+      B.UpdateVertex(V[0], fpar, E, 0.);
+      B.UpdateVertex(V[1], lpar, E, 0.);
     }
     OutEdge = E;
     return Standard_True;
   }
-  if (aChain.Length() > 1 && ConcatBSplines) {
+  if (theChain.Length() > 1 && ConcatBSplines) {
     // second step: union edges with various curves
     // skl for bug 0020052 from Mantis: perform such unions
     // only if curves are bspline or bezier
 
-    TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(aChain.First()));
-    TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(aChain.Last()));
+    TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(theChain.First()));
+    TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(theChain.Last()));
     Standard_Boolean NeedUnion = Standard_True;
-    for(j=1; j<=aChain.Length(); j++) {
-      TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
+    for(j = 1; j <= theChain.Length(); j++) {
+      TopoDS_Edge edge = TopoDS::Edge(theChain.Value(j));
       TopLoc_Location Loc;
       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
       if(c3d.IsNull()) continue;
@@ -720,15 +1457,15 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
     }
     if(NeedUnion) {
 #ifdef OCCT_DEBUG
-      cout<<"can not make analitical union => make approximation"<<endl;
+      std::cout<<"can not make analitical union => make approximation"<<std::endl;
 #endif
-      TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
+      TopoDS_Edge E = GlueEdgesWithPCurves(theChain, VF, VL);
       OutEdge = E;
       return Standard_True;
     }
     else {
 #ifdef OCCT_DEBUG
-      cout<<"can not make approximation for such types of curves"<<endl;
+      std::cout<<"can not make approximation for such types of curves"<<std::endl;
 #endif
       return Standard_False;
     }
@@ -742,11 +1479,38 @@ static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, Topo
 //=======================================================================
 
 static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS_Edge& edge2, 
-                                          double Tol, const TopTools_MapOfShape& DegEdgeVrt)
+                                          double theAngTol, double theLinTol, 
+                                          const TopTools_MapOfShape& AvoidEdgeVrt, const bool theLineDirectionOk,
+                                          const gp_Pnt& theFirstPoint, const gp_Vec& theDirectionVec,
+                                          const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap)
 {
-  TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
-  if (CV.IsNull() || DegEdgeVrt.Contains(CV))
-    return Standard_False;
+  Standard_Boolean IsDegE1 = BRep_Tool::Degenerated(edge1);
+  Standard_Boolean IsDegE2 = BRep_Tool::Degenerated(edge2);
+  
+  if (IsDegE1 && IsDegE2)
+  {
+    //Find connstion point in 2d
+    TopoDS_Face CommonFace;
+    Standard_Real MinSqDist;
+    TopAbs_Orientation OrOfE1OnFace, OrOfE2OnFace;
+    Standard_Integer IndOnE1, IndOnE2;
+    gp_Pnt2d PointsOnEdge1 [2], PointsOnEdge2 [2];
+    if (!FindClosestPoints(edge1, edge2, theVFmap, CommonFace,
+                           MinSqDist, OrOfE1OnFace, OrOfE2OnFace,
+                           IndOnE1, IndOnE2, PointsOnEdge1, PointsOnEdge2))
+      return Standard_False;
+    
+    if (MinSqDist <= Precision::SquareConfusion())
+      return Standard_True;
+    
+    return Standard_False;
+  }
+  else if (IsDegE1 || IsDegE2)
+    return Standard_False;
+  
+  TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
+  if (CV.IsNull() || AvoidEdgeVrt.Contains(CV))
+    return Standard_False;
 
   BRepAdaptor_Curve ade1(edge1);
   BRepAdaptor_Curve ade2(edge2);
@@ -782,9 +1546,57 @@ static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS
     Diff2 = -Diff2;
   }
 
-  if (Diff1.Angle(Diff2) > Tol)
+  if (Diff1.Angle(Diff2) > theAngTol)
+    return Standard_False;
+
+  if (theLineDirectionOk && t2 == GeomAbs_Line)
+  {
+    // Check that the accumulated deflection does not exceed the linear tolerance
+    Standard_Real aLast = (edge2.Orientation() == TopAbs_FORWARD) ?
+      ade2.LastParameter() : ade2.FirstParameter();
+    gp_Vec aCurV(theFirstPoint, ade2.Value(aLast));
+    Standard_Real aDD = theDirectionVec.CrossSquareMagnitude(aCurV);
+    if (aDD > theLinTol*theLinTol)
+      return Standard_False;
+
+    // Check that the accumulated angle does not exceed the angular tolerance.
+    // For symmetry, check the angle between vectors of:
+    // - first edge and resulting curve, and
+    // - the last edge and resulting curve.
+    if (theDirectionVec.Angle(aCurV) > theAngTol || Diff2.Angle(aCurV) > theAngTol)
+      return Standard_False;
+  }
+
+  return Standard_True;
+}
+
+//=======================================================================
+//function : GetLineEdgePoints
+//purpose  : 
+//=======================================================================
+static Standard_Boolean GetLineEdgePoints(const TopoDS_Edge& theInpEdge, gp_Pnt& theFirstPoint, gp_Vec& theDirectionVec)
+{
+  double f, l;
+  Handle(Geom_Curve) aCur = BRep_Tool::Curve(theInpEdge, f, l);
+  if(aCur.IsNull()) 
+    return Standard_False;
+
+  Handle(Geom_TrimmedCurve) aTC = Handle(Geom_TrimmedCurve)::DownCast(aCur);
+  if (!aTC.IsNull())
+    aCur = aTC->BasisCurve();
+
+  if (aCur->DynamicType() != STANDARD_TYPE(Geom_Line))
     return Standard_False;
 
+  if (theInpEdge.Orientation() == TopAbs_REVERSED) {
+    Standard_Real tmp = f;
+    f = l;
+    l = tmp;
+  }
+  theFirstPoint = aCur->Value(f);
+  gp_Pnt aLP = aCur->Value(l);
+  theDirectionVec = aLP.XYZ().Subtracted(theFirstPoint.XYZ());
+  theDirectionVec.Normalize();
   return Standard_True;
 }
 
@@ -796,25 +1608,34 @@ static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS
 
 static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
                             NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
-                            Standard_Boolean IsClosed, double Tol, const TopTools_MapOfShape& DegEdgeVrt )
+                            Standard_Boolean IsClosed, double theAngTol, double theLinTol, 
+                            const TopTools_MapOfShape& AvoidEdgeVrt,
+                            const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap)
 {
   Standard_Boolean isOk = Standard_False;
   TopoDS_Edge edge1, edge2;
 
   SubSequenceOfEdges SubSeq;
-  SubSeq.SeqsEdges.Append(TopoDS::Edge(anInpEdgeSeq(1)));
+  TopoDS_Edge RefEdge = TopoDS::Edge(anInpEdgeSeq(1));
+  SubSeq.SeqsEdges.Append(RefEdge);
   SeqOfSubSeqOfEdges.Append(SubSeq);
 
+  gp_Pnt aFirstPoint;
+  gp_Vec aDirectionVec;
+  Standard_Boolean isLineDirectionOk = GetLineEdgePoints(RefEdge, aFirstPoint, aDirectionVec);  
+  
   for (int i = 1; i < anInpEdgeSeq.Length(); i++)
   {
     edge1 = TopoDS::Edge(anInpEdgeSeq(i));
     edge2 = TopoDS::Edge(anInpEdgeSeq(i+1));
-    isOk = IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt);
+    isOk = IsMergingPossible(edge1, edge2, theAngTol, theLinTol,
+                             AvoidEdgeVrt, isLineDirectionOk, aFirstPoint, aDirectionVec, theVFmap);
     if (!isOk)
     {
       SubSequenceOfEdges aSubSeq;
       aSubSeq.SeqsEdges.Append(edge2);
       SeqOfSubSeqOfEdges.Append(aSubSeq);
+      isLineDirectionOk = GetLineEdgePoints(edge2, aFirstPoint, aDirectionVec);
     }
     else
       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(edge2);
@@ -824,7 +1645,8 @@ static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
   {
     edge1 = TopoDS::Edge(anInpEdgeSeq.Last());
     edge2 = TopoDS::Edge(anInpEdgeSeq.First());
-    if (IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt))
+    if (IsMergingPossible(edge1, edge2, theAngTol, theLinTol,
+                          AvoidEdgeVrt, Standard_False, aFirstPoint, aDirectionVec, theVFmap))
     {
       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(SeqOfSubSeqOfEdges.ChangeFirst().SeqsEdges);
       SeqOfSubSeqOfEdges.Remove(1);
@@ -832,79 +1654,118 @@ static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
   }
 }
 
-
 //=======================================================================
 //function : MergeEdges
 //purpose  : auxilary
 //=======================================================================
-static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
-                                   const Standard_Real Tol,
+static Standard_Boolean MergeEdges(TopTools_SequenceOfShape& SeqEdges,
+                                   const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap,
+                                   const Standard_Real theAngTol,
+                                   const Standard_Real theLinTol,
                                    const Standard_Boolean ConcatBSplines,
+                                   const Standard_Boolean isSafeInputMode,
+                                   Handle(ShapeBuild_ReShape)& theContext,
                                    NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
-                                   const TopTools_MapOfShape& NonMergVrt )
+                                   const TopTools_MapOfShape& NonMergVrt)
 {
-  // make chain for union
-  //BRep_Builder B;
-  ShapeAnalysis_Edge sae;
-  TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
-  TopoDS_Edge LastE = FirstE;
-  TopoDS_Vertex VF = sae.FirstVertex(FirstE);
-  TopoDS_Vertex VL = sae.LastVertex(LastE);
-  TopTools_SequenceOfShape aChain;
-  aChain.Append(FirstE);
-  TColStd_MapOfInteger IndUsedEdges;
-  IndUsedEdges.Add(1);
+  TopTools_IndexedDataMapOfShapeListOfShape aMapVE;
   Standard_Integer j;
   TopTools_MapOfShape VerticesToAvoid;
-  TopTools_SequenceOfShape SeqEdges1;
   for (j = 1; j <= SeqEdges.Length(); j++)
   {
     TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
-    if (BRep_Tool::Degenerated(anEdge))
+    // fill in the map V-E
+    for (TopoDS_Iterator it(anEdge.Oriented(TopAbs_FORWARD)); it.More(); it.Next())
     {
-      TopoDS_Vertex V1, V2;
-      TopExp::Vertices(anEdge, V1, V2);
-      VerticesToAvoid.Add(V1);
-      VerticesToAvoid.Add(V2);
-      continue;
+      TopoDS_Shape aV = it.Value();
+      if (aV.Orientation() == TopAbs_FORWARD || aV.Orientation() == TopAbs_REVERSED)
+      {
+        if (!aMapVE.Contains(aV))
+          aMapVE.Add(aV, TopTools_ListOfShape());
+        aMapVE.ChangeFromKey(aV).Append(anEdge);
+      }
     }
-    SeqEdges1.Append(anEdge);
   }
+  VerticesToAvoid.Unite(NonMergVrt);
 
-  for(j=2; j<=SeqEdges1.Length(); j++) {
-    for(Standard_Integer k=2; k<=SeqEdges1.Length(); k++) {
-      if(IndUsedEdges.Contains(k)) continue;
-      TopoDS_Edge edge = TopoDS::Edge(SeqEdges1.Value(k));
-      TopoDS_Vertex VF2 = sae.FirstVertex(edge);
-      TopoDS_Vertex VL2 = sae.LastVertex(edge);
-      if(VF2.IsSame(VL)) {
-        aChain.Append(edge);
-        LastE = edge;
-        VL = sae.LastVertex(LastE);
-        IndUsedEdges.Add(k);
-      }
-      else if(VL2.IsSame(VF)) {
-        aChain.Prepend(edge);
-        FirstE = edge;
-        VF = sae.FirstVertex(FirstE);
-        IndUsedEdges.Add(k);
+  // do loop while there are unused edges
+  TopTools_MapOfShape aUsedEdges;
+  for (;;)
+  {
+    TopoDS_Edge edge;
+    for(j=1; j <= SeqEdges.Length(); j++)
+    {
+      edge = TopoDS::Edge(SeqEdges.Value(j));
+      if (!aUsedEdges.Contains(edge))
+        break;
+    }
+    if (j > SeqEdges.Length())
+      break; // all edges have been used
+
+    // make chain for unite
+    TopTools_SequenceOfShape aChain;
+    aChain.Append(edge);
+    aUsedEdges.Add(edge);
+    TopoDS_Vertex V[2];
+    TopExp::Vertices(edge, V[0], V[1], Standard_True);
+
+    // connect more edges to the chain in both directions
+    for (j = 0; j < 2; j++)
+    {
+      Standard_Boolean isAdded = Standard_True;
+      while (isAdded)
+      {
+        isAdded = Standard_False;
+        if (V[j].IsNull())
+          break;
+        const TopTools_ListOfShape& aLE = aMapVE.FindFromKey(V[j]);
+        for (TopTools_ListIteratorOfListOfShape itL(aLE); itL.More(); itL.Next())
+        {
+          edge = TopoDS::Edge(itL.Value());
+          if (!aUsedEdges.Contains(edge))
+          {
+            TopoDS_Vertex V2[2];
+            TopExp::Vertices(edge, V2[0], V2[1], Standard_True);
+            // the neighboring edge must have V[j] reversed and located on the opposite end
+            if (V2[1 - j].IsEqual(V[j].Reversed()))
+            {
+              if (j == 0)
+                aChain.Prepend(edge);
+              else
+                aChain.Append(edge);
+              aUsedEdges.Add(edge);
+              V[j] = V2[j];
+              isAdded = Standard_True;
+              break;
+            }
+          }
+        }
       }
     }
-  }
 
-  Standard_Boolean IsClosed = Standard_False;
-  if (VF.IsSame ( VL ))
-    IsClosed = Standard_True;
+    if (aChain.Length() < 2)
+      continue;
 
-  VerticesToAvoid.Unite(NonMergVrt);
-  GenerateSubSeq(aChain, SeqOfSubSeqOfEdges, IsClosed, Tol, VerticesToAvoid);
+    Standard_Boolean IsClosed = Standard_False;
+    if (V[0].IsSame ( V[1] ))
+      IsClosed = Standard_True;
+
+    // split chain by vertices at which merging is not possible
+    NCollection_Sequence<SubSequenceOfEdges> aOneSeq;
+    GenerateSubSeq(aChain, aOneSeq, IsClosed, theAngTol, theLinTol, VerticesToAvoid, theVFmap);
+
+    // put sub-chains in the result
+    SeqOfSubSeqOfEdges.Append(aOneSeq);
+  }
 
   for (int i = 1; i <= SeqOfSubSeqOfEdges.Length(); i++)
   {
     TopoDS_Edge UE;
     if (SeqOfSubSeqOfEdges(i).SeqsEdges.Length() < 2)
       continue;
-    if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, UE, Tol, ConcatBSplines))
+    if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, theVFmap,
+                    UE, theAngTol, 
+                    ConcatBSplines, isSafeInputMode, theContext))
       SeqOfSubSeqOfEdges(i).UnionEdges = UE;
   }
   return Standard_True;
@@ -912,39 +1773,33 @@ static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
 
 //=======================================================================
 //function : MergeSeq
-//purpose  : Tries to unify the sequence of edges with the set of another edges 
-//which lies on the same geometry
+//purpose  : Tries to unify the sequence of edges with the set of
+//           another edges which lies on the same geometry
 //=======================================================================
-
-static Standard_Boolean MergeSeq (const TopTools_SequenceOfShape& SeqEdges,
-                                  const Standard_Real Tol,
+static Standard_Boolean MergeSeq (TopTools_SequenceOfShape& SeqEdges,
+                                  const TopTools_IndexedDataMapOfShapeListOfShape& theVFmap,
+                                  const Standard_Real theAngTol,
+                                  const Standard_Real theLinTol,
                                   const Standard_Boolean ConcatBSplines,
+                                  const Standard_Boolean isSafeInputMode,
                                   Handle(ShapeBuild_ReShape)& theContext,
-                                  TopTools_DataMapOfShapeShape& theOldShapes,
-                                  const TopTools_MapOfShape& nonMergVert,
-                                  const TopTools_DataMapOfShapeShape& NewEdges2OldEdges)
-{ 
+                                  const TopTools_MapOfShape& nonMergVert)
+{
   NCollection_Sequence<SubSequenceOfEdges> SeqOfSubsSeqOfEdges;
-  int k = 1;
-  if ( MergeEdges(SeqEdges, Tol, ConcatBSplines, SeqOfSubsSeqOfEdges, nonMergVert) )
+  if (MergeEdges(SeqEdges, theVFmap, theAngTol, theLinTol, ConcatBSplines, isSafeInputMode,
+                 theContext, SeqOfSubsSeqOfEdges, nonMergVert))
   {
     for (Standard_Integer i = 1; i <= SeqOfSubsSeqOfEdges.Length(); i++ )
     {
       if (SeqOfSubsSeqOfEdges(i).UnionEdges.IsNull())
         continue;
-      theContext->Replace(SeqOfSubsSeqOfEdges(i).SeqsEdges(1), SeqOfSubsSeqOfEdges(i).UnionEdges);
-      k++;
-      for (Standard_Integer j = 2; j <= SeqOfSubsSeqOfEdges(i).SeqsEdges.Length(); j++)
-      {
-        TopoDS_Shape OldEdge = NewEdges2OldEdges(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
-        theOldShapes.Bind(OldEdge, SeqOfSubsSeqOfEdges(i).UnionEdges);
-        theContext->Remove(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
-      }
+
+      theContext->Merge(SeqOfSubsSeqOfEdges(i).SeqsEdges,
+        SeqOfSubsSeqOfEdges(i).UnionEdges);
     }
     return Standard_True;
   }
-  else
-    return Standard_False;
+  return Standard_False;
 }
 
 //=======================================================================
@@ -954,6 +1809,7 @@ static Standard_Boolean MergeSeq (const TopTools_SequenceOfShape& SeqEdges,
 
 static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges, 
                                 const TopTools_IndexedDataMapOfShapeListOfShape& theMapEdgesVertex,
+                                const TopTools_MapOfShape& theMapKeepShape,
                                 TopTools_MapOfShape& theShareVertMap)
 {
   ShapeAnalysis_Edge sae;
@@ -972,11 +1828,7 @@ static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges,
   for (Standard_Integer k = 1; k <= SeqVertexes.Length()/* && !IsSharedVertexPresent*/; k++ )
   {
     const TopTools_ListOfShape& ListEdgesV1 = theMapEdgesVertex.FindFromKey(SeqVertexes(k));
-    TopTools_MapOfShape aMapOfEdges;
-    TopTools_ListIteratorOfListOfShape iter(ListEdgesV1);
-    for (; iter.More(); iter.Next())
-      aMapOfEdges.Add(iter.Value());
-    if (aMapOfEdges.Extent() > 2)
+    if (ListEdgesV1.Extent() > 2 || theMapKeepShape.Contains(SeqVertexes(k)))
       theShareVertMap.Add(SeqVertexes(k));
   }
   //return theShareVertMap.IsEmpty() ? false : true;
@@ -988,10 +1840,14 @@ static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges,
 //=======================================================================
 
 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
-  : myUnifyFaces (Standard_True),
+  : myLinTol(Precision::Confusion()),
+    myAngTol(Precision::Angular()),
+    myUnifyFaces(Standard_True),
     myUnifyEdges (Standard_True),
     myConcatBSplines (Standard_False),
-    myAllowInternal (Standard_False)
+    myAllowInternal (Standard_False),
+    mySafeInputMode(Standard_True),
+    myHistory(new BRepTools_History)
 {
   myContext = new ShapeBuild_ReShape;
 }
@@ -1006,11 +1862,15 @@ ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& a
                                                            const Standard_Boolean UnifyFaces,
                                                            const Standard_Boolean ConcatBSplines)
   : myInitShape (aShape),
-    myUnifyFaces (UnifyFaces),
+    myLinTol(Precision::Confusion()),
+    myAngTol(Precision::Angular()),
+    myUnifyFaces(UnifyFaces),
     myUnifyEdges (UnifyEdges),
     myConcatBSplines (ConcatBSplines),
     myAllowInternal (Standard_False),
-    myShape (aShape)
+    mySafeInputMode (Standard_True),
+    myShape (aShape),
+    myHistory(new BRepTools_History)
 {
   myContext = new ShapeBuild_ReShape;
 }
@@ -1032,7 +1892,8 @@ void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
   myConcatBSplines = ConcatBSplines;
 
   myContext->Clear();
-  myOldShapes.Clear();
+  myKeepShapes.Clear();
+  myHistory->Clear();
 }
 
 //=======================================================================
@@ -1046,33 +1907,36 @@ void ShapeUpgrade_UnifySameDomain::AllowInternalEdges (const Standard_Boolean th
 }
 
 //=======================================================================
-//function : putIntWires
-//purpose  : Add internal wires that are classified inside the face as a subshape,
-//           and remove them from the sequence
+//function : SetSafeInputMode
+//purpose  : 
 //=======================================================================
-static void putIntWires(TopoDS_Shape& theFace, TopTools_SequenceOfShape& theWires)
+
+void ShapeUpgrade_UnifySameDomain::SetSafeInputMode(Standard_Boolean theValue)
 {
-  TopoDS_Face& aFace = TopoDS::Face(theFace);
-  for (Standard_Integer i=1; i <= theWires.Length(); i++)
-  {
-    TopoDS_Shape aWire = theWires(i);
-    gp_Pnt2d aP2d;
-    Standard_Boolean isP2d = Standard_False;
-    for (TopoDS_Iterator it(aWire); it.More() && !isP2d; it.Next())
-    {
-      const TopoDS_Edge& anEdge = TopoDS::Edge(it.Value());
-      Standard_Real aFirst, aLast;
-      Handle(Geom2d_Curve) aC2d = BRep_Tool::CurveOnSurface(anEdge, aFace, aFirst, aLast);
-      aC2d->D0((aFirst + aLast) * 0.5, aP2d);
-      isP2d = Standard_True;
-    }
-    BRepClass_FaceClassifier aClass(aFace, aP2d, Precision::PConfusion());
-    if (aClass.State() == TopAbs_IN)
-    {
-      BRep_Builder().Add(aFace, aWire);
-      theWires.Remove(i);
-      i--;
-    }
+  mySafeInputMode = theValue;
+}
+
+//=======================================================================
+//function : KeepShape
+//purpose  : 
+//=======================================================================
+
+void ShapeUpgrade_UnifySameDomain::KeepShape(const TopoDS_Shape& theShape)
+{
+  if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_VERTEX)
+    myKeepShapes.Add(theShape);
+}
+
+//=======================================================================
+//function : KeepShapes
+//purpose  : 
+//=======================================================================
+
+void ShapeUpgrade_UnifySameDomain::KeepShapes(const TopTools_MapOfShape& theShapes)
+{
+  for (TopTools_MapIteratorOfMapOfShape it(theShapes); it.More(); it.Next()) {
+    if (it.Value().ShapeType() == TopAbs_EDGE || it.Value().ShapeType() == TopAbs_VERTEX)
+      myKeepShapes.Add(it.Value());
   }
 }
 
@@ -1086,444 +1950,789 @@ void ShapeUpgrade_UnifySameDomain::UnifyFaces()
   // creating map of edge faces for the whole shape
   TopTools_IndexedDataMapOfShapeListOfShape aGMapEdgeFaces;
   TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aGMapEdgeFaces);
-
-  // processing each shell
+  
+  // unify faces in each shell separately
   TopExp_Explorer exps;
-  for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next()) {
-    TopoDS_Shell aShell = TopoDS::Shell(exps.Current());
-
-    // creating map of edge faces for the shell
-    TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
-    TopExp::MapShapesAndAncestors(aShell, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
-
-    // map of processed shapes
-    TopTools_MapOfShape aProcessed;
-
-    Standard_Integer NbModif = 0;
-    Standard_Boolean hasFailed = Standard_False;
-    Standard_Real tol = Precision::Confusion();
-
-    // count faces
-    Standard_Integer nbf = 0;
-    TopExp_Explorer exp;
-    TopTools_MapOfShape mapF;
-    for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
-      if (mapF.Add(exp.Current()))
-        nbf++;
-    }
+  for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next())
+    IntUnifyFaces(exps.Current(), aGMapEdgeFaces);
+
+  // gather all faces out of shells in one compound and unify them at once
+  BRep_Builder aBB;
+  TopoDS_Compound aCmp;
+  aBB.MakeCompound(aCmp);
+  Standard_Integer nbf = 0;
+  for (exps.Init(myShape, TopAbs_FACE, TopAbs_SHELL); exps.More(); exps.Next(), nbf++)
+    aBB.Add(aCmp, exps.Current());
+
+  if (nbf > 0)
+    IntUnifyFaces(aCmp, aGMapEdgeFaces);
+  
+  myShape = myContext->Apply(myShape);
+}
+
+//=======================================================================
+//function : SetFixWireModes
+//purpose  : 
+//=======================================================================
 
-    // processing each face
-    mapF.Clear();
-    for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
-      TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
+static void SetFixWireModes(ShapeFix_Face& theSff)
+{
+  Handle(ShapeFix_Wire) aFixWire = theSff.FixWireTool();
+  aFixWire->FixSelfIntersectionMode() = 0;
+  aFixWire->FixNonAdjacentIntersectingEdgesMode() = 0;
+  aFixWire->FixLackingMode() = 0;
+  aFixWire->FixNotchedEdgesMode() = 0;
+  aFixWire->ModifyTopologyMode() = Standard_False;
+  aFixWire->ModifyRemoveLoopMode() = 0;
+  aFixWire->FixGapsByRangesMode() = Standard_False;
+  aFixWire->FixSmallMode() = 0;
+}
 
-      if (aProcessed.Contains(aFace))
-        continue;
+//=======================================================================
+//function : IntUnifyFaces
+//purpose  : 
+//=======================================================================
+
+void ShapeUpgrade_UnifySameDomain::IntUnifyFaces(const TopoDS_Shape& theInpShape,
+   TopTools_IndexedDataMapOfShapeListOfShape& theGMapEdgeFaces)
+{
+  // creating map of edge faces for the shape
+  TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
+  TopExp::MapShapesAndAncestors(theInpShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
+
+  // map of processed shapes
+  TopTools_MapOfShape aProcessed;
+
+  // processing each face
+  TopExp_Explorer exp;
+  for (exp.Init(theInpShape, TopAbs_FACE); exp.More(); exp.Next()) {
+    
+    TopoDS_Face aFace = TopoDS::Face(exp.Current());
+
+    if (aProcessed.Contains(aFace))
+      continue;
 
-      Standard_Integer dummy;
-      TopTools_SequenceOfShape edges;
-      AddOrdinaryEdges(edges,aFace,dummy);
+    // Boundary edges for the new face
+    TopTools_SequenceOfShape edges;
 
-      TopTools_SequenceOfShape faces;
-      faces.Append(aFace);
+    Standard_Integer dummy;
+    AddOrdinaryEdges(edges, aFace, dummy);
 
-      //surface and location to construct result
-      TopLoc_Location aBaseLocation;
-      Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
-      aBaseSurface = ClearRts(aBaseSurface);
+    // Faces to get unified with the current faces
+    TopTools_SequenceOfShape faces;
 
-      // find adjacent faces to union
-      Standard_Integer i;
-      for (i = 1; i <= edges.Length(); i++) {
-        TopoDS_Edge edge = TopoDS::Edge(edges(i));
-        if (BRep_Tool::Degenerated(edge))
+    // Add the current face for unification
+    faces.Append(aFace);
+
+    // surface and location to construct result
+    TopLoc_Location aBaseLocation;
+    Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
+    aBaseSurface = ClearRts(aBaseSurface);
+    TopAbs_Orientation RefFaceOrientation = aFace.Orientation();
+
+    //Take original surface
+    TopoDS_Face RefFace;
+    BRep_Builder BB;
+    BB.MakeFace(RefFace, aBaseSurface, aBaseLocation, 0.);
+    RefFace.Orientation(RefFaceOrientation);
+    TopTools_MapOfShape MapEdgesWithTemporaryPCurves; //map of edges not lying on RefFace
+    //these edges may be updated by temporary pcurves
+    
+    Standard_Real Uperiod = (aBaseSurface->IsUPeriodic())? aBaseSurface->UPeriod() : 0.;
+
+    // find adjacent faces to union
+    Standard_Integer i;
+    for (i = 1; i <= edges.Length(); i++) {
+      TopoDS_Edge edge = TopoDS::Edge(edges(i));
+      if (BRep_Tool::Degenerated(edge))
+        continue;
+
+      // get connectivity of the edge in the global shape
+      const TopTools_ListOfShape& aGList = theGMapEdgeFaces.FindFromKey(edge);
+      if (!myAllowInternal && (aGList.Extent() != 2 || myKeepShapes.Contains(edge))) {
+        // non manifold case is not processed unless myAllowInternal
+        continue;
+      }
+      //
+      // Get the faces connected through the edge in the current shape
+      const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
+      if (aList.Extent() < 2) {
+        continue;
+      }
+
+      // for a planar face create and store pcurve of edge on face
+      // to speed up all operations
+      if (!mySafeInputMode && aBaseSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
+        BRepLib::BuildPCurveForEdgeOnPlane(edge, aFace);
+
+      // get normal of the face to compare it with normals of other faces
+      gp_Dir aDN1;
+      //
+      // take intermediate point on edge to compute the normal
+      Standard_Real f, l;
+      BRep_Tool::Range(edge, f, l);
+      Standard_Real aTMid = (f + l) * .5;
+      //
+      Standard_Boolean bCheckNormals = GetNormalToSurface(aFace, edge, aTMid, aDN1);
+      //
+      // Process the faces
+      TopTools_ListIteratorOfListOfShape anIter(aList);
+      for (; anIter.More(); anIter.Next()) {
+        
+        TopoDS_Face aCheckedFace = TopoDS::Face(anIter.Value());
+        if (aCheckedFace.IsSame(aFace))
           continue;
 
-        // get connectivity of the edge in the global shape
-        const TopTools_ListOfShape& aGList = aGMapEdgeFaces.FindFromKey(edge);
-        if (!myAllowInternal && aGList.Extent() != 2) {
-          // non mainfold case is not processed unless myAllowInternal
+        if (aProcessed.Contains(aCheckedFace))
           continue;
-        }
-        // process faces connected through the edge in the current shell
-        const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
-        TopTools_ListIteratorOfListOfShape anIter(aList);
-        for (; anIter.More(); anIter.Next()) {
-          TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
-          if (anCheckedFace.IsSame(aFace))
-            continue;
-
-          if (aProcessed.Contains(anCheckedFace))
-            continue;
-
-          if (IsSameDomain(aFace,anCheckedFace)) {
-
-            // replacing pcurves
-            TopoDS_Face aMockUpFace;
-            BRep_Builder B;
-            B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
-            MovePCurves(aMockUpFace,anCheckedFace);
-
-            if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
-              // sequence edges is modified
-              i = dummy;
+
+        if (bCheckNormals) {
+          // get normal of checked face using the same parameter on edge
+          gp_Dir aDN2;
+          if (GetNormalToSurface(aCheckedFace, edge, aTMid, aDN2)) {
+            // and check if the adjacent faces are having approximately same normals
+            Standard_Real anAngle = aDN1.Angle(aDN2);
+            if (anAngle > myAngTol) {
+              continue;
             }
+          }
+        }
+        //
+        if (IsSameDomain(aFace,aCheckedFace, myLinTol, myAngTol)) {
 
-            faces.Append(anCheckedFace);
-            aProcessed.Add(anCheckedFace);
-            break;
+          if (AddOrdinaryEdges(edges,aCheckedFace,dummy)) {
+            // sequence edges is modified
+            i = dummy;
           }
+
+          faces.Append(aCheckedFace);
+          aProcessed.Add(aCheckedFace);
+          break;
         }
       }
+    }
 
-      if (faces.Length() > 1) {
-        // fill in the connectivity map for selected faces
-        TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
-        for (i = 1; i <= faces.Length(); i++) {
-          TopExp::MapShapesAndAncestors(faces(i), TopAbs_EDGE, TopAbs_FACE, aMapEF);
+    if (faces.Length() > 1) {
+      //Add correct pcurves for the reference surface to the edges of other faces
+      AddPCurves(faces, RefFace, MapEdgesWithTemporaryPCurves);
+      
+      // fill in the connectivity map for selected faces
+      TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
+      for (i = 1; i <= faces.Length(); i++) {
+        TopExp::MapShapesAndAncestors(faces(i), TopAbs_EDGE, TopAbs_FACE, aMapEF);
+      }
+      // Collect keep edges and multi-connected edges, i.e. edges that are internal to
+      // the set of selected faces and have connections to other faces.
+      TopTools_ListOfShape aKeepEdges;
+      for (i = 1; i <= aMapEF.Extent(); i++) {
+        const TopTools_ListOfShape& aLF = aMapEF(i);
+        if (aLF.Extent() == 2) {
+          const TopoDS_Shape& aE = aMapEF.FindKey(i);
+          const TopTools_ListOfShape& aGLF = theGMapEdgeFaces.FindFromKey(aE);
+          if (aGLF.Extent() > 2 || myKeepShapes.Contains(aE)) {
+            aKeepEdges.Append(aE);
+          }
         }
-
-        // Collect multiconnected edges, i.e. edges that are internal to
-        // the set of selected faces and have connections to other faces.
-        TopTools_ListOfShape aMultEdges;
-        for (i = 1; i <= aMapEF.Extent(); i++) {
-          const TopTools_ListOfShape& aLF = aMapEF(i);
-          if (aLF.Extent() == 2) {
-            const TopoDS_Shape& aE = aMapEF.FindKey(i);
-            const TopTools_ListOfShape& aGLF = aGMapEdgeFaces.FindFromKey(aE);
-            if (aGLF.Extent() > 2) {
-              aMultEdges.Append(aE);
+      } 
+      if (!aKeepEdges.IsEmpty()) {
+        if  (!myAllowInternal) {
+          // Remove from the selection the faces which have no other connect edges 
+          // and contain multi-connected edges and/or keep edges.
+          TopTools_MapOfShape anAvoidFaces;
+          TopTools_ListIteratorOfListOfShape it(aKeepEdges);
+          for (; it.More(); it.Next()) {
+            const TopoDS_Shape& aE = it.Value();
+            const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
+            anAvoidFaces.Add(aLF.First());
+            anAvoidFaces.Add(aLF.Last());
+          }
+          for (i = 1; i <= faces.Length(); i++) {
+            if (anAvoidFaces.Contains(faces(i))) {
+              // update the boundaries of merged area, for that
+              // remove from 'edges' the edges of this face and add to 'edges' 
+              // the edges of this face that were not present in 'edges' before
+              Standard_Boolean hasConnectAnotherFaces = Standard_False;
+              TopExp_Explorer ex(faces(i), TopAbs_EDGE);
+              for (; ex.More() && !hasConnectAnotherFaces; ex.Next()) {
+                TopoDS_Shape aE = ex.Current();
+                const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
+                if (aLF.Extent() > 1) {
+                  for (it.Init(aLF); it.More() && !hasConnectAnotherFaces; it.Next()) {
+                    if (!anAvoidFaces.Contains(it.Value()))
+                      hasConnectAnotherFaces = Standard_True;
+                  }
+                }
+              }
+              if (!hasConnectAnotherFaces) {
+                AddOrdinaryEdges(edges, faces(i), dummy);
+                faces.Remove(i);
+                i--;
+              }
             }
           }
-        }
-        if (!aMultEdges.IsEmpty()) {
-          if (!myAllowInternal) {
-            // Remove from the selection the faces containing multiconnected edges
-            TopTools_MapOfShape anAvoidFaces;
-            TopTools_ListIteratorOfListOfShape it(aMultEdges);
-            for (; it.More(); it.Next()) {
+          // check if the faces with keep edges contained in 
+          // already updated the boundaries of merged area
+          if (!faces.IsEmpty()) {
+            TopTools_MapOfShape aMapFaces;
+            for (i = 1; i <= faces.Length(); i++) {
+              aMapFaces.Add(faces(i));
+            }
+            for (it.Init(aKeepEdges); it.More(); it.Next()) {
               const TopoDS_Shape& aE = it.Value();
               const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
-              anAvoidFaces.Add(aLF.First());
-              anAvoidFaces.Add(aLF.Last());
-            }
-            for (i = 1; i <= faces.Length(); ) {
-              if (anAvoidFaces.Contains(faces(i)))
-                faces.Remove(i);
-              else
-                i++;
+              if (aLF.Extent() < 2)
+                continue;
+              if (aMapFaces.Contains(aLF.First()) && 
+                  aMapFaces.Contains(aLF.Last())) {
+                for (i = 1; i <= faces.Length(); i++) {
+                  if (faces(i).IsEqual(aLF.First()) ||
+                      faces(i).IsEqual(aLF.Last())) {
+                    AddOrdinaryEdges(edges, faces(i), dummy);
+                    faces.Remove(i);
+                    i--;
+                  }
+                }
+              }
             }
           }
-          else {
-            // add multiconnected edges as internal in new face
-            TopTools_ListIteratorOfListOfShape it(aMultEdges);
-            for (; it.More(); it.Next()) {
-              const TopoDS_Shape& aE = it.Value();
-              edges.Append(aE.Oriented(TopAbs_INTERNAL));
+        } //if (!myAllowInternal)
+        else { //internal edges are allowed
+          // add multi-connected and keep edges as internal in new face
+          TopTools_ListIteratorOfListOfShape it(aKeepEdges);
+          for (; it.More(); it.Next()) {
+            const TopoDS_Shape& aE = it.Value();
+            edges.Append(aE.Oriented(TopAbs_INTERNAL));
+          }
+        }
+      } //if (!aKeepEdges.IsEmpty())
+    } //if (faces.Length() > 1)
+
+    TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
+    for (i = 1; i <= faces.Length(); i++)
+      TopExp::MapShapesAndUniqueAncestors(faces(i), TopAbs_EDGE, TopAbs_FACE, aMapEF);
+    
+    //Correct orientation of edges
+    for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+    {
+      const TopoDS_Shape& anEdge = edges(ii);
+      const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(anEdge);
+      if (myAllowInternal &&
+          myKeepShapes.Contains(anEdge) &&
+          aLF.Extent() == 2)
+        edges(ii).Orientation(TopAbs_INTERNAL);
+      
+      if (anEdge.Orientation() != TopAbs_INTERNAL)
+        for (Standard_Integer jj = 1; jj <= faces.Length(); jj++)
+        {
+          const TopoDS_Shape aCurFace = faces(jj);
+          Standard_Boolean found = Standard_False;
+          TopExp_Explorer Explo(aCurFace, TopAbs_EDGE);
+          for (; Explo.More(); Explo.Next())
+          {
+            const TopoDS_Shape& aCurEdge = Explo.Current();
+            if (anEdge.IsSame(aCurEdge))
+            {
+              edges(ii) = aCurEdge;
+              found = Standard_True;
+              break;
             }
           }
+          if (found)
+            break;
         }
+    }
+
+    //Exclude internal edges
+    TopTools_IndexedMapOfShape InternalEdges;
+    Standard_Integer ind_e = 1;
+    while (ind_e <= edges.Length())
+    {
+      const TopoDS_Shape& anEdge = edges(ind_e);
+      if (anEdge.Orientation() == TopAbs_INTERNAL)
+      {
+        InternalEdges.Add(anEdge);
+        edges.Remove(ind_e);
       }
+      else
+        ind_e++;
+    }    
+
+    if (RefFaceOrientation == TopAbs_REVERSED)
+      for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+        edges(ii).Reverse();
+    TopoDS_Face F_RefFace = RefFace;
+    F_RefFace.Orientation(TopAbs_FORWARD);
+    
+    // all faces collected in the sequence. Perform union of faces
+    if (faces.Length() > 1)
+    {
+      Standard_Real CoordTol = Precision::Confusion();
 
-      // all faces collected in the sequence. Perform union of faces
-      if (faces.Length() > 1) {
-        NbModif++;
-        TopoDS_Face aResult;
-        BRep_Builder B;
-        B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
-        Standard_Integer nbWires = 0;
-
-        TopoDS_Face tmpF = TopoDS::Face(myContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
-        // connecting wires
-        while (edges.Length()>0) {
-
-          Standard_Boolean isEdge3d = Standard_False;
-          nbWires++;
-          TopTools_MapOfShape aVertices;
-          TopoDS_Wire aWire;
-          B.MakeWire(aWire);
-
-          TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
-          edges.Remove(1);
-          // collect internal edges in separate wires
-          Standard_Boolean isInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
-
-          isEdge3d |= !BRep_Tool::Degenerated(anEdge);
-          B.Add(aWire,anEdge);
-          TopoDS_Vertex V1,V2;
-          TopExp::Vertices(anEdge,V1,V2);
-          aVertices.Add(V1);
-          aVertices.Add(V2);
-
-          Standard_Boolean isNewFound = Standard_False;
-          do {
-            isNewFound = Standard_False;
-            for(Standard_Integer j = 1; j <= edges.Length(); j++) {
-              anEdge = TopoDS::Edge(edges(j));
-              // check if the current edge orientation corresponds to the first one
-              Standard_Boolean isCurrInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
-              if (isCurrInternal != isInternal)
-                continue;
-              TopExp::Vertices(anEdge,V1,V2);
-              if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
-                isEdge3d |= !BRep_Tool::Degenerated(anEdge);
-                aVertices.Add(V1);
-                aVertices.Add(V2);
-                B.Add(aWire,anEdge);
-                edges.Remove(j);
-                j--;
-                isNewFound = Standard_True;
-              }
-            }
-          } while (isNewFound);
-
-          // sorting any type of edges
-          aWire.Closed (BRep_Tool::IsClosed (aWire));
-          aWire = TopoDS::Wire(myContext->Apply(aWire));
-
-          Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
-          sfw->FixReorder();
-          Standard_Boolean isDegRemoved = Standard_False;
-          if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
-            // clear degenerated edges if at least one with 3d curve exist
-            if(isEdge3d) {
-              Handle(ShapeExtend_WireData) sewd = sfw->WireData();
-              for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
-                TopoDS_Edge E = sewd->Edge(j);
-                if(BRep_Tool::Degenerated(E)) {
-                  sewd->Remove(j);
-                  isDegRemoved = Standard_True;
-                  j--;
-                }
-              }
+      TopTools_IndexedDataMapOfShapeListOfShape VEmap;
+      for (Standard_Integer ind = 1; ind <= edges.Length(); ind++)
+        TopExp::MapShapesAndUniqueAncestors(edges(ind), TopAbs_VERTEX, TopAbs_EDGE, VEmap);
+      
+      //Perform relocating to new U-origin
+      //Define boundaries in 2d space of RefFace
+      if (Uperiod != 0.)
+      {
+        TopTools_MapOfShape edgesMap;
+        CoordTol = ComputeMinEdgeSize(edges, F_RefFace, edgesMap);
+        CoordTol /= 10.;
+        CoordTol = Max(CoordTol, Precision::Confusion());
+
+        //try to find a real seam edge - if it exists, do nothing
+        Standard_Boolean SeamFound = Standard_False;
+        for (Standard_Integer ii = 1; ii <= faces.Length(); ii++)
+        {
+          const TopoDS_Face& face_ii = TopoDS::Face(faces(ii));
+          TopoDS_Wire anOuterWire = BRepTools::OuterWire(face_ii);
+          TopoDS_Iterator itw(anOuterWire);
+          for (; itw.More(); itw.Next())
+          {
+            const TopoDS_Edge& anEdge = TopoDS::Edge(itw.Value());
+            if (BRepTools::IsReallyClosed(anEdge, face_ii))
+            {
+              SeamFound = Standard_True;
+              break;
             }
-            sfw->FixShifted();
-            if(isDegRemoved)
-              sfw->FixDegenerated();
           }
-          TopoDS_Wire aWireFixed = sfw->Wire();
-          //aContext->Replace(aWire,aWireFixed);
-          myContext->Replace(aWire,aWireFixed);
-          //for history
-          /*
-          if (!myOldNewMap.IsBound(aWire))
+        }
+        
+        if (!SeamFound)
+        {
+          //try to find the origin of U in 2d space
+          //so that all the faces are in [origin, origin + Uperiod]
+          Standard_Real Umax;
+          Standard_Integer i_face_max;
+          FindFaceWithMaxUbound(faces, F_RefFace, edgesMap, Umax, i_face_max);
+          
+          TopTools_MapOfShape UsedEdges;
+          NCollection_DataMap<TopoDS_Shape, Handle(Geom2d_Curve)> EdgeNewPCurve;
+
+          //Relocate pcurves to new U-origin
+          RelocatePCurvesToNewUorigin(edges, faces(i_face_max), F_RefFace, CoordTol, Uperiod,
+                                      VEmap, EdgeNewPCurve, UsedEdges);
+
+          //PCurves from unused edges (may be degenerated edges)
+          for (Standard_Integer ind = 1; ind <= edges.Length(); ind++)
           {
-            TopTools_ListOfShape EmptyList;
-            myOldNewMap.Bind(aWire, EmptyList);
+            const TopoDS_Edge& anEdge = TopoDS::Edge(edges(ind));
+            if (!UsedEdges.Contains(anEdge))
+            {
+              Standard_Real fpar, lpar;
+              Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, F_RefFace, fpar, lpar);
+              aPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
+              EdgeNewPCurve.Bind(anEdge, aPCurve);
+            }
           }
-          myOldNewMap(aWire).Clear();
-          myOldNewMap(aWire).Append(aWireFixed);
-          */
-          /////////////
           
-          // add resulting wire
-          if(isEdge3d) {
-            B.Add(aResult,aWireFixed);
+          //Restore VEmap
+          VEmap.Clear();
+          for (Standard_Integer ind = 1; ind <= edges.Length(); ind++)
+            TopExp::MapShapesAndUniqueAncestors(edges(ind), TopAbs_VERTEX, TopAbs_EDGE, VEmap);
+
+          //Find NewUmin and NewUmax
+          Standard_Real NewUmin = RealLast(), NewUmax = RealFirst();
+          for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+          {
+            const Handle(Geom2d_Curve)& aPCurve = EdgeNewPCurve(edges(ii));
+            UpdateBoundaries(aPCurve, aPCurve->FirstParameter(), aPCurve->LastParameter(),
+                             NewUmin, NewUmax);
           }
-          else  {
-            // sorting edges
-            Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
-            Standard_Integer nbEdges = sbwd->NbEdges();
-            // sort degenerated edges and create one edge instead of several ones
-            ShapeAnalysis_WireOrder sawo(Standard_False, 0);
-            ShapeAnalysis_Edge sae;
-            Standard_Integer aLastEdge = nbEdges;
-            for(Standard_Integer j = 1; j <= nbEdges; j++) {
-              Standard_Real f,l;
-              //smh protection on NULL pcurve
-              Handle(Geom2d_Curve) c2d;
-              if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
-                aLastEdge--;
-                continue;
-              }
-              sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
+          
+          if (NewUmax - NewUmin < Uperiod - CoordTol &&
+              !(-Precision::Confusion() < NewUmin && NewUmin < Uperiod+Precision::Confusion() &&
+                -Precision::Confusion() < NewUmax && NewUmax < Uperiod+Precision::Confusion()))
+          {
+            //we can build a face without seam edge:
+            //update the edges with earlier computed relocated pcurves
+            //fitting into (NewUorigin, NewUorigin + Uperiod)
+            Standard_Real umin, umax, vmin, vmax;
+            aBaseSurface->Bounds(umin, umax, vmin, vmax);
+            Standard_Real RestSpaceInU = Uperiod - (NewUmax - NewUmin);
+            Standard_Real NewUorigin = NewUmin - RestSpaceInU/2;
+            if (NewUorigin < umin)
+              NewUorigin = umin;
+            Handle(Geom_Surface) NewSurf;
+            if (NewUorigin == umin)
+              NewSurf = aBaseSurface;
+            else
+              NewSurf = new Geom_RectangularTrimmedSurface(aBaseSurface,
+                                                           NewUorigin, NewUorigin + Uperiod,
+                                                           Standard_True); //trim U
+            TopoDS_Face OldRefFace = RefFace;
+            Handle(Geom2d_Curve) NullPCurve;
+            RefFace.Nullify();
+            BB.MakeFace(RefFace, NewSurf, aBaseLocation, 0.);
+            for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+            {
+              TopoDS_Edge anEdge = TopoDS::Edge(edges(ii));
+              if (MapEdgesWithTemporaryPCurves.Contains(anEdge))
+                BB.UpdateEdge(anEdge, NullPCurve, OldRefFace, 0.);
+              const Handle(Geom2d_Curve)& aPCurve = EdgeNewPCurve(anEdge);
+              BB.UpdateEdge(anEdge, aPCurve, RefFace, 0.);
             }
-            sawo.Perform();
-
-            // constructind one degenerative edge
-            gp_XY aStart, anEnd, tmp;
-            Standard_Integer nbFirst = sawo.Ordered(1);
-            TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
-            ShapeBuild_Edge sbe;
-            TopoDS_Vertex aDummyV;
-            TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
-            sawo.XY(nbFirst,aStart,tmp);
-            sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
-
-            gp_XY aVec = anEnd-aStart;
-            Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
-
-            B.UpdateEdge(E,aLine,tmpF,0.);
-            B.Range(E,tmpF,0.,aVec.Modulus());
-            Handle(Geom_Curve) C3d;
-            B.UpdateEdge(E,C3d,0.);
-            B.Degenerated(E,Standard_True);
-            TopoDS_Wire aW;
-            B.MakeWire(aW);
-            B.Add(aW,E);
-            aW.Closed (Standard_True);
-            B.Add(aResult,aW);
           }
+        } //if (!SeamFound)
+      } //if (Uperiod != 0.)
+      ////////////////////////////////////
+      F_RefFace = RefFace;
+      F_RefFace.Orientation(TopAbs_FORWARD);
+      
+      TopTools_SequenceOfShape NewFaces, NewWires;
+      
+      if (Uperiod == 0)
+      {
+        //Set the "period" for closed non-periodic surface
+        TopLoc_Location aLoc;
+        Handle(Geom_Surface) aSurf = BRep_Tool::Surface(RefFace, aLoc);
+        if (aSurf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface)))
+          aSurf = (Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurf))->BasisSurface();
+        Standard_Real Ufirst, Ulast, Vfirst, Vlast;
+        aSurf->Bounds(Ufirst, Ulast, Vfirst, Vlast);
+        if (aSurf->IsUClosed())
+          Uperiod = Ulast - Ufirst;
+      }
+
+      TopTools_MapOfShape UsedEdges;
+
+      Standard_Real FaceUmin = RealLast();
+      for (Standard_Integer ii = 1; ii <= edges.Length(); ii++)
+      {
+        const TopoDS_Edge& anEdge = TopoDS::Edge(edges(ii));
+        BRepAdaptor_Curve2d aBAcurve(anEdge, F_RefFace);
+        gp_Pnt2d aFirstPoint = aBAcurve.Value(aBAcurve.FirstParameter());
+        gp_Pnt2d aLastPoint  = aBAcurve.Value(aBAcurve.LastParameter());
+        if (aFirstPoint.X() < FaceUmin)
+          FaceUmin = aFirstPoint.X();
+        if (aLastPoint.X() < FaceUmin)
+          FaceUmin = aLastPoint.X();
+      }
+
+      //Building new wires from <edges>
+      //and build faces
+      while (!edges.IsEmpty())
+      {
+        //try to find non-degenerated edge
+        TopoDS_Edge StartEdge = TopoDS::Edge(edges(1));
+        Standard_Integer istart = 1;
+        while (BRep_Tool::Degenerated(StartEdge) &&
+               istart < edges.Length())
+        {
+          istart++;
+          StartEdge = TopoDS::Edge(edges(istart));
         }
 
-        // perform substitution of face
-        //aContext->Replace(aContext->Apply(aFace),aResult);
-        myContext->Replace(myContext->Apply(aFace),aResult);
-        //for history
-        /*
-        if (!myOldNewMap.IsBound(aFace))
+        TopoDS_Wire aNewWire;
+        BB.MakeWire(aNewWire);
+        BB.Add(aNewWire, StartEdge);
+        RemoveEdgeFromMap(StartEdge, VEmap);
+        
+        Standard_Real fpar, lpar;
+        Handle(Geom2d_Curve) StartPCurve = BRep_Tool::CurveOnSurface(StartEdge, F_RefFace, fpar, lpar);
+        TopoDS_Vertex StartVertex, CurVertex;
+        TopExp::Vertices(StartEdge, StartVertex, CurVertex, Standard_True); //with orientation
+        Standard_Real StartParam, CurParam;
+        if (StartEdge.Orientation() == TopAbs_FORWARD)
+        {
+          StartParam = fpar; CurParam = lpar;
+        }
+        else
         {
-          TopTools_ListOfShape EmptyList;
-          myOldNewMap.Bind(aFace, EmptyList);
+          StartParam = lpar; CurParam = fpar;
         }
-        myOldNewMap(aFace).Clear();
-        myOldNewMap(aFace).Append(aResult);
-        */
-        /////////////
-
-        ShapeFix_Face sff (aResult);
-        //Intializing by tolerances
-        sff.SetPrecision(Precision::Confusion());
-        sff.SetMinTolerance(tol);
-        sff.SetMaxTolerance(1.);
-        //Setting modes
-        sff.FixOrientationMode() = 0;
-        //sff.FixWireMode() = 0;
-        //sff.SetContext(aContext);
-        sff.SetContext(myContext);
-        // Applying the fixes
-        sff.Perform();
-        if(sff.Status(ShapeExtend_FAIL))
-        hasFailed = Standard_True;
-
-        // breaking down to several faces
-        //TopoDS_Shape theResult = aContext->Apply(aResult);
-        TopoDS_Shape theResult = myContext->Apply(aResult);
-        for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
-          TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
-          Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
-          grid->SetValue ( 1, 1, aBaseSurface );
-          Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
-          ShapeFix_ComposeShell CompShell;
-          CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
-          //CompShell.SetContext( aContext );
-          CompShell.SetContext( myContext );
-
-          TopTools_SequenceOfShape parts, anIntWires;
-          ShapeFix_SequenceOfWireSegment wires;
-          for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
-            const TopoDS_Wire& aWire = TopoDS::Wire(W_Exp.Current());
-            // check if the wire is ordinary (contains non-internal edges)
-            Standard_Boolean isInternal = Standard_True;
-            for (TopoDS_Iterator it(aWire); it.More() && isInternal; it.Next())
-              isInternal = (it.Value().Orientation() == TopAbs_INTERNAL);
-            if (isInternal)
+        gp_Pnt2d StartPoint = StartPCurve->Value(StartParam);
+        gp_Pnt2d CurPoint   = StartPCurve->Value(CurParam);
+        
+        TopoDS_Edge CurEdge = StartEdge;
+        for (;;) //loop till the end of current new wire
+        {
+          TopoDS_Edge NextEdge;
+          gp_Pnt2d NextPoint;
+          
+          const TopTools_ListOfShape& Elist = VEmap.FindFromKey(CurVertex);
+          TopTools_ListIteratorOfListOfShape itl(Elist);
+          if (Elist.IsEmpty())
+          {
+            if (CurVertex.IsSame(StartVertex))
             {
-              // place internal wire separately
-              anIntWires.Append(aWire);
+              //Points of two vertices coincide in 3d but may be not in 2d
+              if (Uperiod != 0. &&
+                  Abs(StartPoint.X() - CurPoint.X()) > Uperiod/2) //end of parametric space
+              {
+                //<edges> do not contain seams => we must reconstruct the seam up to <NextEdge>
+                gp_Pnt2d StartOfNextEdge;
+                TopoDS_Vertex LastVertexOfSeam;
+                ReconstructMissedSeam(edges, UsedEdges, F_RefFace, CurVertex,
+                                      CurPoint, Uperiod, FaceUmin, CoordTol,
+                                      NextEdge, aNewWire, NextPoint,
+                                      StartOfNextEdge, LastVertexOfSeam, VEmap);
+              }
+              else
+              {
+                break; //end of wire
+              }
             }
+          }
+          
+          if (NextEdge.IsNull())
+          {
+            Standard_Boolean EndOfWire = Standard_False;
+            
+            TopTools_ListOfShape TmpElist, TrueElist;
+            //<TrueElist> will be the list of candidates to become <NextEdge>
+            for (itl.Initialize(Elist); itl.More(); itl.Next())
+            {
+              const TopoDS_Edge& anEdge = TopoDS::Edge(itl.Value());
+              if (UsedEdges.Contains(anEdge))
+                continue;
+              TopoDS_Vertex aFirstVertex = TopExp::FirstVertex(anEdge, Standard_True);
+              if (!aFirstVertex.IsSame(CurVertex))
+                continue;
+              TmpElist.Append(anEdge);
+            }
+            if (TmpElist.Extent() <= 1 ||
+                Uperiod != 0.)
+              TrueElist.Assign(TmpElist);
             else
             {
-              Handle(ShapeExtend_WireData) sbwd =
-                new ShapeExtend_WireData (aWire);
-              ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
-              wires.Append(seg);
+              //we must choose the closest direction - the biggest angle
+              Standard_Real MaxAngle = RealFirst();
+              TopoDS_Edge TrueEdge;
+              Handle(Geom2d_Curve) CurPCurve = BRep_Tool::CurveOnSurface(CurEdge, F_RefFace, fpar, lpar);
+              CurParam = (CurEdge.Orientation() == TopAbs_FORWARD)? lpar : fpar;
+              gp_Vec2d CurDir;
+              CurPCurve->D1(CurParam, CurPoint, CurDir);
+              CurDir.Normalize();
+              if (CurEdge.Orientation() == TopAbs_REVERSED)
+                CurDir.Reverse();
+              for (itl.Initialize(TmpElist); itl.More(); itl.Next())
+              {
+                const TopoDS_Edge& anEdge = TopoDS::Edge(itl.Value());
+                Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, F_RefFace, fpar, lpar);
+                Standard_Real aParam = (anEdge.Orientation() == TopAbs_FORWARD)? fpar : lpar;
+                gp_Pnt2d aPoint;
+                gp_Vec2d aDir;
+                aPCurve->D1(aParam, aPoint, aDir);
+                aDir.Normalize();
+                if (anEdge.Orientation() == TopAbs_REVERSED)
+                  aDir.Reverse();
+                Standard_Real anAngle = CurDir.Angle(aDir);
+                if (anAngle > MaxAngle)
+                {
+                  MaxAngle = anAngle;
+                  TrueEdge = anEdge;
+                }
+              }
+              TrueElist.Append(TrueEdge);
             }
-          }
 
-          CompShell.DispatchWires ( parts,wires );
-          for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
-            ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
-            //aFixOrient.SetContext(aContext);
-            aFixOrient.SetContext(myContext);
-            aFixOrient.FixOrientation();
-            // put internal wires to faces
-            putIntWires(parts(j), anIntWires);
+            //Find next edge in TrueElist
+            for (itl.Initialize(TrueElist); itl.More(); itl.Next())
+            {
+              const TopoDS_Edge& anEdge = TopoDS::Edge(itl.Value());
+              
+              Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(anEdge, F_RefFace, fpar, lpar);
+              Standard_Real aParam = (anEdge.Orientation() == TopAbs_FORWARD)? fpar : lpar;
+              gp_Pnt2d aPoint = aPCurve->Value(aParam);
+              Standard_Real Diff = Abs(aPoint.X() - CurPoint.X());
+              if (Uperiod != 0. &&
+                  Diff > CoordTol &&
+                  Abs(Diff - Uperiod) > CoordTol) //may be is is a deg.vertex
+                continue;
+              
+              //Check: may be <CurPoint> and <aPoint> are on Period from each other
+              if (Uperiod != 0. && Diff > Uperiod/2) //end of parametric space
+              {
+                //<edges> do not contain seams => we must reconstruct the seam up to <NextEdge>
+                gp_Pnt2d StartOfNextEdge;
+                TopoDS_Vertex LastVertexOfSeam;
+                ReconstructMissedSeam(edges, UsedEdges, F_RefFace, CurVertex,
+                                      CurPoint, Uperiod, FaceUmin, CoordTol,
+                                      NextEdge, aNewWire, NextPoint,
+                                      StartOfNextEdge, LastVertexOfSeam, VEmap);
+                
+                //Check: may be it is the end
+                if (LastVertexOfSeam.IsSame(StartVertex) &&
+                    Abs(StartPoint.X() - StartOfNextEdge.X()) < Uperiod/2)
+                  EndOfWire = Standard_True;
+                
+                break;
+              } //if (Uperiod != 0. && Abs(aPoint.X() - CurPoint.X()) > Uperiod/2)
+              else
+              {
+                NextEdge = anEdge;
+                Standard_Real LastParam = (NextEdge.Orientation() == TopAbs_FORWARD)? lpar : fpar;
+                NextPoint = aPCurve->Value(LastParam);
+                break;
+              }
+            } //for (itl.Initialize(TrueElist); itl.More(); itl.Next())
+            
+            if (EndOfWire)
+              break;
           }
-
-          TopoDS_Shape CompRes;
-          if ( parts.Length() !=1 ) {
-            TopoDS_Shell S;
-            B.MakeShell ( S );
-            for ( i=1; i <= parts.Length(); i++ )
-              B.Add ( S, parts(i) );
-            S.Closed (BRep_Tool::IsClosed (S));
-            CompRes = S;
+          
+          if (NextEdge.IsNull())
+          {
+            //throw Standard_ConstructionError("Construction of unified wire failed: no proper edge found");
+            return;
           }
-          else CompRes = parts(1);
-
-          //aContext->Replace(aCurrent,CompRes);
-          myContext->Replace(aCurrent,CompRes);
-          //for history
-          /*
-          if (!myOldNewMap.IsBound(aCurrent))
+          else
           {
-            TopTools_ListOfShape EmptyList;
-            myOldNewMap.Bind(aCurrent, EmptyList);
+            CurPoint = NextPoint;
+            CurEdge = NextEdge;
+            CurVertex = TopExp::LastVertex(CurEdge, Standard_True); //with orientation
+            BB.Add(aNewWire, CurEdge);
+            UsedEdges.Add(CurEdge);
+            RemoveEdgeFromMap(CurEdge, VEmap);
           }
-          myOldNewMap(aCurrent).Clear();
-          myOldNewMap(aCurrent).Append(CompRes);
-          */
-          /////////////
+        } //for (;;)
+        UsedEdges.Add(StartEdge);
+        
+        //Remove used edges from sequence
+        Standard_Integer ind = 1;
+        while (ind <= edges.Length())
+        {
+          if (UsedEdges.Contains(edges(ind)))
+            edges.Remove(ind);
+          else
+            ind++;
         }
-
-        // remove the remaining faces
-        for(i = 2; i <= faces.Length(); i++)
-        { 
-          myOldShapes.Bind(faces(i), theResult);
-          myContext->Remove(faces(i));
+        
+        //add just built wire to current face or save it in the sequence of wires
+        Standard_Boolean EdgeOnBoundOfSurfFound = Standard_False;
+        TopoDS_Iterator itw(aNewWire);
+        for (; itw.More(); itw.Next())
+        {
+          const TopoDS_Edge& anEdge = TopoDS::Edge(itw.Value());
+          if (BRep_Tool::IsClosed(anEdge, RefFace))
+          {
+            EdgeOnBoundOfSurfFound = Standard_True;
+            break;
+          }
         }
-      }
-    } // end processing each face
-
-    //TopoDS_Shape aResult = Shape;
-    if (NbModif > 0 && !hasFailed) {
-      //TopoDS_Shape aResult = aContext->Apply(aShell);
-      TopoDS_Shape aResult = myContext->Apply(aShell);
-
-      ShapeFix_Edge sfe;
-      if (!myContext.IsNull()) sfe.SetContext(myContext);
-      for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
-        TopoDS_Edge E = TopoDS::Edge(exp.Current());
-        sfe.FixVertexTolerance (E);
-        // ptv add fix same parameter
-        sfe.FixSameParameter(E, Precision::Confusion());
+        if (EdgeOnBoundOfSurfFound) //this wire can not be a hole
+        {
+          TopLoc_Location aLoc;
+          Handle(Geom_Surface) aSurf = BRep_Tool::Surface(RefFace, aLoc);
+          TopoDS_Face aResult;
+          BB.MakeFace(aResult,aSurf,aLoc,0);
+          BB.Add(aResult, aNewWire);
+          aResult.Orientation(RefFaceOrientation);
+          NewFaces.Append(aResult);
+        }
+        else //may be this wire is a hole
+        {
+          NewWires.Append(aNewWire);
+        }
+      } //while (!edges.IsEmpty())
+
+      //Build wires from internal edges
+      TopTools_IndexedDataMapOfShapeListOfShape IntVEmap;
+      for (Standard_Integer ii = 1; ii <= InternalEdges.Extent(); ii++)
+        TopExp::MapShapesAndAncestors(InternalEdges(ii), TopAbs_VERTEX, TopAbs_EDGE, IntVEmap);
+      TopTools_SequenceOfShape InternalWires;
+      while (!InternalEdges.IsEmpty())
+      {
+        TopoDS_Edge aFirstEdge = TopoDS::Edge(InternalEdges(1));
+        InternalEdges.RemoveFromIndex(1);
+        TopoDS_Wire anInternalWire;
+        BB.MakeWire(anInternalWire);
+        BB.Add(anInternalWire, aFirstEdge);
+        TopoDS_Edge EndEdges [2];
+        EndEdges[0] = EndEdges[1] = aFirstEdge;
+        TopoDS_Vertex VV [2];
+        TopExp::Vertices(aFirstEdge, VV[0], VV[1]);
+        for (;;)
+        {
+          if (VV[0].IsSame(VV[1])) //closed wire
+            break;
+          Standard_Boolean found = Standard_False;
+          for (Standard_Integer ii = 0; ii < 2; ii++)
+          {
+            const TopTools_ListOfShape& Elist = IntVEmap.FindFromKey(VV[ii]);
+            TopTools_ListIteratorOfListOfShape itl(Elist);
+            for (; itl.More(); itl.Next())
+            {
+              TopoDS_Edge anEdge = TopoDS::Edge(itl.Value());
+              if (anEdge.IsSame(EndEdges[ii]))
+                continue;
+              found = Standard_True;
+              InternalEdges.RemoveKey(anEdge);
+              BB.Add(anInternalWire, anEdge);
+              TopoDS_Vertex V1, V2;
+              TopExp::Vertices(anEdge, V1, V2);
+              VV[ii] = (V1.IsSame(VV[ii]))? V2 : V1;
+              EndEdges[ii] = anEdge;
+              break;
+            }
+          }
+          if (!found) //end of open wire
+            break;
+        }
+        InternalWires.Append(anInternalWire);
       }
 
-      myContext->Replace(aShell, aResult);
-      //for history
-      /*
-      if (!myOldNewMap.IsBound(aShell))
+      //Insert new faces instead of old ones
+      if (NewFaces.IsEmpty())
       {
-        TopTools_ListOfShape EmptyList;
-        myOldNewMap.Bind(aShell, EmptyList);
+        //one face without seam
+        TopLoc_Location aLoc;
+        Handle(Geom_Surface) aSurf = BRep_Tool::Surface(RefFace, aLoc);
+        TopoDS_Face aResult;
+        BB.MakeFace(aResult,aSurf,aLoc,0.);
+        for (Standard_Integer ii = 1; ii <= NewWires.Length(); ii++)
+          BB.Add(aResult, NewWires(ii));
+        for (Standard_Integer ii = 1; ii <= InternalWires.Length(); ii++)
+          BB.Add(aResult, InternalWires(ii));
+        aResult.Orientation(RefFaceOrientation);
+        myContext->Merge(faces, aResult);
       }
-      myOldNewMap(aShell).Clear();
-      myOldNewMap(aShell).Append(aResult);
-      */
-      /////////////
-    }
-    //else
-    {
-      for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
-        TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
-        Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
-        sfw->SetContext(myContext);
-        sfw->SetPrecision(Precision::Confusion());
-        sfw->SetMinTolerance(Precision::Confusion());
-        sfw->SetMaxTolerance(1.);
-        sfw->SetFace(aFace);
-        for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
-          TopoDS_Wire wire = TopoDS::Wire(iter.Value());
-          sfw->Load(wire);
-          sfw->FixReorder();
-          sfw->FixShifted();
+      else if (NewFaces.Length() == 1)
+      {
+        for (Standard_Integer ii = 1; ii <= NewWires.Length(); ii++)
+          BB.Add(NewFaces(1), NewWires(ii));
+        for (Standard_Integer ii = 1; ii <= InternalWires.Length(); ii++)
+          BB.Add(NewFaces(1), InternalWires(ii));
+        myContext->Merge(faces, NewFaces(1));
+      }
+      else
+      {
+        //Insert new wires and internal wires into correspondent faces
+        InsertWiresIntoFaces(NewWires, NewFaces, RefFace);
+        InsertWiresIntoFaces(InternalWires, NewFaces, RefFace);
+        
+        NCollection_Sequence<TopTools_MapOfShape> Emaps;
+        for (Standard_Integer ii = 1; ii <= faces.Length(); ii++)
+        {
+          TopTools_MapOfShape aEmap;
+          TopExp::MapShapes(faces(ii), aEmap);
+          Emaps.Append(aEmap);
+        }
+        for (Standard_Integer ii = 1; ii <= NewFaces.Length(); ii++)
+        {
+          TopTools_SequenceOfShape facesForThisFace;
+          TopTools_MapOfShape UsedFaces;
+          TopExp_Explorer Explo(NewFaces(ii), TopAbs_EDGE);
+          for (; Explo.More(); Explo.Next())
+          {
+            const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
+            if (BRep_Tool::Degenerated(anEdge) ||
+                BRep_Tool::IsClosed(anEdge, RefFace))
+              continue;
+            Standard_Integer jj;
+            for (jj = 1; jj <= Emaps.Length(); jj++)
+              if (Emaps(jj).Contains(anEdge))
+                break;
+            if (UsedFaces.Add(faces(jj)))
+              facesForThisFace.Append(faces(jj));
+          }
+          myContext->Merge(facesForThisFace, NewFaces(ii));
         }
       }
-    }
-  } // end processing each shell
-
-  myShape = myContext->Apply(myShape);
+    } //if (faces.Length() > 1)
+  } // end processing each face
 }
 
 //=======================================================================
@@ -1532,276 +2741,208 @@ void ShapeUpgrade_UnifySameDomain::UnifyFaces()
 //=======================================================================
 void ShapeUpgrade_UnifySameDomain::UnifyEdges()
 {
-  Standard_Real Tol = Precision::Confusion();
-  
-  //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
-  Standard_Real myTolerance = Precision::Confusion();
-  TopoDS_Shape aResult = myContext->Apply(myShape);
-
-  TopTools_IndexedMapOfShape ChangedFaces;
-
+  TopoDS_Shape aRes = myContext->Apply(myShape);
   // creating map of edge faces
   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
-  TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
-  
+  TopExp::MapShapesAndAncestors(aRes, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
   // creating map of vertex edges
   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesVertex;
-  TopExp::MapShapesAndAncestors(myShape, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
-
-  //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
-  TopoDS_Shape aRes = myShape;
-  //aRes = aContext->Apply(aSolid);
-  aRes = myContext->Apply(myShape);
-  
-  TopTools_MapOfShape SharedVert;
-
-  
-  TopTools_IndexedMapOfShape anOldEdges;
-  TopExp::MapShapes(myInitShape, TopAbs_EDGE, anOldEdges);
-
-  TopTools_DataMapOfShapeShape NewEdges2OldEdges;
-  for (int i = 1; i <= anOldEdges.Extent(); i++)
+  TopExp::MapShapesAndUniqueAncestors(aRes, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
+  // creating map of vertex faces
+  TopTools_IndexedDataMapOfShapeListOfShape aVFmap;
+  TopExp::MapShapesAndUniqueAncestors(aRes, TopAbs_VERTEX, TopAbs_FACE, aVFmap);
+
+  if (mySafeInputMode)
+    UpdateMapOfShapes(myKeepShapes, myContext);
+
+  // Sequence of the edges of the shape
+  TopTools_SequenceOfShape aSeqEdges;
+  const Standard_Integer aNbE = aMapEdgeFaces.Extent();
+  for (Standard_Integer i = 1; i <= aNbE; ++i)
+    aSeqEdges.Append(aMapEdgeFaces.FindKey(i));
+
+  // Prepare map of shared vertices (with the number of connected edges greater then 2)
+  TopTools_MapOfShape aSharedVert;
+  CheckSharedVertices(aSeqEdges, aMapEdgesVertex, myKeepShapes, aSharedVert);
+  // Merge the edges avoiding removal of the shared vertices
+  Standard_Boolean isMerged = MergeSeq(aSeqEdges, aVFmap, myAngTol, myLinTol, myConcatBSplines,
+                                       mySafeInputMode, myContext, aSharedVert);
+  // Collect faces to rebuild
+  TopTools_IndexedMapOfShape aChangedFaces;
+  if (isMerged)
   {
-    TopoDS_Shape NewEdge = myContext->Apply(anOldEdges(i));
-    if (!NewEdge.IsNull())
-      NewEdges2OldEdges.Bind(NewEdge, anOldEdges(i));
-  }
-
-  TopExp_Explorer exp;
-  // processing separate wires
-  for (exp.Init(aRes, TopAbs_WIRE, TopAbs_FACE); exp.More(); exp.Next()) 
-  {
-    TopTools_SequenceOfShape SeqEdges;
-    TopExp_Explorer expE(exp.Current(), TopAbs_EDGE);
-    for (; expE.More(); expE.Next())
-      SeqEdges.Append(expE.Current());
-    SharedVert.Clear();
-    CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert); 
-    MergeSeq(SeqEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges);
-  }
-
-  TopTools_DataMapOfShapeShape oldFaces2NewFaces;
-  for (exp.Init(myShape, TopAbs_FACE); exp.More(); exp.Next()) 
-  {
-    const TopoDS_Face& f = TopoDS::Face(exp.Current());
-    TopoDS_Face NewF = TopoDS::Face(myContext->Apply(f));
-    if (!NewF.IsNull())
-      oldFaces2NewFaces.Bind(f, NewF);
-  }
-
-  // processing each face
-  for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
-    //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
-    TopoDS_Face aFace = TopoDS::Face(myContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
-    TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
-    TopTools_SequenceOfShape aNonSharedEdges;
-    for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
-      TopoDS_Edge edge = TopoDS::Edge(expe.Current());
-      if (!aMapEdgeFaces.Contains(edge)) continue;
-      const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
-      TopTools_ListIteratorOfListOfShape anIter(aList);
-      Standard_Integer NbFacesPerEdge = aList.Extent();
-      for ( ; anIter.More(); anIter.Next()) {
-        TopoDS_Face face = TopoDS::Face(anIter.Value());
-        TopoDS_Face face1 = TopoDS::Face(oldFaces2NewFaces(anIter.Value()));
-        if (face1.IsSame(aFace) && NbFacesPerEdge != 1)
-          continue;
-        if (NbFacesPerEdge == 1)
-          //store non-shared edges separately 
-          aNonSharedEdges.Append(edge);
-        else 
-        {
-          if (aMapFacesEdges.Contains(face))
-            aMapFacesEdges.ChangeFromKey(face).Append(edge);
-          else 
-          {
-            TopTools_ListOfShape ListEdges;
-            ListEdges.Append(edge);
-            aMapFacesEdges.Add(face,ListEdges);
-          }
-        }
-      }
-    }
-      
-    for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++)
-    {
-      const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
-      TopTools_SequenceOfShape SeqEdges;
-      TopTools_ListIteratorOfListOfShape anIter(ListEdges);
-      for ( ; anIter.More(); anIter.Next())
-        SeqEdges.Append(anIter.Value());
-      if (SeqEdges.Length()==1) 
-        continue;  
-
-      SharedVert.Clear();
-      CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert);
-      //if (!SharedVert.IsEmpty()) 
-      //  continue;
-      if ( MergeSeq(SeqEdges,Tol,myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
-      {
-        //for history
-        /*
-        for (j = 1; j <= SeqEdges.Length(); j++)
-        {
-          if (!myOldNewMap.IsBound(SeqEdges(j)))
-          {
-            TopTools_ListOfShape EmptyList;
-            myOldNewMap.Bind(SeqEdges(j), EmptyList);
-          }
-          myOldNewMap(SeqEdges(j)).Clear();
-          myOldNewMap(SeqEdges(j)).Append(E);
-        }
-        */
-        /////////////
-        
-        TopoDS_Face tmpF = TopoDS::Face(exp.Current());
-        if ( !ChangedFaces.Contains(tmpF) )
-          ChangedFaces.Add(tmpF);
-        tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
-        if ( !ChangedFaces.Contains(tmpF) )
-          ChangedFaces.Add(tmpF);
-      }
-    }
-    
-    if ( aNonSharedEdges.Length() > 1 )
+    for (Standard_Integer i = 1; i <= aNbE; ++i)
     {
-      SharedVert.Clear();
-      CheckSharedVertices(aNonSharedEdges, aMapEdgesVertex, SharedVert); 
-      if ( MergeSeq(aNonSharedEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
+      const TopoDS_Shape& aE = aMapEdgeFaces.FindKey(i);
+      if (myContext->IsRecorded(aE))
       {
-        TopoDS_Face tmpF = TopoDS::Face(exp.Current());
-        if ( !ChangedFaces.Contains(tmpF) )
-          ChangedFaces.Add(tmpF);
+        TopTools_ListIteratorOfListOfShape it(aMapEdgeFaces(i));
+        for (; it.More(); it.Next())
+          aChangedFaces.Add(it.Value());
       }
     }
-
-  } // end processing each face
+  }
 
   // fix changed faces and replace them in the local context
-  for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
-    //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
-    TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
+  Standard_Real aPrec = Precision::Confusion();
+  for (Standard_Integer i = 1; i <= aChangedFaces.Extent(); i++) {
+    TopoDS_Face aFace = TopoDS::Face(myContext->Apply(aChangedFaces.FindKey(i)));
     if (aFace.IsNull())
       continue;
-    Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
-    sff->SetContext(myContext);
-    sff->SetPrecision(myTolerance);
-    sff->SetMinTolerance(myTolerance);
-    sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
-    sff->Perform();
-    TopoDS_Shape aNewFace = sff->Face();
-    //aContext->Replace(aFace,aNewFace);
-    myContext->Replace(aFace,aNewFace);
-    //for history
-    /*
-    if (!myOldNewMap.IsBound(aFace))
+
+    // for a planar face create and store pcurve of edge on face
+    // to speed up all operations; but this is allowed only when non-safe mode in force
+    if (!mySafeInputMode)
     {
-      TopTools_ListOfShape EmptyList;
-      myOldNewMap.Bind(aFace, EmptyList);
+      TopLoc_Location aLoc;
+      Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace, aLoc);
+      aSurface = ClearRts(aSurface);
+      if (aSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
+      {
+        TopTools_ListOfShape aLE;
+        for (TopExp_Explorer anEx(aFace, TopAbs_EDGE); anEx.More(); anEx.Next())
+          aLE.Append(anEx.Current());
+        BRepLib::BuildPCurveForEdgesOnPlane(aLE, aFace);
+      }
     }
-    myOldNewMap(aFace).Clear();
-    myOldNewMap(aFace).Append(aNewFace);
-    */
-    /////////////
+
+    ShapeFix_Face sff(aFace);
+    if (mySafeInputMode)
+      sff.SetContext(myContext);
+    sff.SetPrecision(aPrec);
+    sff.SetMinTolerance(aPrec);
+    sff.SetMaxTolerance(Max(1., aPrec*1000.));
+    sff.FixOrientationMode() = 0;
+    sff.FixAddNaturalBoundMode() = 0;
+    sff.FixIntersectingWiresMode() = 0;
+    sff.FixLoopWiresMode() = 0;
+    sff.FixSplitFaceMode() = 0;
+    sff.FixPeriodicDegeneratedMode() = 0;
+    SetFixWireModes(sff);
+    sff.Perform();
+    TopoDS_Shape aNewFace = sff.Face();
+    myContext->Replace(aFace,aNewFace);
   }
 
-  if (ChangedFaces.Extent() > 0) {
+  if (aChangedFaces.Extent() > 0) {
     // fix changed shell and replace it in the local context
-    //TopoDS_Shape aRes1 = aContext->Apply(aRes);
     TopoDS_Shape aRes1 = myContext->Apply(aRes);
+    Standard_Boolean isChanged = Standard_False;
     TopExp_Explorer expsh;
     for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
       TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
       Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
       sfsh->FixFaceOrientation(aShell);
       TopoDS_Shape aNewShell = sfsh->Shell();
-      //aContext->Replace(aShell,aNewShell);
-      myContext->Replace(aShell,aNewShell);
-      //for history
-      /*
-      if (!myOldNewMap.IsBound(aShell))
-      {
-        TopTools_ListOfShape EmptyList;
-        myOldNewMap.Bind(aShell, EmptyList);
+      if (!aNewShell.IsSame(aShell)) {
+        myContext->Replace(aShell, aNewShell);
+        isChanged = Standard_True;
       }
-      myOldNewMap(aShell).Clear();
-      myOldNewMap(aShell).Append(aNewShell);
-      */
-      /////////////
-    }
-    //TopoDS_Shape aRes2 = aContext->Apply(aRes1);
-    TopoDS_Shape aRes2 = myContext->Apply(aRes1);
-    myContext->Replace(myShape,aRes2);
-    //for history
-    /*
-    if (!myOldNewMap.IsBound(aSolid))
-    {
-      TopTools_ListOfShape EmptyList;
-      myOldNewMap.Bind(aSolid, EmptyList);
     }
-    myOldNewMap(aSolid).Clear();
-    myOldNewMap(aSolid).Append(aRes2);
-    */
-    /////////////
+    if (isChanged)
+      aRes1 = myContext->Apply(aRes1);
+    myContext->Replace(myShape, aRes1);
   }
 
   myShape = myContext->Apply(myShape);
 }
 
-//=======================================================================
-//function : UnifyFacesAndEdges
-//purpose  : 
-//=======================================================================
-
-void ShapeUpgrade_UnifySameDomain::UnifyFacesAndEdges()
-{
-  UnifyFaces();
-  
-  /*
-  ShapeUpgrade_RemoveLocations RemLoc;
-  RemLoc.Remove(myShape);
-  myShape = RemLoc.GetResult();
-  */
-
-  UnifyEdges();
-}
-
 //=======================================================================
 //function : Build
 //purpose  : builds the resulting shape
-//======================================================================
+//=======================================================================
 void ShapeUpgrade_UnifySameDomain::Build() 
 {
-  if (myUnifyFaces && myUnifyEdges)
-    UnifyFacesAndEdges();
-
-  else if (myUnifyEdges)
-    UnifyEdges();
-  else if (myUnifyFaces)
+  if (myUnifyFaces)
     UnifyFaces();
+  if (myUnifyEdges)
+    UnifyEdges();
 
-  //Done();
+  // Fill the history of modifications during the operation
+  FillHistory();
 }
 
 //=======================================================================
-//function : Shape
-//purpose  : give the resulting shape
+//function : FillHistory
+//purpose  : Fill the history of modifications during the operation
 //=======================================================================
-const TopoDS_Shape& ShapeUpgrade_UnifySameDomain::Shape() const
+void ShapeUpgrade_UnifySameDomain::FillHistory()
 {
-  return myShape;
-}
+  if (myHistory.IsNull())
+    // History is not requested
+    return;
+
+  // Only Vertices, Edges and Faces can be modified during unification.
+  // Thus, only these kind of shapes should be checked.
+
+  // Get history from the context.
+  // It contains all modifications of the operation. Some of these
+  // modifications become not relevant and should be filtered.
+  Handle(BRepTools_History) aCtxHistory = myContext->History();
+
+  // Explore the history of the context and fill
+  // the history of UnifySameDomain algorithm
+  Handle(BRepTools_History) aUSDHistory = new BRepTools_History();
+
+  // Map all Vertices, Edges, Faces and Solids in the input shape
+  TopTools_IndexedMapOfShape aMapInputShape;
+  TopExp::MapShapes(myInitShape, TopAbs_VERTEX, aMapInputShape);
+  TopExp::MapShapes(myInitShape, TopAbs_EDGE  , aMapInputShape);
+  TopExp::MapShapes(myInitShape, TopAbs_FACE  , aMapInputShape);
+  TopExp::MapShapes(myInitShape, TopAbs_SOLID , aMapInputShape);
+
+  // Map all Vertices, Edges, Faces and Solids in the result shape
+  TopTools_IndexedMapOfShape aMapResultShapes;
+  TopExp::MapShapes(myShape, TopAbs_VERTEX, aMapResultShapes);
+  TopExp::MapShapes(myShape, TopAbs_EDGE  , aMapResultShapes);
+  TopExp::MapShapes(myShape, TopAbs_FACE  , aMapResultShapes);
+  TopExp::MapShapes(myShape, TopAbs_SOLID , aMapResultShapes);
+
+  // Iterate on all input shapes and get their modifications
+  Standard_Integer i, aNb = aMapInputShape.Extent();
+  for (i = 1; i <= aNb; ++i)
+  {
+    const TopoDS_Shape& aS = aMapInputShape(i);
 
-//=======================================================================
-//function : Generated
-//purpose  : returns the new shape from the old one
-//=======================================================================
-TopoDS_Shape ShapeUpgrade_UnifySameDomain::Generated(const TopoDS_Shape& aShape) const
-{
-  TopoDS_Shape aNewShape = myContext->Apply(aShape);
+    // Check the shape itself to be present in the result
+    if (aMapResultShapes.Contains(aS))
+    {
+      // The shape is present in the result as is, thus has not been modified
+      continue;
+    }
 
-  if (aNewShape.IsNull())
-    aNewShape = myContext->Apply(myOldShapes(aShape));
-  
-  return aNewShape;
+    // Check if the shape has been modified during the operation
+    const TopTools_ListOfShape& aLSImages = aCtxHistory->Modified(aS);
+    if (aLSImages.IsEmpty())
+    {
+      // The shape has not been modified and not present in the result,
+      // thus it has been removed
+      aUSDHistory->Remove(aS);
+      continue;
+    }
+
+    // Check the images of the shape to be present in the result
+    Standard_Boolean bRemoved = Standard_True;
+    TopTools_ListIteratorOfListOfShape aItLSIm(aLSImages);
+    for (; aItLSIm.More(); aItLSIm.Next())
+    {
+      const TopoDS_Shape& aSIm = aItLSIm.Value();
+      if (aMapResultShapes.Contains(aSIm))
+      {
+        if (!aSIm.IsSame(aS))
+          // Image is found in the result, thus the shape has been modified
+          aUSDHistory->AddModified(aS, aSIm);
+        bRemoved = Standard_False;
+      }
+    }
+
+    if (bRemoved)
+    {
+      // No images are found in the result, thus the shape has been removed
+      aUSDHistory->Remove(aS);
+    }
+  }
+
+  // Merge the history of the operation into global history
+  myHistory->Merge(aUSDHistory);
 }