0027772: Foundation Classes - define Standard_Boolean using C++ type "bool" instead...
[occt.git] / src / BRepBuilderAPI / BRepBuilderAPI_Sewing.cxx
old mode 100755 (executable)
new mode 100644 (file)
index 9f41bcf..58dd718
@@ -1,7 +1,19 @@
-// File:        BRepBuilderAPI_Sewing.cxx
-// Created:        Fri Mar 24 09:45:44 1995
-// Author:        Jing Cheng MEI
-//                <mei@junon>
+// Created on: 1995-03-24
+// Created by: Jing Cheng MEI
+// Copyright (c) 1995-1999 Matra Datavision
+// Copyright (c) 1999-2014 OPEN CASCADE SAS
+//
+// This file is part of Open CASCADE Technology software library.
+//
+// This library is free software; you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License version 2.1 as published
+// by the Free Software Foundation, with special exception defined in the file
+// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
+// distribution for complete text of the license and disclaimer of any warranty.
+//
+// Alternatively, this file may be used under the terms of Open CASCADE
+// commercial license or contractual agreement.
+
 // dcl          CCI60011 : Correction of degeneratedSection
 //              Improvement of SameParameter Edge to treat case of failure in BRepLib::SameParameter
 // dcl          Thu Aug 20 09:24:49 1998
@@ -29,7 +41,6 @@
 
 #define TEST 1
 
-#include <BRepBuilderAPI_Sewing.ixx>
 
 #include <Bnd_Box.hxx>
 #include <Bnd_Box2d.hxx>
 #include <BndLib_Add2dCurve.hxx>
 #include <BndLib_Add3dCurve.hxx>
 #include <BRep_Builder.hxx>
+#include <BRep_ListOfPointRepresentation.hxx>
+#include <BRep_PointOnCurve.hxx>
 #include <BRep_Tool.hxx>
+#include <BRep_TVertex.hxx>
+#include <BRepBuilderAPI_BndBoxTreeSelector.hxx>
+#include <BRepBuilderAPI_CellFilter.hxx>
+#include <BRepBuilderAPI_Sewing.hxx>
+#include <BRepBuilderAPI_VertexInspector.hxx>
 #include <BRepLib.hxx>
+#include <BRepTools.hxx>
 #include <BRepTools_Quilt.hxx>
+#include <BRepTools_ReShape.hxx>
 #include <BSplCLib.hxx>
 #include <Extrema_ExtPC.hxx>
 #include <GCPnts_AbscissaPoint.hxx>
 #include <Geom_BSplineCurve.hxx>
 #include <Geom_Curve.hxx>
 #include <Geom_Line.hxx>
+#include <Geom_OffsetSurface.hxx>
+#include <Geom_RectangularTrimmedSurface.hxx>
 #include <Geom_Surface.hxx>
 #include <GeomAdaptor_Curve.hxx>
 #include <GeomAdaptor_Surface.hxx>
 #include <GeomLib.hxx>
 #include <gp_Pnt.hxx>
 #include <gp_Vec.hxx>
-//#include <LocalAnalysis_SurfaceContinuity.hxx>
+#include <Message_ProgressIndicator.hxx>
+#include <Message_ProgressSentry.hxx>
+#include <NCollection_UBTreeFiller.hxx>
 #include <Precision.hxx>
 #include <Standard_ErrorHandler.hxx>
 #include <Standard_Failure.hxx>
+#include <Standard_NoSuchObject.hxx>
+#include <Standard_OutOfRange.hxx>
+#include <Standard_Type.hxx>
 #include <TColgp_Array1OfVec.hxx>
 #include <TColgp_SequenceOfPnt.hxx>
 #include <TColStd_Array1OfInteger.hxx>
 #include <TColStd_Array1OfReal.hxx>
+#include <TColStd_Array2OfReal.hxx>
 #include <TColStd_DataMapIteratorOfDataMapOfIntegerListOfInteger.hxx>
 #include <TColStd_DataMapOfIntegerListOfInteger.hxx>
 #include <TColStd_IndexedMapOfInteger.hxx>
 #include <TColStd_ListIteratorOfListOfInteger.hxx>
 #include <TColStd_ListOfInteger.hxx>
+#include <TColStd_MapIteratorOfMapOfInteger.hxx>
 #include <TColStd_MapOfInteger.hxx>
 #include <TColStd_SequenceOfReal.hxx>
 #include <TopAbs.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopLoc_Location.hxx>
 #include <TopoDS.hxx>
+#include <TopoDS_Compound.hxx>
 #include <TopoDS_Edge.hxx>
+#include <TopoDS_Face.hxx>
 #include <TopoDS_Iterator.hxx>
 #include <TopoDS_Shape.hxx>
+#include <TopoDS_Shell.hxx>
 #include <TopoDS_Vertex.hxx>
 #include <TopoDS_Wire.hxx>
-#include <TopoDS_Shell.hxx>
 #include <TopTools_Array1OfShape.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
 #include <TopTools_MapIteratorOfMapOfShape.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopTools_SequenceOfShape.hxx>
-#include <TopoDS_Compound.hxx>
-#include <TColStd_Array2OfReal.hxx>
-#include <TColStd_MapIteratorOfMapOfInteger.hxx>
-#include <BRepTools.hxx>
-#include <Geom_RectangularTrimmedSurface.hxx>
-#include <Geom_OffsetSurface.hxx>
-#include <BRep_PointOnCurve.hxx>
-#include <BRep_ListOfPointRepresentation.hxx>
-#include <BRep_TVertex.hxx>
-#include <Message_ProgressSentry.hxx>
-#include <BRepBuilderAPI_VertexInspector.hxx>
-#include <BRepBuilderAPI_CellFilter.hxx>
-#include <BRepBuilderAPI_BndBoxTreeSelector.hxx>
-#include <NCollection_UBTreeFiller.hxx>
 
-static void SortBox (const Handle(Bnd_HArray1OfBox) hSetBoxes,
-                    const Bnd_Box& aBox,
-                    TColStd_ListOfInteger& listIndex)
-{
-  Standard_Integer i, nbBoxes = hSetBoxes->Length();
-  for (i = 1; i <= nbBoxes; i++)
-    if (!aBox.IsOut(hSetBoxes->Value(i)))
-      listIndex.Append(i);
-}
+IMPLEMENT_STANDARD_RTTIEXT(BRepBuilderAPI_Sewing,MMgt_TShared)
 
