//=======================================================================
//function : Execute
//purpose  :
//======================================================================= 
Standard_Integer GEOMImpl_ScaleDriver::Execute(TFunction_Logbook& log) const
{
  if (Label().IsNull()) return 0;
  Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());

  GEOMImpl_IScale aCI (aFunction);
  Standard_Integer aType = aFunction->GetType();

  TopoDS_Shape aShape;

  if (aType == SCALE_SHAPE || aType == SCALE_SHAPE_COPY) {
    Handle(GEOM_Function) aRefShape = aCI.GetShape();
    TopoDS_Shape aShapeBase = aRefShape->GetValue();
    if (aShapeBase.IsNull()) return 0;

    gp_Pnt aP (0,0,0);
    Handle(GEOM_Function) aRefPoint = aCI.GetPoint();
    if (!aRefPoint.IsNull()) {
      TopoDS_Shape aShapePnt = aRefPoint->GetValue();
      if (aShapePnt.IsNull()) return 0;
      if (aShapePnt.ShapeType() != TopAbs_VERTEX) return 0;
      aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt));
    }

    // Bug 6839: Check for standalone (not included in faces) degenerated edges
    TopTools_IndexedDataMapOfShapeListOfShape aEFMap;
    TopExp::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, aEFMap);
    Standard_Integer i, nbE = aEFMap.Extent();
    for (i = 1; i <= nbE; i++) {
      TopoDS_Shape anEdgeSh = aEFMap.FindKey(i);
      if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeSh))) {
        const TopTools_ListOfShape& aFaces = aEFMap.FindFromIndex(i);
        if (aFaces.IsEmpty())
          Standard_ConstructionError::Raise
            ("Scaling aborted : cannot scale standalone degenerated edge");
      }
    }

    // Perform Scaling
    gp_Trsf aTrsf;
    aTrsf.SetScale(aP, aCI.GetFactor());
    BRepBuilderAPI_Transform aBRepTrsf (aShapeBase, aTrsf, Standard_False);
	aShape = aBRepTrsf.Shape();
  }
  else if (aType == SCALE_SHAPE_AFFINE || aType == SCALE_SHAPE_AFFINE_COPY) {
	Handle(GEOM_Function) aRefShape = aCI.GetShape();
	Handle(GEOM_Function) aRefVector = aCI.GetVector();
	TopoDS_Shape aShapeBase = aRefShape->GetValue();
	TopoDS_Shape aShapeVector  = aRefVector->GetValue();
	if (aShapeBase.IsNull() || aShapeVector.IsNull()) return 0;
	if (aShapeVector.ShapeType() != TopAbs_EDGE) return 0;
	TopoDS_Edge anEdgeVector = TopoDS::Edge(aShapeVector);

	// Bug 6839: Check for standalone (not included in faces) degenerated edges
	TopTools_IndexedDataMapOfShapeListOfShape aEFMap;
	TopExp::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, aEFMap);
	Standard_Integer i, nbE = aEFMap.Extent();
	for (i = 1; i <= nbE; i++) {
	  TopoDS_Shape anEdgeSh = aEFMap.FindKey(i);
	  if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeSh))) {
		const TopTools_ListOfShape& aFaces = aEFMap.FindFromIndex(i);
		if (aFaces.IsEmpty())
		  Standard_ConstructionError::Raise
			("Scaling aborted : cannot scale standalone degenerated edge");
	  }
	}

	//Get axis
	gp_Pnt aP1 = BRep_Tool::Pnt(TopExp::FirstVertex(anEdgeVector));
	gp_Pnt aP2 = BRep_Tool::Pnt(TopExp::LastVertex(anEdgeVector));
    gp_Dir aDir(gp_Vec(aP1, aP2));
	gp_Ax2 anAx2(aP1, aDir);

	// Perform Scaling
	gp_GTrsf aGTrsf;
	aGTrsf.SetAffinity(anAx2, aCI.GetFactor());
	BRepBuilderAPI_GTransform aBRepGTrsf(aShapeBase, aGTrsf, Standard_False);
	aShape = aBRepGTrsf.Shape();
  }
  else if (aType == SCALE_SHAPE_AXES || aType == SCALE_SHAPE_AXES_COPY) {
	Handle(GEOM_Function) aRefShape = aCI.GetShape();
    TopoDS_Shape aShapeBase = aRefShape->GetValue();
    if (aShapeBase.IsNull()) return 0;

    bool isP = false;
    gp_Pnt aP (0,0,0);
    Handle(GEOM_Function) aRefPoint = aCI.GetPoint();
    if (!aRefPoint.IsNull()) {
      TopoDS_Shape aShapePnt = aRefPoint->GetValue();
      if (aShapePnt.IsNull()) return 0;
      if (aShapePnt.ShapeType() != TopAbs_VERTEX) return 0;
      aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt));
      isP = true;
    }

    // Bug 6839: Check for standalone (not included in faces) degenerated edges
    TopTools_IndexedDataMapOfShapeListOfShape aEFMap;
    TopExp::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, aEFMap);
    Standard_Integer i, nbE = aEFMap.Extent();
    for (i = 1; i <= nbE; i++) {
      TopoDS_Shape anEdgeSh = aEFMap.FindKey(i);
      if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeSh))) {
        const TopTools_ListOfShape& aFaces = aEFMap.FindFromIndex(i);
        if (aFaces.IsEmpty())
          Standard_ConstructionError::Raise
            ("Scaling aborted : cannot scale standalone degenerated edge");
      }
    }

    // Perform Scaling
    gp_GTrsf aGTrsf;
    gp_Mat rot (aCI.GetFactorX(), 0, 0,
                0, aCI.GetFactorY(), 0,
                0, 0, aCI.GetFactorZ());
    aGTrsf.SetVectorialPart(rot);

    if (isP) {
      gp_Pnt anO (0,0,0);
      if (anO.Distance(aP) > Precision::Confusion()) {
        gp_GTrsf aGTrsfP0;
        aGTrsfP0.SetTranslationPart(anO.XYZ() - aP.XYZ());
        gp_GTrsf aGTrsf0P;
        aGTrsf0P.SetTranslationPart(aP.XYZ());
        //aGTrsf = aGTrsf0P * aGTrsf * aGTrsfP0;
        aGTrsf = aGTrsf0P.Multiplied(aGTrsf);
        aGTrsf = aGTrsf.Multiplied(aGTrsfP0);
      }
    }

    BRepBuilderAPI_GTransform aBRepGTrsf (aShapeBase, aGTrsf, Standard_False);
    if (!aBRepGTrsf.IsDone())
      Standard_ConstructionError::Raise("Scaling not done");
	aShape = aBRepGTrsf.Shape();
  } else {
  }

  if (aShape.IsNull()) return 0;

  // Check shape validity
  BRepCheck_Analyzer ana (aShape, false);
  if (!ana.IsValid()) {
    ShapeFix_ShapeTolerance aSFT;
    aSFT.LimitTolerance(aShape,Precision::Confusion(),Precision::Confusion());
    Handle(ShapeFix_Shape) aSfs = new ShapeFix_Shape(aShape);
    aSfs->SetPrecision(Precision::Confusion());
    aSfs->Perform();
    aShape = aSfs->Shape();

    ana.Init(aShape, Standard_False);
	if (!ana.IsValid()) {
	  Standard_CString anErrStr("Scaling aborted : non valid shape result");
	  #ifdef THROW_ON_INVALID_SH
		Standard_ConstructionError::Raise(anErrStr);
	  #else
	  MESSAGE(anErrStr);
	  //further processing can be performed here
		//...
	  //in case of failure of automatic treatment
	  //mark the corresponding GEOM_Object as problematic
	  TDF_Label aLabel = aFunction->GetOwnerEntry();
	  if (!aLabel.IsRoot()) {
		Handle(GEOM_Object) aMainObj = GEOM_Object::GetObject(aLabel);
		if (!aMainObj.IsNull())
		  aMainObj->SetDirty(Standard_True);
	  }
	  #endif
	}
  }

  aFunction->SetValue(aShape);

  log.SetTouched(Label()); 

  return 1;    
}
//=======================================================================
//function : Execute
//purpose  :
//=======================================================================
Standard_Integer GEOMImpl_PlateDriver::Execute(TFunction_Logbook& log) const
{
    if (Label().IsNull()) return 0;
    Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
    if(aFunction.IsNull()) return 0;

    GEOMImpl_IPlate aPI (aFunction);
    Standard_Integer aType = aFunction->GetType();

    TopoDS_Shape aShape;

    if (aType == PLATE_BY_SHAPES_LIST) {
        int ind, aLen = aPI.GetLength();

        if (aLen < 1)
            return 0;

        GeomPlate_BuildPlateSurface aPlate;
        Handle(GeomPlate_Surface) myPlateSurf;

        Handle(GEOM_Function) aRefInitialShape = aPI.GetInitialShape();
        if (!aRefInitialShape.IsNull()) {
            TopoDS_Shape anInitialShape = aRefInitialShape->GetValue();
            if (!anInitialShape.IsNull() && anInitialShape.ShapeType() == TopAbs_FACE)
            {
                aPlate.LoadInitSurface(BRep_Tool::Surface(TopoDS::Face(anInitialShape)));

                TopExp_Explorer exp (anInitialShape, TopAbs_EDGE); //in case we have an init surface we must pass all of it's edges as constrains
                for (; exp.More(); exp.Next()) {                   //otherwise exception is risen from the plate driver
                    BRepAdaptor_Curve aCurve(TopoDS::Edge(exp.Current()));
                    Handle(BRepAdaptor_HCurve) aHCurve = new BRepAdaptor_HCurve(aCurve);
                    Handle(GeomPlate_CurveConstraint) aCrvConstr = new GeomPlate_CurveConstraint(aHCurve, DEFAULT_CONTINUITY);
                    aPlate.Add(aCrvConstr);
                }
            }
        }

        for (ind = 1; ind <= aLen; ind++) {
            Handle(GEOM_Function) aRefShape = aPI.GetShape(ind);
            TopoDS_Shape aShape = aRefShape->GetValue();
            if (aShape.ShapeType() == TopAbs_VERTEX) { //case a simple point
                gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
                Handle(GeomPlate_PointConstraint) aPntConstr = new GeomPlate_PointConstraint(aP, DEFAULT_CONTINUITY);
                aPlate.Add(aPntConstr);
            }
            else {
                TopExp_Explorer exp (aShape, TopAbs_EDGE); //this case treats all cases where edges can be found
                Standard_Boolean hasEdge = Standard_False;
                for (; exp.More(); exp.Next()) {
                    BRepAdaptor_Curve aCurve(TopoDS::Edge(exp.Current()));
                    Handle(BRepAdaptor_HCurve) aHCurve = new BRepAdaptor_HCurve(aCurve);
                    Handle(GeomPlate_CurveConstraint) aCrvConstr = new GeomPlate_CurveConstraint(aHCurve, DEFAULT_CONTINUITY);
                    aPlate.Add(aCrvConstr);
                    hasEdge = Standard_True;
                }
                if (!hasEdge) { //this case treats a compound of points
                    exp.Init(aShape, TopAbs_VERTEX);
                    for (; exp.More(); exp.Next()) {
                        gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
                        Handle(GeomPlate_PointConstraint) aPntConstr = new GeomPlate_PointConstraint(aP, DEFAULT_CONTINUITY);
                        aPlate.Add(aPntConstr);
                    }
                }
            }
        }
        aPlate.Perform();
        if (!aPlate.IsDone())
            Standard_ConstructionError::Raise("Plate surface cannot be created using the specific shapes !");
        else
            myPlateSurf = aPlate.Surface();
        GeomPlate_MakeApprox aMKS( myPlateSurf, Precision::Approximation(), DEFAULT_Nbmax, DEFAULT_dgmax, DEFAULT_dmax);
        BRepBuilderAPI_MakeFace MK (aMKS.Surface(), Precision::Confusion());
        MK.Build();
        if (!MK.IsDone())
            Standard_ConstructionError::Raise("Plate topology cannot be created !");
        else {
            aShape = MK.Shape();
            BRepCheck_Analyzer ana (aShape, false);
            if (!ana.IsValid()) {
                Standard_CString anErrStr("Plate algorithm has produced an invalid shape result");
#ifdef THROW_ON_INVALID_SH
                Standard_ConstructionError::Raise(anErrStr);
#else
                MESSAGE(anErrStr);
                //further processing can be performed here
                //...
                //in case of failure of automatic treatment
                //mark the corresponding GEOM_Object as problematic
                TDF_Label aLabel = aFunction->GetOwnerEntry();
                if (!aLabel.IsRoot()) {
                    Handle(GEOM_Object) aMainObj = GEOM_Object::GetObject(aLabel);
                    if (!aMainObj.IsNull())
                        aMainObj->SetDirty(Standard_True);
                }
#endif
            }
        }
    }
    if (aShape.IsNull()) return 0;
    aFunction->SetValue(aShape);
    log.SetTouched(Label());
    return 1;
}
//=======================================================================
//function : Execute
//purpose  :
//======================================================================= 
Standard_Integer GEOMImpl_DraftDriver::Execute(TFunction_Logbook& log) const
{
  if (Label().IsNull()) return 0;
  Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
  if(aFunction.IsNull()) return 0;

  GEOMImpl_IDraft aCI (aFunction);
  Standard_Integer aType = aFunction->GetType();

  TopoDS_Shape aShape;
  TopoDS_Shape aPlaneShape;

  gp_Pln theNeutralPlane;
  gp_Dir theDirection;

  Handle(GEOM_Function) aRefShape = aCI.GetShape();
  TopoDS_Shape aShapeBase = aRefShape->GetValue();

  //get the reference plane and direction
  if (aType == DRAFT_BY_FACE_PLN_ANG) {
	Handle(GEOM_Function) aRefPlane = aCI.GetPlane();
	if (aRefPlane.IsNull())
	  return 0;
	aPlaneShape = aRefPlane->GetValue();
  }
  else if (aType == DRAFT_BY_FACE_STA_ANG) {
	GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetStationary(), aPlaneShape);
  }
  if (aPlaneShape.IsNull() || aPlaneShape.ShapeType() != TopAbs_FACE)
	return 0;

  TopoDS_Face aFace = TopoDS::Face(aPlaneShape);

  Handle(Geom_Surface) surf = BRep_Tool::Surface(aFace);
  Handle(Geom_Plane) myPlane = Handle(Geom_Plane)::DownCast(surf);

  theNeutralPlane = myPlane->Pln();
  theDirection = theNeutralPlane.Axis().Direction();

  //compute the value
  Standard_Real theAngle = aCI.GetAngle();

  int aLen = aCI.GetLength();
  int ind = 1;
  int added = 0;

  BRepOffsetAPI_DraftAngle aDraft (aShapeBase);

  for (; ind <= aLen; ind++) {
	TopoDS_Shape aShapeFace;
	if (GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetFace(ind), aShapeFace)) {
	  TopoDS_Face aFace = TopoDS::Face(aShapeFace);
	  aDraft.Add(aFace, theDirection, theAngle, theNeutralPlane);
	  if (aDraft.AddDone())
		added++;
	  else
		aDraft.Remove(aFace);
	}
  }
  if (added == 0)
	StdFail_NotDone::Raise("None of the faces provided can be used for draft algo");

  aDraft.Build();

  if (!aDraft.IsDone()) {
	StdFail_NotDone::Raise("Draft can't be computed on the given shape with the given parameters");
  }
  aShape = aDraft.Shape();

  if (aShape.IsNull()) return 0;

  // Check shape validity
  BRepCheck_Analyzer ana (aShape, false);
  if (!ana.IsValid()) {
	Standard_CString anErrStr("Draft algorythm has produced an invalid shape result");
	#ifdef THROW_ON_INVALID_SH
	  Standard_ConstructionError::Raise(anErrStr);
	#else
	  MESSAGE(anErrStr);
	  //further processing can be performed here
	  //...
	  //in case of failure of automatic treatment
	  //mark the corresponding GEOM_Object as problematic
	  TDF_Label aLabel = aFunction->GetOwnerEntry();
	  if (!aLabel.IsRoot()) {
		Handle(GEOM_Object) aMainObj = GEOM_Object::GetObject(aLabel);
		if (!aMainObj.IsNull())
		  aMainObj->SetDirty(Standard_True);
	  }
	#endif
  }
  aFunction->SetValue(aShape);
  log.SetTouched(Label());
  return 1;
}
//=======================================================================
//function : Execute
//purpose  :
//=======================================================================
Standard_Integer GEOMImpl_ChamferDriver::Execute(TFunction_Logbook& log) const
{
  if (Label().IsNull()) return 0;
  Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());

  GEOMImpl_IChamfer aCI (aFunction);
  Standard_Integer aType = aFunction->GetType();

  TopoDS_Shape aShape;

  Handle(GEOM_Function) aRefShape = aCI.GetShape();
  TopoDS_Shape aShapeBase = aRefShape->GetValue();



  if (aType == CHAMFER_SHAPE_EDGES_2D)
  {
	BRepFilletAPI_MakeFillet2d fill;
	TopoDS_Face aFace;

	Standard_Boolean aWireFlag = Standard_False;
	
	if (aShapeBase.ShapeType() == TopAbs_FACE)
		aFace = TopoDS::Face(aShapeBase);
	else if (aShapeBase.ShapeType() == TopAbs_WIRE)
	{
		TopoDS_Wire aWire = TopoDS::Wire(aShapeBase);
		BRepBuilderAPI_MakeFace aMF(aWire);
		aMF.Build();
		if (!aMF.IsDone()) {
			StdFail_NotDone::Raise("Cannot build initial face from given wire");
		}
		aFace = aMF.Face();
		aWireFlag = Standard_True;
	}
	else
		StdFail_NotDone::Raise("Base shape is neither a face or a wire !");

	fill.Init(aFace);

	double aD1_2D = aCI.GetD1();
	double aD2_2D = aCI.GetD2();

	TopoDS_Shape aShapeFace1, aShapeFace2;

	if (GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.Get2DEdge1(), aShapeFace1) &&
		GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.Get2DEdge2(), aShapeFace2))
	{
		fill.AddChamfer(TopoDS::Edge(aShapeFace1), TopoDS::Edge(aShapeFace2), aD1_2D, aD2_2D);
	}
	else
		StdFail_NotDone::Raise("Cannot get 2d egde from sub-shape index!");

	fill.Build();
	if (!fill.IsDone()) {
		StdFail_NotDone::Raise("Chamfer can not be computed on the given shape with the given parameters");
	}
	if (aWireFlag)
	{
		BRepBuilderAPI_MakeWire MW;
		TopExp_Explorer exp (fill.Shape(), TopAbs_EDGE);
		for (; exp.More(); exp.Next())
			MW.Add(TopoDS::Edge(exp.Current()));
		MW.Build();
		if (!MW.IsDone())
			StdFail_NotDone::Raise("Resulting wire cannot be built");
			
		aShape = MW.Shape();
	}
	else
		aShape = fill.Shape();
  }
  else
  {
	  // Check the shape type. It have to be shell
	  // or solid, or compsolid, or compound of these shapes.
	  if (!isGoodForChamfer(aShapeBase)) {
		StdFail_NotDone::Raise
		  ("Wrong shape. Must be shell or solid, or compsolid or compound of these shapes");
	  }

	  BRepFilletAPI_MakeChamfer fill (aShapeBase);

	  if (aType == CHAMFER_SHAPE_ALL) {
		// symmetric chamfer on all edges
		double aD = aCI.GetD();
		TopTools_IndexedDataMapOfShapeListOfShape M;
		GEOMImpl_Block6Explorer::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, M);
		for (int i = 1; i <= M.Extent(); i++) {
		  TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
		  TopoDS_Face F = TopoDS::Face(M.FindFromIndex(i).First());
		  if (!BRepTools::IsReallyClosed(E, F) &&
			  !BRep_Tool::Degenerated(E) &&
			  M.FindFromIndex(i).Extent() == 2)
			fill.Add(aD, E, F);
		}
	  }else if (aType == CHAMFER_SHAPE_EDGE || aType == CHAMFER_SHAPE_EDGE_AD) {
		// chamfer on edges, common to two faces, with D1 on the first face

		TopoDS_Shape aFace1, aFace2;
		if (GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetFace1(), aFace1) &&
			GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetFace2(), aFace2))
		  {
		TopoDS_Face F = TopoDS::Face(aFace1);

		// fill map of edges of the second face
		TopTools_MapOfShape aMap;
		TopExp_Explorer Exp2 (aFace2, TopAbs_EDGE);
		for (; Exp2.More(); Exp2.Next()) {
		  aMap.Add(Exp2.Current());
		}
	
		// find edges of the first face, common with the second face
		TopExp_Explorer Exp (aFace1, TopAbs_EDGE);
		for (; Exp.More(); Exp.Next()) {
		  if (aMap.Contains(Exp.Current())) {
			TopoDS_Edge E = TopoDS::Edge(Exp.Current());
			if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
			  {
			if ( aType == CHAMFER_SHAPE_EDGE )
			  {
				double aD1 = aCI.GetD1();
				double aD2 = aCI.GetD2();
				fill.Add(aD1, aD2, E, F);
			  }
			else
			  {
				double aD = aCI.GetD();
				double anAngle = aCI.GetAngle();
				if ( (anAngle > 0) && (anAngle < (Standard_PI/2)) )
				  fill.AddDA(aD, anAngle, E, F);
			  }
			  }
		  }
		}
		  }
	  }
	  else if (aType == CHAMFER_SHAPE_FACES || aType == CHAMFER_SHAPE_FACES_AD) {
		// chamfer on all edges of the selected faces, with D1 on the selected face
		// (on first selected face, if the edge belongs to two selected faces)

		int aLen = aCI.GetLength();
		int ind = 1;
		TopTools_MapOfShape aMap;
		TopTools_IndexedDataMapOfShapeListOfShape M;
		GEOMImpl_Block6Explorer::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, M);
		for (; ind <= aLen; ind++)
		{
		  TopoDS_Shape aShapeFace;
		  if (GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetFace(ind), aShapeFace))
		{
		  TopoDS_Face F = TopoDS::Face(aShapeFace);
		  TopExp_Explorer Exp (F, TopAbs_EDGE);
		  for (; Exp.More(); Exp.Next()) {
			if (!aMap.Contains(Exp.Current()))
			  {
			TopoDS_Edge E = TopoDS::Edge(Exp.Current());
			if (!BRepTools::IsReallyClosed(E, F) &&
				!BRep_Tool::Degenerated(E) &&
				M.FindFromKey(E).Extent() == 2)
			  if (aType == CHAMFER_SHAPE_FACES)
				{
				  double aD1 = aCI.GetD1();
				  double aD2 = aCI.GetD2();
				  fill.Add(aD1, aD2, E, F);
				}
			  else
				{
				  double aD = aCI.GetD();
				  double anAngle = aCI.GetAngle();
				  if ( (anAngle > 0) && (anAngle < (Standard_PI/2)) )
				fill.AddDA(aD, anAngle, E, F);
				}
			  }
		  }
		}
		}
	  }
	else if (aType == CHAMFER_SHAPE_EDGES || aType == CHAMFER_SHAPE_EDGES_AD)
	  {
		// chamfer on selected edges with lenght param D1 & D2.

		int aLen = aCI.GetLength();
		int ind = 1;
		TopTools_MapOfShape aMap;
		TopTools_IndexedDataMapOfShapeListOfShape M;
		GEOMImpl_Block6Explorer::MapShapesAndAncestors(aShapeBase, TopAbs_EDGE, TopAbs_FACE, M);
		for (; ind <= aLen; ind++)
		{
		  TopoDS_Shape aShapeEdge;
		  if (GEOMImpl_ILocalOperations::GetSubShape(aShapeBase, aCI.GetEdge(ind), aShapeEdge))
		{
		  TopoDS_Edge E = TopoDS::Edge(aShapeEdge);
		  const TopTools_ListOfShape& aFacesList = M.FindFromKey(E);
		  TopoDS_Face F = TopoDS::Face( aFacesList.First() );
		  if (aType == CHAMFER_SHAPE_EDGES)
			{
			  double aD1 = aCI.GetD1();
			  double aD2 = aCI.GetD2();
			  fill.Add(aD1, aD2, E, F);
			}
		  else
			{
			  double aD = aCI.GetD();
			  double anAngle = aCI.GetAngle();
			  if ( (anAngle > 0) && (anAngle < (Standard_PI/2)) )
			fill.AddDA(aD, anAngle, E, F);
			}
		}
		}
	  }
	  else {
	  }

	  fill.Build();
	  if (!fill.IsDone()) {
		StdFail_NotDone::Raise("Chamfer can not be computed on the given shape with the given parameters");
	  }
	  aShape = fill.Shape();
  }

  if (aShape.IsNull()) return 0;

  // Check shape validity
  BRepCheck_Analyzer ana (aShape, false);
  if (!ana.IsValid()) {
  	// 08.07.2008 added by skl during fixing bug 19761 from Mantis
	ShapeFix_ShapeTolerance aSFT;
	aSFT.LimitTolerance(aShape, Precision::Confusion(),
						Precision::Confusion(), TopAbs_SHAPE);
	Handle(ShapeFix_Shape) aSfs = new ShapeFix_Shape(aShape);
	aSfs->Perform();
	aShape = aSfs->Shape();

    // fix SameParameter flag
    BRepLib::SameParameter(aShape, 1.E-5, Standard_True);

	ana.Init(aShape);
	if (!ana.IsValid()) {
	  Standard_CString anErrStr("Chamfer algorithm has produced an invalid shape result");
	  #ifdef THROW_ON_INVALID_SH
		Standard_ConstructionError::Raise(anErrStr);
	  #else
		MESSAGE(anErrStr);
		//further processing can be performed here
		//...
		//in case of failure of automatic treatment
		//mark the corresponding GEOM_Object as problematic
		TDF_Label aLabel = aFunction->GetOwnerEntry();
		if (!aLabel.IsRoot()) {
		  Handle(GEOM_Object) aMainObj = GEOM_Object::GetObject(aLabel);
		  if (!aMainObj.IsNull())
			aMainObj->SetDirty(Standard_True);
		}
	  #endif
	}
  }

  aFunction->SetValue(aShape);

  log.SetTouched(Label());

  return 1;
}