+//#include <LocalAnalysis_SurfaceContinuity.hxx>
 //=======================================================================
 //function : SameRange
 //purpose  : 
 //=======================================================================
-
 Handle(Geom2d_Curve) BRepBuilderAPI_Sewing::SameRange(const Handle(Geom2d_Curve)& CurvePtr,
                                                const Standard_Real FirstOnCurve,
                                                const Standard_Real LastOnCurve,
@@ -141,7 +150,7 @@ Handle(Geom2d_Curve) BRepBuilderAPI_Sewing::SameRange(const Handle(Geom2d_Curve)
                       RequestedFirst,RequestedLast,NewCurvePtr);
   }
   catch (Standard_Failure) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
     cout << "Exception in BRepBuilderAPI_Sewing::SameRange: ";
     Standard_Failure::Caught()->Print(cout); cout << endl;
 #endif
@@ -313,7 +322,7 @@ void BRepBuilderAPI_Sewing::SameParameter(const TopoDS_Edge& edge) const
     BRepLib::SameParameter(edge);
   }
   catch (Standard_Failure) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
     cout << "Exception in BRepBuilderAPI_Sewing::SameParameter: ";
     Standard_Failure::Caught()->Print(cout); cout << endl;
 #endif
@@ -333,7 +342,7 @@ void BRepBuilderAPI_Sewing::SameParameter(const TopoDS_Edge& edge) const
 
 TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Shape& edge,
                                               const TopTools_SequenceOfShape& seqEdges,
-                                              const TColStd_SequenceOfInteger& seqForward,
+                                              const TColStd_SequenceOfBoolean& seqForward,
                                               TopTools_MapOfShape& mapMerged,
                                               const Handle(BRepTools_ReShape)& locReShape)
 {
@@ -396,8 +405,8 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Shape& edge,
       if (locReShape != myReShape) Edge2 = TopoDS::Edge(aTmpShape);
 
       // Calculate relative orientation
-      Standard_Integer Orientation = seqForward(i);
-      if (!isForward) Orientation = (Orientation? 0 : 1);
+      Standard_Boolean Orientation = seqForward(i);
+      if (!isForward) Orientation = !Orientation;
 
       // Retrieve faces information for the second edge
       TopoDS_Shape bnd2 = oedge2;
@@ -490,10 +499,85 @@ static Standard_Boolean findNMVertices(const TopoDS_Edge& theEdge,
   return Standard_True;
 }
 
-static inline Standard_Real ComputeToleranceVertex(const Standard_Real dist, const Standard_Real Tol1, const Standard_Real Tol2)
+static void ComputeToleranceVertex(TopoDS_Vertex theV1, TopoDS_Vertex theV2,
+                                   TopoDS_Vertex& theNewV)
+{
+  Standard_Integer m, n;
+  Standard_Real aR[2], dR, aD, aEps;
+  TopoDS_Vertex aV[2];
+  gp_Pnt aP[2];
+  BRep_Builder aBB;
+  //
+  aEps = RealEpsilon();
+  aV[0] = theV1;
+  aV[1] = theV2;
+  for (m = 0; m < 2; ++m) {
+    aP[m] = BRep_Tool::Pnt(aV[m]);
+    aR[m] = BRep_Tool::Tolerance(aV[m]);
+    }  
+    //
+  m=0; // max R
+  n=1; // min R
+  if (aR[0] < aR[1]) {
+    m=1;
+    n=0;
+  }
+  //
+  dR = aR[m] - aR[n]; // dR >= 0.
+  gp_Vec aVD(aP[m], aP[n]);
+  aD = aVD.Magnitude();
+  //
+  if (aD <= dR || aD < aEps) { 
+    aBB.MakeVertex (theNewV, aP[m], aR[m]);
+  }
+  else {
+    Standard_Real aRr;
+    gp_XYZ aXYZr;
+    gp_Pnt aPr;
+    //
+    aRr = 0.5 * (aR[m] + aR[n] + aD);
+    aXYZr = 0.5 * (aP[m].XYZ() + aP[n].XYZ() - aVD.XYZ() * (dR/aD));
+    aPr.SetXYZ(aXYZr);
+    //
+    aBB.MakeVertex (theNewV, aPr, aRr);
+  }
+  return;
+}
+
+static void ComputeToleranceVertex(TopoDS_Vertex theV1, TopoDS_Vertex theV2,
+                                   TopoDS_Vertex theV3, TopoDS_Vertex& theNewV)
 {
-  return (dist * 0.5 + Tol1 + Tol2);
+  Standard_Real aDi, aDmax;
+  gp_Pnt aCenter;
+  gp_Pnt aP[3];
+  Standard_Real aR[3];
+  TopoDS_Vertex aV[3];
+  gp_XYZ aXYZ(0.,0.,0.);
+  aV[0] = theV1;
+  aV[1] = theV2;
+  aV[2] = theV3;
+  for (Standard_Integer i = 0; i < 3; ++i) {
+    aP[i] = BRep_Tool::Pnt(aV[i]);
+    aR[i] = BRep_Tool::Tolerance(aV[i]);
+    aXYZ = aXYZ + aP[i].XYZ();
+  }
+  //
+  aXYZ.Divide(3.0);
+  aCenter.SetXYZ(aXYZ);
+  //
+  aDmax=-1.;
+  for ( Standard_Integer i = 0; i < 3; ++i) {
+    aDi = aCenter.Distance(aP[i]);
+    aDi += aR[i];
+    if (aDi > aDmax)
+      aDmax = aDi;
+  }
+
+  BRep_Builder aBB;
+  aBB.MakeVertex (theNewV, aCenter, aDmax);
+  return;
 }
+
 TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirst,
                                               const TopoDS_Edge& edgeLast,
                                               const TopTools_ListOfShape& listFacesFirst,
@@ -602,111 +686,54 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirs
     //V21 = TopoDS::Vertex(myReShape->Apply(V21));
     //V22 = TopoDS::Vertex(myReShape->Apply(V22));
 
-    gp_Pnt p11 = BRep_Tool::Pnt(V11);
-    gp_Pnt p12 = BRep_Tool::Pnt(V12);
-    gp_Pnt p21 = BRep_Tool::Pnt(V21); 
-    gp_Pnt p22 = BRep_Tool::Pnt(V22);
-
-    
-
     //Standard_Boolean isRev = Standard_False;
-    gp_Pnt pfirst;
-    Standard_Real Tol1 = 0.;
     if (isClosed1 || isClosed2) {
       // at least one of the edges is closed
       if (isClosed1 && isClosed2) {
         // both edges are closed
-        pfirst.SetXYZ(0.5*(p11.XYZ() + p21.XYZ()));
-        gp_Vec v1 =  p21.XYZ() - p11.XYZ();
-        Standard_Real d1 = v1.Magnitude();
-        Tol1 = ComputeToleranceVertex(d1,BRep_Tool::Tolerance(V11),BRep_Tool::Tolerance(V21));
-        //Tol1 = Max(pfirst.Distance(p11),pfirst.Distance(p21));
+        ComputeToleranceVertex(V11, V21, V1New);
       }
       else if (isClosed1) {
         // only first edge is closed
-        gp_XYZ pt =0.5*(p21.XYZ()+ p22.XYZ());
-        pfirst.SetXYZ(0.5*(p11.XYZ() + pt));
-        gp_Vec v1 =  p22.XYZ() - p21.XYZ();
-        Standard_Real d1 = v1.Magnitude();
-        Tol1= ComputeToleranceVertex(d1,BRep_Tool::Tolerance(V22),BRep_Tool::Tolerance(V21));
-        gp_Vec v2 =  p11.XYZ() - pt;
-        Standard_Real d2 = v2.Magnitude();
-        Tol1= ComputeToleranceVertex(d2,Tol1,BRep_Tool::Tolerance(V11));
-        //Tol1 = Max(pfirst.Distance(p21),pfirst.Distance(p22));
-        //Tol1 = Max(pfirst.Distance(p11),Tol1);
+        ComputeToleranceVertex(V22, V21, V11, V1New);
       }
       else {
         // only second edge is closed
-        gp_XYZ pt = 0.5*(p11.XYZ()+ p12.XYZ());
-        pfirst.SetXYZ(0.5*(p21.XYZ() + pt));
-        gp_Vec v1 =  p11.XYZ() - p12.XYZ();
-        Standard_Real d1 = v1.Magnitude();
-        Tol1 = ComputeToleranceVertex(d1,BRep_Tool::Tolerance(V11),BRep_Tool::Tolerance(V12));
-        gp_Vec v2 =  p21.XYZ() - pt;
-        Standard_Real d2 = v2.Magnitude();
-        Tol1 = ComputeToleranceVertex(d2,Tol1,BRep_Tool::Tolerance(V21));
-        //Tol1 = Max(pfirst.Distance(p11),pfirst.Distance(p12));
-        //Tol1 = Max(pfirst.Distance(p21),Tol1);
+        ComputeToleranceVertex(V11, V12, V21, V1New);
       }
-      aBuilder.MakeVertex(V1New,pfirst,Tol1);
       V2New = V1New;
     }
     else {
       // both edges are open
-      gp_Pnt plast;
-      Standard_Real Tol2 = 0.;
       Standard_Boolean isOldFirst = ( secForward ? V11.IsSame(V21) :  V11.IsSame(V22) );
       Standard_Boolean isOldLast = ( secForward ? V12.IsSame(V22) : V12.IsSame(V21)) ;
       if (secForward) {
         //case if vertices already sewed
         if(!isOldFirst)
         {
-          pfirst.SetXYZ(0.5*(p11.XYZ() + p21.XYZ()));
-          gp_Vec v1 =  p21.XYZ() - p11.XYZ();
-          Standard_Real d1 = v1.Magnitude();
-          Tol1 = ComputeToleranceVertex(d1,BRep_Tool::Tolerance(V11),BRep_Tool::Tolerance(V21));
+          ComputeToleranceVertex(V11, V21, V1New);
         }
         if(!isOldLast)
         {
-          plast.SetXYZ(0.5*(p12.XYZ() + p22.XYZ()));
-
-          gp_Vec v2 =  p22.XYZ() - p12.XYZ();
-          Standard_Real d2 = v2.Magnitude();
-
-          Tol2 = ComputeToleranceVertex(d2,BRep_Tool::Tolerance(V12),BRep_Tool::Tolerance(V22));
+          ComputeToleranceVertex(V12, V22, V2New);
         }
-
       }
       else {
         if(!isOldFirst)
         {
-          pfirst.SetXYZ(0.5*(p11.XYZ() + p22.XYZ()));
-          gp_Vec v1 =  p22.XYZ() - p11.XYZ();
-          Standard_Real d1 = v1.Magnitude();
-          Tol1 = ComputeToleranceVertex(d1,BRep_Tool::Tolerance(V11),BRep_Tool::Tolerance(V22));
+          ComputeToleranceVertex(V11, V22, V1New);
         }
         if(!isOldLast)
         {
-          plast.SetXYZ(0.5*(p12.XYZ() + p21.XYZ()));
-          gp_Vec v2 =  p21.XYZ() - p12.XYZ();
-          Standard_Real d2 = v2.Magnitude();
-          Tol2 = ComputeToleranceVertex(d2,BRep_Tool::Tolerance(V12),BRep_Tool::Tolerance(V21));
+          ComputeToleranceVertex(V12, V21, V2New);
         }
-
       }
-      if(!isOldFirst)
-        aBuilder.MakeVertex(V1New,pfirst,Tol1);
-      else
+      if(isOldFirst)
         V1New = V11;
-       
 
-      if(!isOldLast)
-        aBuilder.MakeVertex(V2New,plast,Tol2);
-      else
+      if(isOldLast)
         V2New = V12;
-
     }
-
     // Add the vertices in the good sense
     TopoDS_Shape anEdge = edge.Oriented(TopAbs_FORWARD);
     TopoDS_Shape aLocalEdge = V1New.Oriented(TopAbs_FORWARD); //(listNode.First()).Oriented(TopAbs_FORWARD);
@@ -723,6 +750,7 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirs
   // Retrieve second PCurves
   TopLoc_Location loc2;
   Handle(Geom_Surface) surf2;
+  
   //Handle(Geom2d_Curve) c2d2, c2d21;
   //  Standard_Real firstOld, lastOld;
 
@@ -730,10 +758,11 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirs
   if (whichSec == 1) itf2.Initialize(listFacesLast);
   else               itf2.Initialize(listFacesFirst);
   Standard_Boolean isResEdge = Standard_False;
+  TopoDS_Face fac2;
   for (; itf2.More(); itf2.Next()) {
     Handle(Geom2d_Curve) c2d2, c2d21;
     Standard_Real firstOld, lastOld;
-    const TopoDS_Face& fac2 = TopoDS::Face(itf2.Value());
+    fac2 = TopoDS::Face(itf2.Value());
 
     surf2 = BRep_Tool::Surface(fac2, loc2);
     Standard_Boolean isSeam2 = ((IsUClosedSurface(surf2,edge2,loc2) || IsVClosedSurface(surf2,edge2,loc2)) &&
@@ -790,6 +819,7 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirs
 
       TopLoc_Location loc1;
       Handle(Geom_Surface) surf1 = BRep_Tool::Surface(fac1, loc1);
+      
       Standard_Real first2d, last2d;
       Standard_Boolean isSeam1 = ((IsUClosedSurface(surf1,edge1,loc1) || IsVClosedSurface(surf1,edge1,loc1)) &&
         BRep_Tool::IsClosed(TopoDS::Edge(edge1),fac1));
@@ -863,56 +893,85 @@ TopoDS_Edge BRepBuilderAPI_Sewing::SameParameterEdge(const TopoDS_Edge& edgeFirs
 
     }
   }
-  if(isResEdge)
-    // Try to make the edge sameparameter
-    SameParameter(edge);
-
-  //  Standard_Real tolReached = BRep_Tool::Tolerance(edge);
-  //if (!BRep_Tool::SameParameter(edge)) return edge; //gka ????????
+  Standard_Real tolReached = Precision::Infinite();
+  Standard_Boolean isSamePar = Standard_False; 
+  try
+  {
+    if( isResEdge)
+      SameParameter(edge);
+    
 
-  if (firstCall && (!BRep_Tool::SameParameter(edge) || !isResEdge)) {
+    if( BRep_Tool::SameParameter(edge))
+    {
+      isSamePar = Standard_True;
+      tolReached = BRep_Tool::Tolerance(edge);
+    }
+  }
+  
+  catch(Standard_Failure)
+  {
+    isSamePar = Standard_False;
+  }
+  if (firstCall && ( !isResEdge || !isSamePar || tolReached > myTolerance)) {
     Standard_Integer whichSecn = whichSec;
     // Try to merge on the second section
-    Standard_Boolean second_ok = Standard_True;
+    Standard_Boolean second_ok = Standard_False;
     TopoDS_Edge s_edge = SameParameterEdge(edgeFirst,edgeLast,listFacesFirst,listFacesLast,
       secForward,whichSecn,Standard_False);
-    //if (s_edge.IsNull()) return s_edge; // gka version for free edges
-    if (s_edge.IsNull()) second_ok = Standard_False;
-    else if (!BRep_Tool::SameParameter(s_edge)) second_ok = Standard_False;
-    else {
-      edge = s_edge;
-      whichSec = whichSecn;
+    if( !s_edge.IsNull())
+    {
+      Standard_Real tolReached_2  = BRep_Tool::Tolerance(s_edge);
+      second_ok = ( BRep_Tool::SameParameter(s_edge) && tolReached_2 < tolReached );
+      if( second_ok)
+      {
+        edge = s_edge;
+        whichSec = whichSecn;
+        tolReached = tolReached_2;
+      }
     }
 
-    if (!second_ok) {
+    if (!second_ok && !edge.IsNull()) {
 
       GeomAdaptor_Curve c3dAdapt(c3d);
 
       // Discretize edge curve
-      Standard_Integer i, j, nbp = 15;
-      Standard_Real deltaT = (last3d - first3d) / (nbp 1);
+      Standard_Integer i, j, nbp = 23;
+      Standard_Real deltaT = (last3d - first3d) / (nbp -1);
       TColgp_Array1OfPnt c3dpnt(1,nbp);
-      for (i = 1; i <= nbp; i++) c3dpnt(i) = c3dAdapt.Value(first3d + i*deltaT);
+      for (i = 1; i <= nbp; i++) 
+        c3dpnt(i) = c3dAdapt.Value(first3d + (i-1)*deltaT);
 
-      Standard_Real u, v, dist, maxTol = -1.0;
+      Standard_Real dist = 0., maxTol = -1.0;
       Standard_Boolean more = Standard_True;
 
       for (j = 1; more; j++) {
         Handle(Geom2d_Curve) c2d2;
         BRep_Tool::CurveOnSurface(edge, c2d2, surf2, loc2, first, last, j);
+            
         more = !c2d2.IsNull();
         if (more) {
+          Handle(Geom_Surface) aS = surf2;
+          if(!loc2.IsIdentity())
+            aS = Handle(Geom_Surface)::DownCast(surf2->Transformed ( loc2 ));
 
-          deltaT = (last - first) / (nbp + 1);
+          Standard_Real dist2 = 0.;
+          deltaT = (last - first) / (nbp - 1);
           for (i = 1; i <= nbp; i++) {
-            c2d2->Value(first + i*deltaT).Coord(u,v);
-            dist = surf2->Value(u,v).Distance(c3dpnt(i));
-            if (dist > maxTol) maxTol = dist;
+            gp_Pnt2d aP2d =  c2d2->Value(first + (i -1)*deltaT);
+            gp_Pnt aP2(0.,0.,0.);
+            aS->D0(aP2d.X(),aP2d.Y(), aP2);
+            gp_Pnt aP1 = c3dpnt(i);
+            dist = aP2.SquareDistance(aP1);
+            if (dist > dist2) 
+              dist2 = dist;
           }
+          maxTol = Max(sqrt(dist2), Precision::Confusion());
         }
       }
-
-      if (maxTol >= 0.) aBuilder.UpdateEdge(edge, maxTol);
+      if(maxTol >= 0. && maxTol < tolReached)
+        aBuilder.UpdateEdge(edge, maxTol);
       aBuilder.SameParameter(edge,Standard_True);
     }
   }
@@ -1031,6 +1090,7 @@ void BRepBuilderAPI_Sewing::EvaluateDistances(TopTools_SequenceOfShape& sequence
     TopLoc_Location loc;
     Standard_Real first, last;
     Handle(Geom_Curve) c3d = BRep_Tool::Curve(sec, loc, first, last);
+    if (c3d.IsNull()) continue;
     if (!loc.IsIdentity()) {
       c3d = Handle(Geom_Curve)::DownCast(c3d->Copy());
       c3d->Transform(loc.Transformation());
@@ -1115,7 +1175,7 @@ void BRepBuilderAPI_Sewing::EvaluateDistances(TopTools_SequenceOfShape& sequence
         ProjectPointsOnCurve(ptsRef,c3d,first,last,arrDist,arrPara,arrProj,Standard_False);
       for( j = 1; j <= npt; j++ )
       {
-        if(arrDist(j) < 0. || arrDist(j) > myTolerance)
+        if(arrDist(j) < 0.)
           continue;
         if(dist < arrDist(j))
           dist = arrDist(j);
@@ -1275,7 +1335,7 @@ Standard_Boolean BRepBuilderAPI_Sewing::IsMergedClosed(const TopoDS_Edge& Edge1,
 
 void BRepBuilderAPI_Sewing::AnalysisNearestEdges(const TopTools_SequenceOfShape& sequenceSec,
                                                  TColStd_SequenceOfInteger& seqIndCandidate,
-                                                 TColStd_SequenceOfInteger& seqOrientations,
+                                                 TColStd_SequenceOfBoolean& seqOrientations,
                                                  const Standard_Boolean evalDist)
 {
 
@@ -1405,7 +1465,7 @@ void BRepBuilderAPI_Sewing::AnalysisNearestEdges(const TopTools_SequenceOfShape&
 Standard_Boolean BRepBuilderAPI_Sewing::FindCandidates(TopTools_SequenceOfShape& seqSections,
                                                        TColStd_IndexedMapOfInteger& mapReference,
                                                        TColStd_SequenceOfInteger& seqCandidates,
-                                                       TColStd_SequenceOfInteger& seqOrientations)
+                                                       TColStd_SequenceOfBoolean& seqOrientations)
 {
   Standard_Integer i, nbSections = seqSections.Length();
   if(nbSections <= 1)
@@ -1439,49 +1499,32 @@ Standard_Boolean BRepBuilderAPI_Sewing::FindCandidates(TopTools_SequenceOfShape&
     }
     else {
       const TopoDS_Edge& Edge2 = TopoDS::Edge(seqSections(i));
-      //gka
-      seqSectionsNew.Append(Edge2);
-      seqCandidatesNew.Append(i);
-      /*TopoDS_Shape bnd = Edge2;
-      if (mySectionBound.IsBound(bnd)) bnd = mySectionBound(bnd);
-      //gka
-      if (myBoundFaces.Contains(bnd)) {
-      Standard_Boolean isOK = Standard_True;
-      TopTools_ListIteratorOfListOfShape itf2(myBoundFaces.FindFromKey(bnd));
-      for (; itf2.More() && isOK; itf2.Next()) {
-      const TopoDS_Face& Face2 = TopoDS::Face(itf2.Value());
-      // Check whether condition is satisfied
-      isOK = !Faces1.Contains(Face2);
-      if (!isOK) isOK = IsMergedClosed(Edge1,Edge2,Face2);
-      }
-      if (isOK) {
       seqSectionsNew.Append(Edge2);
       seqCandidatesNew.Append(i);
-      }
-      }*/
     }
   }
 
   Standard_Integer nbSectionsNew = seqSectionsNew.Length();
   if (nbSectionsNew > 1) {
-
+    
     // Evaluate distances between reference and other sections
     TColStd_Array1OfBoolean arrForward(1,nbSectionsNew);
     TColStd_Array1OfReal arrDistance(1,nbSectionsNew);
     TColStd_Array1OfReal arrLen(1,nbSectionsNew);
     TColStd_Array1OfReal arrMinDist(1,nbSectionsNew);
     EvaluateDistances(seqSectionsNew,arrForward,arrDistance,arrLen,arrMinDist,1);
-
+    
     // Fill sequence of candidate indices sorted by distance
     for (i = 2; i <= nbSectionsNew; i++) {
-      if (arrDistance(i) >= 0.0 && arrLen(i) > myMinTolerance) {
+      Standard_Real aMaxDist = arrDistance(i);
+      if (aMaxDist >= 0.0 && aMaxDist <= myTolerance &&  arrLen(i) > myMinTolerance) {
+        
         // Reference section is connected to section #i
         Standard_Boolean isInserted = Standard_False;
-        Standard_Integer j, ori = (arrForward(i)? 1 : 0);
-        for (j = 1; (j <= seqCandidates.Length()) && !isInserted; j++) {
-          Standard_Integer aInd = seqCandidates.Value(j);//debug
+        Standard_Boolean ori = arrForward(i);
+        for (Standard_Integer j = 1; (j <= seqCandidates.Length()) && !isInserted; j++) {
           Standard_Real aDelta = arrDistance(i) - arrDistance(seqCandidates.Value(j));
-          //if (arrDistance(i) <= arrDistance(seqCandidates.Value(j))) {
+          
           if( aDelta < Precision::Confusion()) {
 
             if(fabs(aDelta) > RealSmall() || 
@@ -1499,21 +1542,25 @@ Standard_Boolean BRepBuilderAPI_Sewing::FindCandidates(TopTools_SequenceOfShape&
         }
       }
     }
-
-    // Replace candidate indices
+   
     nbCandidates = seqCandidates.Length();
+    if (!nbCandidates) 
+      return Standard_False; // Section has no candidates to merge
+    
+    // Replace candidate indices
+   
     for (i = 1; i <= nbCandidates; i++)
       seqCandidates(i) = seqCandidatesNew(seqCandidates(i));
+    
   }
-  //}
-
+  
   if (!nbCandidates) return Standard_False; // Section has no candidates to merge
 
   if (myNonmanifold && nbCandidates >1) {
     TColStd_SequenceOfInteger seqNewCandidates;
-    TColStd_SequenceOfInteger seqOrientationsNew;
+    TColStd_SequenceOfBoolean seqOrientationsNew;
     seqCandidates.Prepend(1);
-    seqOrientations.Prepend(1);
+    seqOrientations.Prepend(Standard_True);
     for(Standard_Integer k = 1; k <= seqSections.Length() && seqCandidates.Length() > 1 ; k++) {
       AnalysisNearestEdges(seqSections,seqCandidates,seqOrientations,(k==1));
       if(k == 1 && !seqCandidates.Length()) return Standard_False;
@@ -1613,7 +1660,8 @@ Standard_Boolean BRepBuilderAPI_Sewing::FindCandidates(TopTools_SequenceOfShape&
       if (mapReference.Contains(indCandidate)) break;
       // Find candidates for candidate #indCandidate
       mapReference.Add(indCandidate); // Push candidate in the map
-      TColStd_SequenceOfInteger seqCandidates1, seqOrientations1;
+      TColStd_SequenceOfInteger seqCandidates1;
+      TColStd_SequenceOfBoolean seqOrientations1;
       Standard_Boolean isFound =
         FindCandidates(seqSections,mapReference,seqCandidates1,seqOrientations1);
       mapReference.RemoveLast(); // Pop candidate from the map
@@ -1692,13 +1740,13 @@ void BRepBuilderAPI_Sewing::Init(const Standard_Real tolerance,
                           const Standard_Boolean optionNonmanifold)
 {
   // Set tolerance and Perform options
-  myTolerance      = tolerance;
+  myTolerance      = Max (tolerance, Precision::Confusion());
   mySewing         = optionSewing;
   myAnalysis       = optionAnalysis;
   myCutting        = optionCutting;
   myNonmanifold    = optionNonmanifold;
   // Set min and max tolerances
-  myMinTolerance   = tolerance*1e-4; //szv: proposal
+  myMinTolerance   = myTolerance * 1e-4; //szv: proposal
   if (myMinTolerance < Precision::Confusion()) myMinTolerance = Precision::Confusion();
   myMaxTolerance   = Precision::Infinite();
   // Set other modes
@@ -1761,7 +1809,7 @@ void BRepBuilderAPI_Sewing::Add(const TopoDS_Shape& aShape)
 //purpose  : 
 //=======================================================================
 
-#ifdef DEB
+#ifdef OCCT_DEBUG
 #include <OSD_Timer.hxx>
 #endif
 
@@ -1769,7 +1817,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
 {
   const Standard_Integer aNumberOfStages = myAnalysis + myCutting + mySewing + 2;
   Message_ProgressSentry aPS (thePI, "Sewing", 0, aNumberOfStages, 1);
-#ifdef DEB
+#ifdef OCCT_DEBUG
   Standard_Real t_total = 0., t_analysis = 0., t_assembling = 0., t_cutting = 0., t_merging = 0.;
   OSD_Chronometer chr_total, chr_local;
   chr_total.Reset();
@@ -1779,7 +1827,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
   // face analysis
   if (myAnalysis)
   {
-#if DEB
+#ifdef OCCT_DEBUG
     cout << "Begin face analysis..." << endl;
     chr_local.Reset();
     chr_local.Start();
@@ -1788,7 +1836,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
     if (!aPS.More())
       return;
     aPS.Next();
-#if DEB
+#ifdef OCCT_DEBUG
     chr_local.Stop();
     chr_local.Show(t_analysis);
     cout << "Face analysis finished after " << t_analysis << " s" << endl;
@@ -1803,7 +1851,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
     if (myBoundFaces.Extent())
     {
 
-#if DEB
+#ifdef OCCT_DEBUG
       cout << "Begin vertices assembling..." << endl;
       chr_local.Reset();
       chr_local.Start();
@@ -1812,14 +1860,14 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
       if (!aPS.More())
         return;
       aPS.Next();
-#if DEB
+#ifdef OCCT_DEBUG
       chr_local.Stop();
       chr_local.Show(t_assembling);
       cout << "Vertices assembling finished after " << t_assembling << " s" << endl;
 #endif
       if (myCutting)
       {
-#if DEB
+#ifdef OCCT_DEBUG
         cout << "Begin cutting..." << endl;
         chr_local.Reset();
         chr_local.Start();
@@ -1828,13 +1876,13 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
         if (!aPS.More())
           return;
         aPS.Next();
-#if DEB
+#ifdef OCCT_DEBUG
         chr_local.Stop();
         chr_local.Show(t_cutting);
         cout << "Cutting finished after " << t_cutting << " s" << endl;
 #endif
       }
-#if DEB
+#ifdef OCCT_DEBUG
       cout << "Begin merging..." << endl;
       chr_local.Reset();
       chr_local.Start();
@@ -1843,7 +1891,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
       if (!aPS.More())
         return;
       aPS.Next();
-#if DEB
+#ifdef OCCT_DEBUG
       chr_local.Stop();
       chr_local.Show(t_merging);
       cout << "Merging finished after " << t_merging << " s" << endl;
@@ -1862,7 +1910,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
     if (mySewing)
     {
 
-#if DEB
+#ifdef OCCT_DEBUG
       cout << "Creating sewed shape..." << endl;
 #endif
       // examine the multiple edges if any and process sameparameter for edges if necessary
@@ -1882,7 +1930,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
         mySewedShape.Nullify();
         return;
       }
-#if DEB
+#ifdef OCCT_DEBUG
       cout << "Sewed shape created" << endl;
 #endif
     }
@@ -1895,7 +1943,7 @@ void BRepBuilderAPI_Sewing::Perform(const Handle(Message_ProgressIndicator)& the
       return;
     }
   }
-#if DEB
+#ifdef OCCT_DEBUG
   chr_total.Stop();
   chr_total.Show(t_total);
   cout << "Sewing finished!" << endl;
@@ -2246,7 +2294,7 @@ void BRepBuilderAPI_Sewing::FaceAnalysis(const Handle(Message_ProgressIndicator)
            Standard_Real first, last;
            Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,first,last);
            if (c3d.IsNull()) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
              cout << "Warning: Possibly small edge can be sewed: No 3D curve" << endl;
 #endif
            }
@@ -2267,7 +2315,7 @@ void BRepBuilderAPI_Sewing::FaceAnalysis(const Handle(Message_ProgressIndicator)
                isSmall = (length <= MinTolerance());
              }
              catch (Standard_Failure) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
                cout << "Warning: Possibly small edge can be sewed: ";
                Standard_Failure::Caught()->Print(cout); cout << endl;
 #endif
@@ -2326,7 +2374,7 @@ void BRepBuilderAPI_Sewing::FaceAnalysis(const Handle(Message_ProgressIndicator)
 
          // Replace small edge
          if (isSmall) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
            cout << "Warning: Small edge made degenerated by FaceAnalysis" << endl;
 #endif
            nbSmall++;
@@ -2363,7 +2411,7 @@ void BRepBuilderAPI_Sewing::FaceAnalysis(const Handle(Message_ProgressIndicator)
 
       // Remove small face
       if (nbSmall == nbEdges) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
        cout << "Warning: Small face removed by FaceAnalysis" << endl;
 #endif
        myLittleFace.Add(face);
@@ -2751,7 +2799,7 @@ static Standard_Boolean GlueVertices(TopTools_IndexedDataMapOfShapeShape& aVerte
     }
   }
   Standard_Integer nbNodes = NodeVertices.Extent();
-#ifdef DEB
+#ifdef OCCT_DEBUG
   cout << "Glueing " << nbNodes << " nodes..." << endl;
 #endif
   // Merge nearest nodes
@@ -2912,7 +2960,7 @@ void BRepBuilderAPI_Sewing::VerticesAssembling(const Handle(Message_ProgressIndi
     }
     // Glue vertices
     if (nbVert) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
       cout << "Assemble " << nbVert << " vertices on faces..." << endl;
 #endif
       while (GlueVertices(myVertexNode,myNodeSections,myBoundFaces,myTolerance, thePI));
@@ -2921,7 +2969,7 @@ void BRepBuilderAPI_Sewing::VerticesAssembling(const Handle(Message_ProgressIndi
       return;
     aPS.Next();
     if (nbVertFree) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
       cout << "Assemble " << nbVertFree << " vertices on floating edges..." << endl;
 #endif
       while (GlueVertices(myVertexNodeFree,myNodeSections,myBoundFaces,myTolerance, thePI));
@@ -3138,7 +3186,7 @@ void BRepBuilderAPI_Sewing::Merging(const Standard_Boolean /* firstTime */,
     if (!isPrevSplit) {
       // Obtain sequence of edges merged with bound
       TopTools_SequenceOfShape seqMergedWithBound;
-      TColStd_SequenceOfInteger seqMergedWithBoundOri;
+      TColStd_SequenceOfBoolean seqMergedWithBoundOri;
       if (MergedNearestEdges(bound,seqMergedWithBound,seqMergedWithBoundOri)) {
         // Store bound in the map
         MergedWithBound.Bind(bound,bound);
@@ -3215,7 +3263,7 @@ void BRepBuilderAPI_Sewing::Merging(const Standard_Boolean /* firstTime */,
         if (!nbMerged) MergedWithBound.UnBind(bound);
       }
     }
-    Standard_Boolean isMerged = MergedWithBound.Extent();
+    const Standard_Boolean isMerged = !MergedWithBound.IsEmpty();
 
     // Merge with cutting sections
     Handle(BRepTools_ReShape) SectionsReShape = new BRepTools_ReShape;
@@ -3230,7 +3278,7 @@ void BRepBuilderAPI_Sewing::Merging(const Standard_Boolean /* firstTime */,
         if (myMergedEdges.Contains(section)) continue;
         // Merge cutting section
         TopTools_SequenceOfShape seqMergedWithSection;
-        TColStd_SequenceOfInteger seqMergedWithSectionOri;
+        TColStd_SequenceOfBoolean seqMergedWithSectionOri;
         if (MergedNearestEdges(section,seqMergedWithSection,seqMergedWithSectionOri)) {
           // Store section in the map
           MergedWithSections.Bind(section,section);
@@ -3316,7 +3364,7 @@ void BRepBuilderAPI_Sewing::Merging(const Standard_Boolean /* firstTime */,
         }
       }
     }
-    Standard_Boolean isMergedSplit = MergedWithSections.Extent();
+    const Standard_Boolean isMergedSplit = !MergedWithSections.IsEmpty();
 
     if (!isMerged && !isMergedSplit) {
       // Nothing was merged in this iteration
@@ -3417,7 +3465,7 @@ void BRepBuilderAPI_Sewing::Merging(const Standard_Boolean /* firstTime */,
 
 Standard_Boolean BRepBuilderAPI_Sewing::MergedNearestEdges(const TopoDS_Shape& edge,
                                                            TopTools_SequenceOfShape& SeqMergedEdge,
-                                                           TColStd_SequenceOfInteger& SeqMergedOri)
+                                                           TColStd_SequenceOfBoolean& SeqMergedOri)
 {
   // Retrieve edge nodes
   TopoDS_Vertex no1, no2;
@@ -3533,41 +3581,22 @@ Standard_Boolean BRepBuilderAPI_Sewing::MergedNearestEdges(const TopoDS_Shape& e
     }
 
     // Find merging candidates
-    TColStd_SequenceOfInteger seqForward;
+    TColStd_SequenceOfBoolean seqForward;
     TColStd_SequenceOfInteger seqCandidates;
     TColStd_IndexedMapOfInteger mapReference;
-    mapReference.Add(1); // Add index of reference section
+    mapReference.Add(indRef); // Add index of reference section
     if (FindCandidates(seqEdges,mapReference,seqCandidates,seqForward)) {
       Standard_Integer nbCandidates = seqCandidates.Length();
-      // Check if reference section is merged reversed
-      Standard_Boolean toReverse = Standard_False;
-      if (indRef != 1) {
-        // Find reference edge in candidates
-        Standard_Boolean isFound = Standard_False;
-        for (i = 1; i <= nbCandidates && !isFound; i++) {
-          isFound = (seqCandidates(i) == indRef);
-          if (isFound) {
-            // Record orientation
-            toReverse = !seqForward(i);
-            // Restore first edge
-            seqCandidates(i) = 1;
-            seqForward(i) = 1;
-          }
-        }
-        // Fail if reference is not in candidates
-        if (!isFound) return Standard_False;
-      }
       // Record candidate sections
       for (i = 1; i <= nbCandidates; i++) {
         // Retrieve merged edge
         TopoDS_Shape iedge = seqEdges(seqCandidates(i));
-        Standard_Integer ori =
-          ((seqForward(i) && toReverse) || (!seqForward(i) && !toReverse))? 0 : 1;
+        Standard_Boolean ori = seqForward(i) != 0;
         SeqMergedEdge.Append(iedge);
         SeqMergedOri.Append(ori);
         if (!myNonmanifold) break;
       }
-      success = nbCandidates;
+      success = (nbCandidates != 0);
     }
   }
 
@@ -3610,15 +3639,16 @@ void BRepBuilderAPI_Sewing::Cutting(const Handle(Message_ProgressIndicator)& the
     const TopoDS_Edge& bound = TopoDS::Edge(myBoundFaces.FindKey(i));
     // Do not cut floating edges
     if (!myBoundFaces(i).Extent()) continue;
+    // Obtain bound curve
+    c3d = BRep_Tool::Curve(bound, loc, first, last);
+    if (c3d.IsNull()) continue;
+    if (!loc.IsIdentity()) {
+      c3d = Handle(Geom_Curve)::DownCast(c3d->Copy());
+      c3d->Transform(loc.Transformation());
+    }
     // Create cutting sections
     TopTools_ListOfShape listSections;
     { //szv: Use brackets to destroy local variables
-      // Obtain bound curve
-      c3d = BRep_Tool::Curve(bound, loc, first, last);
-      if (!loc.IsIdentity()) {
-        c3d = Handle(Geom_Curve)::DownCast(c3d->Copy());
-        c3d->Transform(loc.Transformation());
-      }
       // Obtain candidate vertices
       TopoDS_Vertex V1, V2;
       TopTools_IndexedMapOfShape CandidateVertices;
@@ -3693,7 +3723,7 @@ void BRepBuilderAPI_Sewing::Cutting(const Handle(Message_ProgressIndicator)& the
       myBoundSections.Bind(bound,listSections);
     }
   }
-#ifdef DEB
+#ifdef OCCT_DEBUG
   cout << "From " << nbBounds << " bounds " << myBoundSections.Extent()
     << " were cut into " << mySectionBound.Extent() << " sections" << endl;
 #endif
@@ -4094,7 +4124,6 @@ void BRepBuilderAPI_Sewing::CreateSewedShape()
           if (IndexMerged.Contains(i)) continue;
           TopoDS_Shell shell = TopoDS::Shell(OldShells.FindKey(i));
           if (NewShell.IsNull()) {
-            BRep_Builder aB;
             aB.MakeShell(NewShell);
             TopoDS_Iterator aItSS(shell) ;
             for( ; aItSS.More(); aItSS.Next())
@@ -4248,8 +4277,10 @@ void BRepBuilderAPI_Sewing::ProjectPointsOnCurve(const TColgp_Array1OfPnt& arrPn
   Extrema_ExtPC locProj;
   locProj.Initialize(GAC, first, last);
   gp_Pnt pfirst = GAC.Value(first), plast = GAC.Value(last);
-
-  for (Standard_Integer i1 = 1; i1 <= arrPnt.Length(); i1++) {
+  Standard_Integer find = 1;//(isConsiderEnds ? 1 : 2);
+  Standard_Integer lind = arrPnt.Length();//(isConsiderEnds ? arrPnt.Length() : arrPnt.Length() -1);
+  
+  for (Standard_Integer i1 = find; i1 <= lind ; i1++) {
     gp_Pnt pt = arrPnt(i1);
     Standard_Real worktol = myTolerance;
     Standard_Real distF2 = pfirst.SquareDistance(pt);
@@ -4260,7 +4291,7 @@ void BRepBuilderAPI_Sewing::ProjectPointsOnCurve(const TColgp_Array1OfPnt& arrPn
       // Project current point on curve
       locProj.Perform(pt);
       if (locProj.IsDone() && locProj.NbExt() > 0) {
-        Standard_Real dist2Min = Min(distF2,distL2);
+        Standard_Real dist2Min = (isConsiderEnds || i1 == find || i1 == lind ? Min(distF2,distL2) : Precision::Infinite());
         Standard_Integer ind, indMin = 0;
         for (ind = 1; ind <= locProj.NbExt(); ind++) {
           Standard_Real dProj2 = locProj.SquareDistance(ind);
@@ -4286,7 +4317,7 @@ void BRepBuilderAPI_Sewing::ProjectPointsOnCurve(const TColgp_Array1OfPnt& arrPn
               }
             }
           }
-          if (distProj2 < worktol * worktol) {
+          if (distProj2 < worktol * worktol || !isConsiderEnds) {
             arrDist(i1) = sqrt (distProj2);
             arrPara(i1) = paramProj;
             arrProj(i1) = ptProj;
@@ -4296,7 +4327,7 @@ void BRepBuilderAPI_Sewing::ProjectPointsOnCurve(const TColgp_Array1OfPnt& arrPn
     }
     catch (Standard_Failure) {
       worktol = MinTolerance();
-#ifdef DEB
+#ifdef OCCT_DEBUG
       cout << "Exception in BRepBuilderAPI_Sewing::ProjectPointsOnCurve: ";
       Standard_Failure::Caught()->Print(cout); cout << endl;
 #endif
@@ -4634,7 +4665,7 @@ void BRepBuilderAPI_Sewing::CreateSections(const TopoDS_Shape& section,
       }
       //}
       /*catch (Standard_Failure) {
-      #ifdef DEB
+      #ifdef OCCT_DEBUG
       cout << "Exception in CreateSections: segment [" << par1 << "," << par2 << "]: ";
       Standard_Failure::Caught()->Print(cout); cout << endl;
       #endif
@@ -4676,7 +4707,7 @@ void BRepBuilderAPI_Sewing::SameParameterShape()
       BRepLib::SameParameter(sec, BRep_Tool::Tolerance(sec));
     }
     catch (Standard_Failure) {
-#ifdef DEB
+#ifdef OCCT_DEBUG
       cout << "Fail: BRepBuilderAPI_Sewing::SameParameterShape exception in BRepLib::SameParameter" << endl;
 #endif
       continue;
@@ -4705,3 +4736,22 @@ NCollection_CellFilter_Action BRepBuilderAPI_VertexInspector::Inspect (const Sta
     myResInd.Append (theTarget);
   return CellFilter_Keep; 
 }
+
+//=======================================================================
+//function : Context
+//purpose  : 
+//=======================================================================
+const Handle(BRepTools_ReShape)& BRepBuilderAPI_Sewing::GetContext() const
+{
+  return myReShape;
+}
+
+//=======================================================================
+//function : SetContext
+//purpose  : 
+//=======================================================================
+void BRepBuilderAPI_Sewing::SetContext(const Handle(BRepTools_ReShape)& theContext)
+{
+  myReShape = theContext;
+}
+