summaryrefslogtreecommitdiff
path: root/src/BRepCheck/BRepCheck_Wire.cxx
blob: 8550542ba23410468dcf86e4712e9f299dc24abb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
// File:        BRepCheck_Wire.cxx
// Created:        Tue Dec 12 17:49:08 1995
// Author:        Jacques GOUSSARD
//                <jag@bravox>
// Modified by dpf, Fri Dec 19 15:31:03 1997 
//   Taitement de la fermeture en 2d.
//
//  modified by eap Tue Dec 18 14:14:25 2001 (bug OCC23)
//   Check self-intersection in case of closed edge
//
//  modified by eap Fri Dec 21 17:36:55 2001 (bug OCC35)
//   Closed2d() added

//  Modified by skv - Wed Jul 23 12:22:20 2003 OCC1764 

#include <BRepCheck_Wire.ixx>
#include <BRepCheck_ListOfStatus.hxx>
#include <BRepCheck_ListIteratorOfListOfStatus.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_MapIteratorOfMapOfShape.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <TopTools_DataMapOfShapeListOfShape.hxx>
#include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopLoc_Location.hxx>
#include <TColGeom2d_Array1OfCurve.hxx>
#include <IntRes2d_Intersection.hxx>
#include <IntRes2d_IntersectionPoint.hxx>
#include <IntRes2d_IntersectionSegment.hxx>
#include <IntRes2d_Transition.hxx>
#include <IntRes2d_Domain.hxx>
#include <Geom2dInt_GInter.hxx>
#include <gp_Pnt2d.hxx>
#include <gp_Pnt.hxx>
#include <gp_Lin.hxx>
#include <Geom2d_Curve.hxx>
#include <Geom_Curve.hxx>
#include <Geom2dAdaptor_Curve.hxx>
#include <Geom2dAdaptor_HCurve.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepAdaptor_HSurface.hxx>
#include <BRepCheck.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopTools_MapOfOrientedShape.hxx>
#include <TopTools_HArray1OfShape.hxx>
#include <TopTools_MapIteratorOfMapOfOrientedShape.hxx>

//Patch
#include <Precision.hxx>
#include <Bnd_Array1OfBox2d.hxx>
#include <BndLib_Add2dCurve.hxx>

//#ifdef WNT
#include <stdio.h>
#include <BRepTools_WireExplorer.hxx>
#include <TopExp.hxx>
//#endif

#include <TopTools_IndexedMapOfOrientedShape.hxx>
#include <ElCLib.hxx>


static void Propagate(const TopTools_IndexedDataMapOfShapeListOfShape&,
                      const TopoDS_Shape&,   // edge
                      TopTools_MapOfShape&); // mapofedge


static TopAbs_Orientation GetOrientation(const TopTools_MapOfShape&,
                                         const TopoDS_Edge&);


static 
  void ChoixUV(const TopoDS_Vertex&,
	       const TopoDS_Edge&,
	       const TopoDS_Face&,
	       TopTools_ListOfShape&);

//      20/03/02 akm vvv (OCC234)
// static 
//   Standard_Boolean CheckLoopOrientation( const TopoDS_Vertex&,
// 					const TopoDS_Edge&,
// 					const TopoDS_Edge&,
// 					const TopoDS_Face&,
// 					TopTools_ListOfShape&);
//      20/03/02 akm ^^^

inline Standard_Boolean IsOriented(const TopoDS_Shape& S)
{
  return (S.Orientation() == TopAbs_FORWARD ||
          S.Orientation() == TopAbs_REVERSED);
}

static
  void CurveDirForParameter(const Handle(Geom2d_Curve)& aC2d,
			    const Standard_Real aPrm,
			    gp_Pnt2d& Pnt,
			    gp_Vec2d& aVec2d);

//  Modified by Sergey KHROMOV - Thu Jun 20 11:21:51 2002 OCC325 Begin
static Standard_Boolean IsClosed2dForPeriodicFace
                        (const TopoDS_Face   &theFace,
			 const gp_Pnt2d      &theP1,
			 const gp_Pnt2d      &theP2,
			 const TopoDS_Vertex &theVertex);

static Standard_Boolean GetPnt2d(const TopoDS_Vertex    &theVertex,
				 const TopoDS_Edge      &theEdge,
				 const TopoDS_Face      &theFace,
				       gp_Pnt2d         &aPnt);
//  Modified by Sergey KHROMOV - Wed May 22 10:44:08 2002 End

//=======================================================================
//function : BRepCheck_Wire
//purpose  : 
//=======================================================================
BRepCheck_Wire::BRepCheck_Wire(const TopoDS_Wire& W)
{
  Init(W);
}
//=======================================================================
//function : Minimum
//purpose  : 
//=======================================================================
void BRepCheck_Wire::Minimum()
{
  myCdone = Standard_False;
  myGctrl = Standard_True;
  if (!myMin) {
    BRepCheck_ListOfStatus thelist;
    myMap.Bind(myShape, thelist);
    BRepCheck_ListOfStatus& lst = myMap(myShape);

    // on verifie que le wire est "connexe" == check that the wire is "connex"
    TopExp_Explorer exp(myShape,TopAbs_EDGE);
    Standard_Integer nbedge = 0;
    myMapVE.Clear();
    // fill myMapVE
    for (; exp.More(); exp.Next()) {
      nbedge++;
      TopExp_Explorer expv;
      for (expv.Init(exp.Current(),TopAbs_VERTEX);
           expv.More(); expv.Next()) {
        const TopoDS_Shape& vtx = expv.Current();
        Standard_Integer index = myMapVE.FindIndex(vtx);
        if (index == 0) {
          TopTools_ListOfShape theListOfShape;
          index = myMapVE.Add(vtx, theListOfShape);
        }
        myMapVE(index).Append(exp.Current());
      }
    }
    // wire must have at least one edge
    if (nbedge == 0) {
      BRepCheck::Add(lst,BRepCheck_EmptyWire);
    }
    // check if all edges are connected through vertices
    else if (nbedge >= 2) {
      TopTools_MapOfShape mapE;
      exp.ReInit();
      Propagate(myMapVE,exp.Current(),mapE);
      for (exp.ReInit(); exp.More(); exp.Next()) {
        if (!mapE.Contains(exp.Current())) {
          BRepCheck::Add(lst,BRepCheck_NotConnected);
          break;
        }
      }
    }
    if (lst.IsEmpty()) {
      lst.Append(BRepCheck_NoError);
    }
    myMapVE.Clear();
    myMin = Standard_True;
  }
}
//=======================================================================
//function : InContext
//purpose  : 
//=======================================================================
void BRepCheck_Wire::InContext(const TopoDS_Shape& S)
{

  if (myMap.IsBound(S)) {
    return;
  }
  BRepCheck_ListOfStatus thelist;
  myMap.Bind(S, thelist);

  BRepCheck_ListOfStatus& lst = myMap(S);

  // check if my wire is in <S>
  TopExp_Explorer exp(S,TopAbs_WIRE); 
  for ( ; exp.More(); exp.Next()) {
    if (exp.Current().IsSame(myShape)) {
      break;
    }
  }
  if (!exp.More()) {
    BRepCheck::Add(lst,BRepCheck_SubshapeNotInShape);
    return;
  }

  BRepCheck_Status st = BRepCheck_NoError;
  TopAbs_ShapeEnum styp = S.ShapeType();
  switch (styp) {

  case TopAbs_FACE:
    {
      TopoDS_Edge ed1,ed2; // bidon
      if (myGctrl) 
        st = SelfIntersect(TopoDS::Face(S),ed1,ed2,Standard_True);
      if (st != BRepCheck_NoError) break;
      st = Closed();
      if (st != BRepCheck_NoError) break;
      st = Orientation(TopoDS::Face(S));
      if (st != BRepCheck_NoError) break;
      st = Closed2d(TopoDS::Face(S));
    }
    break;
  default:
    break;
  }
  
  if (st != BRepCheck_NoError) 
    BRepCheck::Add(lst,st);
      
  if (lst.IsEmpty()) 
    lst.Append(BRepCheck_NoError);
}
//=======================================================================
//function : Blind
//purpose  : 
//=======================================================================
void BRepCheck_Wire::Blind()
{
  if (!myBlind) {
    // rien de plus que dans le minimum
    myBlind = Standard_True;
  }
}
//=======================================================================
//function : Closed
//purpose  : 
//=======================================================================
BRepCheck_Status BRepCheck_Wire::Closed(const Standard_Boolean Update)
{

  if (myCdone) {
    if (Update) {
      BRepCheck::Add(myMap(myShape),myCstat);
    }
    return myCstat;
  }

  myCdone = Standard_True; // ce sera fait...

  BRepCheck_ListIteratorOfListOfStatus itl(myMap(myShape));
  if (itl.Value() != BRepCheck_NoError) {
    myCstat = itl.Value();
    return myCstat; // deja enregistre
  }

  myCstat = BRepCheck_NoError;

  TopExp_Explorer exp,expv;
  TopTools_MapOfShape mapS;
  TopTools_DataMapOfShapeListOfShape Cradoc;
  myMapVE.Clear();
  // Checks if the oriented edges of the wire give a "closed" wire,
  // i-e if each oriented vertex on oriented edges is found 2 times...
  // myNbori = 0;
  for (exp.Init(myShape,TopAbs_EDGE);exp.More(); exp.Next()) {
    if (IsOriented(exp.Current())) {
      // myNbori++;
      if (!Cradoc.IsBound(exp.Current())) {
        TopTools_ListOfShape theListOfShape;
        Cradoc.Bind(exp.Current(), theListOfShape);
      }
      Cradoc(exp.Current()).Append(exp.Current());

      mapS.Add(exp.Current());
      for (expv.Init(exp.Current(),TopAbs_VERTEX); expv.More(); expv.Next()) {
        if (IsOriented(expv.Current())) {
          Standard_Integer index = myMapVE.FindIndex(expv.Current());
          if (index == 0) {
            TopTools_ListOfShape theListOfShape1;
            index = myMapVE.Add(expv.Current(), theListOfShape1);
          }
          myMapVE(index).Append(exp.Current());
        }
      }
    }
  }

  Standard_Integer theNbori = mapS.Extent();
  if (theNbori >= 2) {
    mapS.Clear();
    for (exp.ReInit(); exp.More(); exp.Next()) {
      if (IsOriented(exp.Current())) {
        break;
      }
    }
    Propagate(myMapVE,exp.Current(),mapS);
  }
  if (theNbori != mapS.Extent()) {
    myCstat = BRepCheck_NotConnected;
    if (Update) {
      BRepCheck::Add(myMap(myShape),myCstat);
    }
    return myCstat;
  }

  // Checks the number of occurence of an edge : maximum 2, and in this 
  // case, one time FORWARD and one time REVERSED

  Standard_Boolean yabug = Standard_False;
  for (TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itdm(Cradoc);
       itdm.More(); itdm.Next()) {
    if (itdm.Value().Extent() >= 3) {
      yabug = Standard_True;
    }
    else if (itdm.Value().Extent() == 2) {
      if (itdm.Value().First().Orientation() == 
          itdm.Value().Last().Orientation()) {
        yabug = Standard_True;
      }
    }
    if (yabug) {
      myCstat = BRepCheck_RedundantEdge;
      if (Update) {
        BRepCheck::Add(myMap(myShape),myCstat);
      }
      return myCstat;
    }
  }

  for (Standard_Integer i = 1; i<= myMapVE.Extent(); i++) {
    if (myMapVE(i).Extent()%2 != 0) {
      myCstat=BRepCheck_NotClosed;
      if (Update) {
        BRepCheck::Add(myMap(myShape),myCstat);
      }
      return myCstat;
    }
  }

  if (Update) {
    BRepCheck::Add(myMap(myShape),myCstat);
  }
  return myCstat;
}
//=======================================================================
//function : Closed2d
//purpose  : for periodic faces
//=======================================================================
BRepCheck_Status BRepCheck_Wire::Closed2d(const TopoDS_Face& theFace,
                                          const Standard_Boolean Update)
{

  // 3d closure checked?
  BRepCheck_Status aClosedStat = Closed();
  if (aClosedStat != BRepCheck_NoError) {
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }

  // 20/03/02 akm vvv : (OCC234) Hence this method will be used to check
  //                    both periodic and non-periodic faces
  //   // this check is for periodic faces 
  BRepAdaptor_Surface aFaceSurface (theFace, Standard_False);
  // if (!aFaceSurface.IsUPeriodic() && !aFaceSurface.IsVPeriodic())
  // {
  //   if (Update) 
  //     BRepCheck::Add(myMap(myShape),aClosedStat);
  //   return aClosedStat;
  // }
  // 20/03/02 akm ^^^
  
  // count edges having FORWARD or REVERSED orientation
  Standard_Integer aNbOrirntedEdges = 0;
  TopExp_Explorer anEdgeExp(myShape,TopAbs_EDGE);
  for (;anEdgeExp.More(); anEdgeExp.Next()) {
    if (IsOriented(anEdgeExp.Current())) 
      aNbOrirntedEdges++;
  }
  if (aNbOrirntedEdges==0)
  {
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }
  
  // all those edges must form a closed 2d contour and be found by WireExplorer

  Standard_Integer aNbFoundEdges = 0;

  BRepTools_WireExplorer aWireExp(TopoDS::Wire(myShape), theFace);
  TopoDS_Edge aFirstEdge = aWireExp.Current();
  TopoDS_Vertex aFirstVertex = aWireExp.CurrentVertex();
  TopoDS_Edge aLastEdge;
  for (;aWireExp.More(); aWireExp.Next())
  {
    aNbFoundEdges++;
    aLastEdge = aWireExp.Current();
  }

  if (aNbFoundEdges != aNbOrirntedEdges)
  {
    aClosedStat = BRepCheck_NotClosed;
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }
    
  // Check distance between 2d ends of first and last edges
//  Modified by Sergey KHROMOV - Mon May 13 12:42:10 2002 Begin
//   First check if first and last edges are infinite:
  Standard_Real      aF;
  Standard_Real      aL;
  Standard_Boolean   isFirstInfinite = Standard_False;
  Standard_Boolean   isLastInfinite  = Standard_False;
  TopAbs_Orientation anOri;

  anOri = aFirstEdge.Orientation();
  BRep_Tool::Range(aFirstEdge, aF, aL);
  if ((anOri == TopAbs_FORWARD  && aF == -Precision::Infinite()) ||
      (anOri == TopAbs_REVERSED && aL ==  Precision::Infinite()))
    isFirstInfinite = Standard_True;

  anOri = aLastEdge.Orientation();
  BRep_Tool::Range(aLastEdge, aF, aL);
  if ((anOri == TopAbs_FORWARD  && aL ==  Precision::Infinite()) ||
      (anOri == TopAbs_REVERSED && aF == -Precision::Infinite()))
    isLastInfinite = Standard_True;

  if (isFirstInfinite && isLastInfinite) {
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  } else if (aFirstVertex.IsNull()) {
    aClosedStat = BRepCheck_NotClosed;
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }
//  Modified by Sergey KHROMOV - Mon May 13 12:42:10 2002 End

  gp_Pnt2d p, p1, p2; // ends of prev edge, next edge, bidon

  // get first point
  BRep_Tool::UVPoints(aLastEdge, theFace, p2, p);
  if (aLastEdge.Orientation() == TopAbs_REVERSED) p = p2; 
  
//  Modified by Sergey KHROMOV - Mon Apr 22 10:36:33 2002 Begin
//   Standard_Real aTol, aUResol, aVResol;

//   // find 2d tolerance
//   aTol  = BRep_Tool::Tolerance(aFirstVertex);
//   aUResol = 2*aFaceSurface.UResolution(aTol);
//   aVResol = 2*aFaceSurface.VResolution(aTol);

  // get second point
  if (aFirstEdge.Orientation() == TopAbs_REVERSED)
    BRep_Tool::UVPoints(aFirstEdge, theFace, p2, p1);
  else 
    BRep_Tool::UVPoints(aFirstEdge, theFace, p1, p2);

//  Modified by Sergey KHROMOV - Thu Jun 20 10:55:42 2002 OCC325 Begin
// Check 2d distance for periodic faces with seam edge
  if (!IsClosed2dForPeriodicFace(theFace, p, p1, aFirstVertex)) {
    aClosedStat = BRepCheck_NotClosed;
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }
//  Modified by Sergey KHROMOV - Thu Jun 20 10:58:05 2002 End

  // check distance
//   Standard_Real dfUDist=Abs(p.X()-p1.X());
//   Standard_Real dfVDist=Abs(p.Y()-p1.Y());
//   if (dfUDist > aUResol || dfVDist > aVResol)
//   {
  Standard_Real aTol3d = BRep_Tool::Tolerance(aFirstVertex);
  gp_Pnt        aPRef  = BRep_Tool::Pnt(aFirstVertex);
  gp_Pnt        aP1    = aFaceSurface.Value(p.X(),  p.Y());
  gp_Pnt        aP2    = aFaceSurface.Value(p1.X(), p1.Y());
  Standard_Real Dist1  = aPRef.Distance(aP1);
  Standard_Real Dist2  = aPRef.Distance(aP2);

  if (Dist1 > aTol3d || Dist2 > aTol3d) {
//  Modified by Sergey KHROMOV - Mon Apr 22 10:36:44 2002 End
#ifdef DEB
    cout << endl;
    cout << "------------------------------------------------------"   <<endl;
    cout << "--- BRepCheck Wire: Closed2d -> Erreur"                   <<endl;
    if (Dist1 > aTol3d)
      cout << "--- Dist1 (" << Dist1 << ") > Tol3d (" << aTol3d << ")" <<endl;
    if (Dist2 > aTol3d)
      cout << "--- Dist2 (" << Dist2 << ") > Tol3d (" << aTol3d << ")" <<endl;
    cout << "------------------------------------------------------"   <<endl;
#endif
    aClosedStat = BRepCheck_NotClosed;
    if (Update) 
      BRepCheck::Add(myMap(myShape),aClosedStat);
    return aClosedStat;
  }
  
  if (Update) 
    BRepCheck::Add(myMap(myShape),aClosedStat);
  return aClosedStat;
}
//=======================================================================
//function : Orientation
//purpose  : 
//=======================================================================
BRepCheck_Status BRepCheck_Wire::Orientation(const TopoDS_Face& F,
                                             const Standard_Boolean Update)
{
  BRepCheck_Status theOstat = Closed();
  if (theOstat != BRepCheck_NotClosed && theOstat != BRepCheck_NoError) {
    if (Update) {
      BRepCheck::Add(myMap(myShape),theOstat);
    }
    return theOstat;
  }

  theOstat = BRepCheck_NoError;

  TopoDS_Vertex VF,VL;
#ifndef DEB
  TopAbs_Orientation orient, ortmp = TopAbs_FORWARD;
#else
  TopAbs_Orientation orient, ortmp;
#endif
  TopTools_ListOfShape ledge, ListOfPassedEdge;
  TopExp_Explorer exp,vte;
  TopTools_MapOfShape mapS;
  TopoDS_Edge theEdge,theRef;

  // Checks the orientation of the edges
  for (exp.Init(myShape,TopAbs_EDGE); exp.More(); exp.Next()) {
    const TopoDS_Edge& edg = TopoDS::Edge(exp.Current());
    orient = edg.Orientation();
    if (IsOriented(edg)) {
      mapS.Add(edg);
      theEdge = edg;
      theRef = edg;
      for (vte.Init(edg,TopAbs_VERTEX);vte.More(); vte.Next()) {
        TopAbs_Orientation vto = vte.Current().Orientation();
        if (vto == TopAbs_FORWARD) {
          VF = TopoDS::Vertex(vte.Current());
        }
        else if (vto == TopAbs_REVERSED) {
          VL = TopoDS::Vertex(vte.Current());
        }
        if (!VF.IsNull() && !VL.IsNull()) {
          break;
        }
      }
      if (VF.IsNull() && VL.IsNull())
        theOstat = BRepCheck_InvalidDegeneratedFlag;
      break;
    }
  }
 
  if (theOstat == BRepCheck_NoError) {
    Standard_Integer Index = 1;
    Standard_Integer nbOriNoDegen=myMapVE.Extent();
//  Modified by Sergey KHROMOV - Tue May 21 17:12:45 2002 Begin
    Standard_Boolean isGoFwd     = Standard_True;

    if (VL.IsNull())
      isGoFwd = Standard_False;
//  Modified by Sergey KHROMOV - Tue May 21 17:12:45 2002 End

    while (Index < nbOriNoDegen) {
      ledge.Clear();
      ListOfPassedEdge.Clear();
      // on cherche les edges qui s`enchainent sur VL si !VL.IsNull 
      // sinon sur VF.
      
      Standard_Integer ind;
      if (!VL.IsNull()) {
        ind = myMapVE.FindIndex(VL);
      }
      else if (!VF.IsNull()) {
        ind = myMapVE.FindIndex(VF);
      }
      else {
        theOstat = BRepCheck_InvalidDegeneratedFlag;
        break;
      }

      for (TopTools_ListIteratorOfListOfShape itls(myMapVE(ind));
           itls.More(); itls.Next()) {
        const TopoDS_Edge & edg = TopoDS::Edge(itls.Value());

        orient = edg.Orientation();
        if (mapS.Contains(edg)) ortmp = GetOrientation(mapS,edg);

        //Add to list already passed outcoming edges
        if (mapS.Contains(edg) && ortmp == orient && !edg.IsSame(theEdge))
          for (vte.Init(edg,TopAbs_VERTEX); vte.More(); vte.Next())
            {
              TopAbs_Orientation vto = vte.Current().Orientation();
              if (!VL.IsNull())
                {
                  if (vto == TopAbs_FORWARD && VL.IsSame(vte.Current()))
                    {
                      ListOfPassedEdge.Append(edg);
                      break;
                    }
                }
              else // VF is not null
                {
                  if (vto == TopAbs_REVERSED && VF.IsSame(vte.Current()))
                    {
                      ListOfPassedEdge.Append(edg);
                      break;
                    }
                }
            }

        if (!mapS.Contains(edg) || ortmp != orient) {
          for (vte.Init(edg,TopAbs_VERTEX);vte.More(); vte.Next()) {
            TopAbs_Orientation vto = vte.Current().Orientation();
            if (!VL.IsNull()) {
              if (vto == TopAbs_FORWARD && VL.IsSame(vte.Current())) {
                // Si on travaille en 2d (face non nulle) ou 
                // si l'edge n'est pas degenere on l'ajoute
                if (!F.IsNull() || !BRep_Tool::Degenerated(edg))
                  ledge.Append(edg);
                break;
              }
            }
            else { // VF n`est pas nul
              if (vto == TopAbs_REVERSED && VF.IsSame(vte.Current())) {
                // Si on travaille en 2d (face non nulle) ou 
                // si l'edge n'est pas degenere on l'ajoute
                if (!F.IsNull() || !BRep_Tool::Degenerated(edg))
                  ledge.Append(edg);
                break;
              }
            }
          }
        }
      }
      Standard_Integer nbconnex = ledge.Extent();
      Standard_Boolean Changedesens = Standard_False;
      if (nbconnex == 0) {
        if (myCstat == BRepCheck_NotClosed) {
          if (VL.IsNull()) {
            if (Update) {
              BRepCheck::Add(myMap(myShape),theOstat);
            }
            return theOstat; // on sort
          }
          else {
            Index--; // parce que apres Index++ et on n`a pas enchaine
            VL.Nullify(); // on force a enchainer sur VF
            theEdge = theRef;
            Changedesens = Standard_True;
          }
        }
        else {
          theOstat = BRepCheck_BadOrientationOfSubshape;
          if (Update) {
            BRepCheck::Add(myMap(myShape),theOstat);
	    }
          return theOstat;
        }
      }

      // JAG 03/07   else if (nbconnex >= 2 && !F.IsNull())  // On essaie de voir en 2d
      else if (!F.IsNull()) { // On essaie de voir en 2d
        TopoDS_Vertex pivot;
        if (!VL.IsNull()) {
          pivot = VL;
        }
        else {
          pivot = VF;
        }

        ChoixUV(pivot,theEdge,F,ledge);
        nbconnex = ledge.Extent();
//      20/03/02 akm vvv : (OCC234) - The 2d exploration of wire with necessary
//                         checks is performed in Closed2d, here it's useless
//         if (nbconnex == 1 && !CheckLoopOrientation( pivot, theEdge, TopoDS::Edge(ledge.First()), F, ListOfPassedEdge ))
//         {
//           theOstat = BRepCheck_BadOrientationOfSubshape;
//           if (Update)
//             BRepCheck::Add(myMap(myShape),theOstat);
//           return theOstat;
//         }
//      20/03/02 akm ^^^
      }

      if (nbconnex >= 2) {
        theOstat = BRepCheck_BadOrientationOfSubshape;
        if (Update) {
          BRepCheck::Add(myMap(myShape),theOstat);
          }
        return theOstat;
      }
      else if (nbconnex == 1) {
        // decaler le vertex
        for (vte.Init(ledge.First(),TopAbs_VERTEX);vte.More(); vte.Next()) {
          TopAbs_Orientation vto = vte.Current().Orientation();
          if (!VL.IsNull()) {
            if (vto == TopAbs_REVERSED) {
              VL = TopoDS::Vertex(vte.Current());
              break;
            }
          }
          else { // VF n`est pas nul
            if (vto == TopAbs_FORWARD) {
              VF = TopoDS::Vertex(vte.Current());
              break;
            }
          }
        }
        mapS.Add(ledge.First());
        theEdge = TopoDS::Edge(ledge.First());
        if (!vte.More()) {
          if (!VL.IsNull()) {
            VL.Nullify();
          }
          else {
            VF.Nullify();
          }
        }
      }
      else if (!Changedesens) { //nbconnex == 0
        theOstat = BRepCheck_NotClosed;
        if (Update) {
          BRepCheck::Add(myMap(myShape),theOstat);
	  }
	return theOstat;
      }

      // On verifie la fermeture du wire en 2d (pas fait dans Closed())
      
      TopoDS_Vertex    aVRef;
      Standard_Boolean isCheckClose = Standard_False;

      if (isGoFwd && !VF.IsNull()) {
	aVRef        = VF;
	isCheckClose = Standard_True;
      } else if (!isGoFwd && !VL.IsNull()) {
	aVRef        = VL;
	isCheckClose = Standard_True;
      }

//       if (Index==1 && myCstat!=BRepCheck_NotClosed && 
// 	  !VF.IsNull() && !F.IsNull()) {
      if (Index==1 && myCstat!=BRepCheck_NotClosed && 
	  isCheckClose && !F.IsNull()) {
	ledge.Clear();
// 	ind = myMapVE.FindIndex(VF);
	ind = myMapVE.FindIndex(aVRef);
	for (TopTools_ListIteratorOfListOfShape itlsh(myMapVE(ind));
	     itlsh.More(); itlsh.Next()) {
	  const TopoDS_Edge & edg = TopoDS::Edge(itlsh.Value());
	  orient = edg.Orientation();
	  if (!theRef.IsSame(edg)) {
	    for (vte.Init(edg,TopAbs_VERTEX);vte.More(); vte.Next()) {
	      TopAbs_Orientation vto = vte.Current().Orientation();
// 	      if (vto == TopAbs_REVERSED && VF.IsSame(vte.Current())) {
	      if (vto == TopAbs_REVERSED && aVRef.IsSame(vte.Current())) {
		ledge.Append(edg);
		break;
	      }
	    }
	  }
	}
// 	ChoixUV(VF, theRef, F, ledge);
	ChoixUV(aVRef, theRef, F, ledge);
	if (ledge.Extent()==0) {
	  theOstat = BRepCheck_NotClosed;
	  if (Update) {
	    BRepCheck::Add(myMap(myShape),theOstat);
	  }
	  return theOstat;
	}
      }
      // Fin controle fermeture 2d

      Index ++;
    }
  }
  if (Update) {
    BRepCheck::Add(myMap(myShape),theOstat);
  }
  return theOstat;
}
//=======================================================================
//function : SelfIntersect
//purpose  : 
//=======================================================================
BRepCheck_Status BRepCheck_Wire::SelfIntersect(const TopoDS_Face& F,
					       TopoDS_Edge& retE1,
					       TopoDS_Edge& retE2,
					       const Standard_Boolean Update)
{


  Standard_Integer i,j,Nbedges;
  Standard_Real first1,last1,first2,last2, tolint;
  gp_Pnt2d pfirst1,plast1,pfirst2,plast2;
  gp_Pnt P3d, P3d2;
  Handle(BRepAdaptor_HSurface) HS;
  Geom2dAdaptor_Curve C1, C2;
  Geom2dInt_GInter      Inter;
  IntRes2d_Domain myDomain1;
  TopTools_IndexedMapOfOrientedShape EMap;
  TopTools_MapOfOrientedShape auxmape;
  //
  //-- on verifie plus loin avec les bonnes tolerances si on n a 
  //-- pas un point dans la tolerance d un vertex.
  tolint = 1.e-10; 
  HS = new BRepAdaptor_HSurface();
  HS->ChangeSurface().Initialize(F,Standard_False);
  //
  for (TopoDS_Iterator Iter1(myShape);Iter1.More();Iter1.Next()) {
    if (Iter1.Value().ShapeType() == TopAbs_EDGE) {
      EMap.Add(Iter1.Value());
    }
  }
  //
  Nbedges=EMap.Extent();
  if (!Nbedges) {
    if (Update) {
      BRepCheck::Add(myMap(myShape),BRepCheck_EmptyWire);
    }
    return(BRepCheck_EmptyWire);
  }
  //
  IntRes2d_Domain *tabDom = new IntRes2d_Domain[Nbedges];
  TColGeom2d_Array1OfCurve tabCur(1,Nbedges);
  Bnd_Array1OfBox2d boxes(1,Nbedges);
  //
  for(i = 1; i <= Nbedges; i++) { 
    const TopoDS_Edge& E1 = TopoDS::Edge(EMap.FindKey(i));
    if (i == 1) {
      Handle(Geom2d_Curve) pcu = BRep_Tool::CurveOnSurface(E1, F, first1, last1);
      if (pcu.IsNull()) {
	retE1=E1;
	if (Update) {
	  BRepCheck::Add(myMap(myShape),BRepCheck_SelfIntersectingWire);
	}
	delete [] tabDom;
	return(BRepCheck_SelfIntersectingWire);
      }
      //
      C1.Load(pcu);
      // To avoid exeption in Segment if C1 is BSpline - IFV
      if(!C1.IsPeriodic()) {
	if(C1.FirstParameter() > first1) {
	  first1 = C1.FirstParameter();
	}
	if(C1.LastParameter()  < last1 ){
	  last1  = C1.LastParameter();
	}
      }
      //
      BRep_Tool::UVPoints(E1, F, pfirst1, plast1);
      myDomain1.SetValues(pfirst1,first1,tolint, plast1,last1,tolint);
      //
      BndLib_Add2dCurve::Add(C1, first1, last1, Precision::PConfusion(), boxes(i));
    }//if (i == 1) {
    else {
      C1.Load(tabCur(i));
      myDomain1 = tabDom[i-1];
    }
    //
    // Self intersect of C1
    Inter.Perform(C1, myDomain1, tolint, tolint);
    //
    if(Inter.IsDone()) { 
      Standard_Integer nbp = Inter.NbPoints();
      //
      for(Standard_Integer p=1;p<=nbp;p++) {
	const IntRes2d_IntersectionPoint& IP=Inter.Point(p);
	const IntRes2d_Transition& Tr1 = IP.TransitionOfFirst();
	const IntRes2d_Transition& Tr2 = IP.TransitionOfSecond();
	if(   Tr1.PositionOnCurve() == IntRes2d_Middle
	   || Tr2.PositionOnCurve() == IntRes2d_Middle) { 
	  //-- Verification des points avec les vraies tolerances (ie Tol en 3d)
	  //-- Si le point d intersection est dans la tolearnce d un des vertex
	  //-- on considere que cette intersection est bonne (pas d erreur)
	  Standard_Boolean localok = Standard_False;
	  Standard_Real f,l;
	  TopLoc_Location L;
	  const Handle(Geom_Curve) ConS = BRep_Tool::Curve(E1,L,f,l);
	  if(!ConS.IsNull()) { 
	    //-- on va tester en 3d. (ParamOnSecond donne le m resultat)
	    P3d = ConS->Value(IP.ParamOnFirst()); 
	    P3d.Transform(L.Transformation());
	    //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 Begin
	  } 
	  else {
	    gp_Pnt2d aP2d  = C1.Value(IP.ParamOnFirst());
	    P3d = HS->Value(aP2d.X(), aP2d.Y());
	  }
	  //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 End
	  TopExp_Explorer ExplVtx;
	  for(ExplVtx.Init(E1,TopAbs_VERTEX); 
	      localok==Standard_False && ExplVtx.More();
	      ExplVtx.Next()) { 
	    gp_Pnt p3dvtt;
	    Standard_Real tolvtt, p3dvttDistanceP3d;
	    //
	    const TopoDS_Vertex& vtt = TopoDS::Vertex(ExplVtx.Current());
	    p3dvtt = BRep_Tool::Pnt(vtt);
	    tolvtt =  BRep_Tool::Tolerance(vtt);
	    tolvtt=tolvtt*tolvtt;
	    p3dvttDistanceP3d=p3dvtt.SquareDistance(P3d);
	    if(p3dvttDistanceP3d <=  tolvtt) { 
	      localok=Standard_True;
	    }
	  }
	  if(localok==Standard_False) { 
	    retE1=E1;
	    if (Update) {
	      BRepCheck::Add(myMap(myShape),BRepCheck_SelfIntersectingWire);
	      }
	    delete [] tabDom;
#ifdef DEB
	    static Standard_Integer numpoint=0;
	    cout<<"point p"<<++numpoint<<" "<<P3d.X()<<" "<<P3d.Y()<<" "<<P3d.Z()<<endl;cout.flush();
#endif
	    return(BRepCheck_SelfIntersectingWire);
	  }
	}
      }
    }// if(Inter.IsDone()) { 
    //
    for(j=i+1; j<=Nbedges; j++) {
      const TopoDS_Edge& E2 = TopoDS::Edge(EMap.FindKey(j));
      if (i == 1) {
	tabCur(j) = BRep_Tool::CurveOnSurface(E2,F,first2,last2);
	if (!tabCur(j).IsNull() && last2 > first2) {
	  C2.Load(tabCur(j));
	  // To avoid exeption in Segment if C2 is BSpline - IFV
	  if(!C2.IsPeriodic()) {
	    if(C2.FirstParameter() > first2) {
	      first2 = C2.FirstParameter();
	    }
	    if(C2.LastParameter()  < last2 ) {
	      last2  = C2.LastParameter();
	    }
	  }
	  //
	  BRep_Tool::UVPoints(E2,F,pfirst2,plast2);
	  tabDom[j-1].SetValues(pfirst2,first2,tolint,plast2,last2,tolint);
	  
	  BndLib_Add2dCurve::Add( C2, first2, last2, Precision::PConfusion(), boxes(j) );
	}
	else {
	  delete [] tabDom;
#ifdef DEB
	  cout<<"BRepCheck_NoCurveOnSurface or BRepCheck_InvalidRange"<<endl;cout.flush();
#endif
	  if(tabCur(j).IsNull()) {
	    return(BRepCheck_NoCurveOnSurface);
	  }
	  return (BRepCheck_InvalidRange);
	}
      }// if (i == 1) {
      else {
	C2.Load(tabCur(j));
      }
      //
      if (boxes(i).IsOut( boxes(j))) {
	continue;
      }
      //modified by NIZNHY-PKV Fri Oct 29 10:09:01 2010f
      if (E1.IsSame(E2)) {
	continue;
      }
      //modified by NIZNHY-PKV Fri Oct 29 10:09:02 2010t
      //
      //-- ************************************************************
      //-- ******* I n t e r s e c t i o n   C 1   e t   C 2   ********
      //-- ************************************************************
      Inter.Perform(C1,myDomain1,C2,tabDom[j-1],tolint,tolint);
      //
      if(Inter.IsDone()) { 
	Standard_Integer nbp, nbs;
	Standard_Real IP_ParamOnFirst, IP_ParamOnSecond;
	IntRes2d_Transition Tr1,Tr2;
	TopTools_ListOfShape CommonVertices;
	TopTools_ListIteratorOfListOfShape itl;
	TopTools_MapOfShape Vmap;
	//
	TopoDS_Iterator it( E1 );
	for (; it.More(); it.Next()) {
	  Vmap.Add( it.Value() );
	}
	//
	it.Initialize( E2 );
	for (; it.More(); it.Next()) {
	  const TopoDS_Shape& V = it.Value();
	  if (Vmap.Contains( V )) {
	    CommonVertices.Append( V );
	  }
	}
	//
	nbp = Inter.NbPoints();
	nbs = Inter.NbSegments();
	IP_ParamOnFirst  = 0.;
	IP_ParamOnSecond = 0.;
	//
	//// **** Points of intersection **** ////
	for (Standard_Integer p = 1; p <= nbp; p++)  {
	  const IntRes2d_IntersectionPoint& IP = Inter.Point(p);
	  IP_ParamOnFirst  = IP.ParamOnFirst();
	  IP_ParamOnSecond = IP.ParamOnSecond();
	  Tr1 = IP.TransitionOfFirst();
	  Tr2 = IP.TransitionOfSecond();
	  if(   Tr1.PositionOnCurve() == IntRes2d_Middle
	     || Tr2.PositionOnCurve() == IntRes2d_Middle)   {
	    //-- Verification des points avec les vraies tolerances (ie Tol en 3d)
	    //-- Si le point d intersection est dans la tolearnce d un des vertex
	    //-- on considere que cette intersection est bonne (pas d erreur)
	    Standard_Boolean localok = Standard_False;  
	    Standard_Real f1,l1, f2, l2;
	    TopLoc_Location L, L2;
	    //
	    const Handle(Geom_Curve) ConS = BRep_Tool::Curve(E1,L,f1,l1);    
	    const Handle(Geom_Curve) ConS2 = BRep_Tool::Curve(E2,L2,f2,l2);  
	    //gka protect against working out of edge range
	    if ( f1-IP_ParamOnFirst > ::Precision::PConfusion() || 
		IP_ParamOnFirst-l1 > ::Precision::PConfusion() || 
		f2-IP_ParamOnSecond > ::Precision::PConfusion() || 
		IP_ParamOnSecond-l2 > ::Precision::PConfusion() ) 
	      continue;
	    Standard_Real tolvtt;
	    //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 Begin
	    if (!ConS.IsNull()) { 
	      P3d = ConS->Value(IP_ParamOnFirst); 
	      P3d.Transform(L.Transformation());
	    } 
	    else {
	      gp_Pnt2d aP2d  = C1.Value(IP_ParamOnFirst);
	      P3d = HS->Value(aP2d.X(), aP2d.Y());
	    }
	    //
	    if (!ConS2.IsNull()) {
	      P3d2 = ConS2->Value(IP_ParamOnSecond); 
	      P3d2.Transform(L2.Transformation());
	    } 
	    else {
	      gp_Pnt2d aP2d  = C2.Value(IP_ParamOnSecond);
	      P3d2 = HS->Value(aP2d.X(), aP2d.Y());
	    }
	    //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 End
	    itl.Initialize( CommonVertices );
	    for (; itl.More(); itl.Next()) {
	      Standard_Real p3dvttDistanceP3d, p3dvttDistanceP3d2;
	      gp_Pnt p3dvtt;
	      //
	      const TopoDS_Vertex& vtt = TopoDS::Vertex(itl.Value());
	      p3dvtt = BRep_Tool::Pnt(vtt);
	      tolvtt =  BRep_Tool::Tolerance(vtt);
	      tolvtt=1.1*tolvtt;
	      tolvtt=tolvtt*tolvtt;
	      p3dvttDistanceP3d  = p3dvtt.SquareDistance(P3d);
	      p3dvttDistanceP3d2 = p3dvtt.SquareDistance(P3d2);
	      //
	      if (p3dvttDistanceP3d<=tolvtt && p3dvttDistanceP3d2<=tolvtt)  { 
		localok = Standard_True;
		break;
	      }
	    }
	    
	    //-- --------------------------------------------------------
	    //-- Verification sur le baillement maximum entre les 2 edges
	    //--
	    //-- On verifie la distance des edges a la courbe joignant 
	    //-- le point d intersection au vertex (s il existe)
	    if (localok == Standard_False && !CommonVertices.IsEmpty()) {
#ifdef DEB	
	      cout << "\n------------------------------------------------------\n" <<endl;
	      cout << "\n--- BRepCheck Wire: AutoIntersection Phase1 -> Erreur \n" <<endl;
	      
#endif
	      Standard_Real distauvtxleplusproche,VParaOnEdge1,VParaOnEdge2;
	      gp_Pnt VertexLePlusProche;
	      //
	      VParaOnEdge1 =0.;
	      VParaOnEdge2 =0.;
	      distauvtxleplusproche=RealLast();
	      //Find the nearest common vertex
	      itl.Initialize( CommonVertices );
	      for (; itl.More(); itl.Next())   {
		Standard_Real disptvtx;
		gp_Pnt p3dvtt;
		//
		const TopoDS_Vertex& vtt = TopoDS::Vertex(itl.Value());
		p3dvtt = BRep_Tool::Pnt(vtt);
		disptvtx = P3d.Distance(p3dvtt);
		if (disptvtx < distauvtxleplusproche)	{
		  VertexLePlusProche = p3dvtt; 
		  distauvtxleplusproche = disptvtx;
		  VParaOnEdge1 = BRep_Tool::Parameter(vtt,E1);
		  VParaOnEdge2 = BRep_Tool::Parameter(vtt,E2);
		}
		// eap: case of closed edge
		else if (IsEqual(distauvtxleplusproche, disptvtx)) {
		  Standard_Real newVParaOnEdge1 = BRep_Tool::Parameter(vtt,E1);
		  Standard_Real newVParaOnEdge2 = BRep_Tool::Parameter(vtt,E2);
		  if (Abs(IP_ParamOnFirst - VParaOnEdge1) + Abs(IP_ParamOnSecond - VParaOnEdge2)
		      >
		      Abs(IP_ParamOnFirst - newVParaOnEdge1) + Abs(IP_ParamOnSecond - newVParaOnEdge2)) {
		    VertexLePlusProche = p3dvtt;
		    VParaOnEdge1 = newVParaOnEdge1;
		    VParaOnEdge2 = newVParaOnEdge2;
		  }
		}
	      }
	      //Patch: extraordinar situation (e.g. tolerance(v) == 0.)
	      //  Modified by skv - Wed Jul 23 12:28:11 2003 OCC1764 Begin
	      // if (VertexLePlusProche.Distance( P3d ) <= gp::Resolution())
	      if (VertexLePlusProche.Distance(P3d)  <= gp::Resolution() ||
		  VertexLePlusProche.Distance(P3d2) <= gp::Resolution()) {
		    //  Modified by skv - Wed Jul 23 12:28:12 2003 OCC1764 End
		localok = Standard_True;
	      }
	      else {
		gp_Lin Lig( VertexLePlusProche, gp_Vec(VertexLePlusProche,P3d) );
		Standard_Real du1 = 0.1*(IP_ParamOnFirst -VParaOnEdge1);
		Standard_Real du2 = 0.1*(IP_ParamOnSecond-VParaOnEdge2);
		Standard_Real maxd1 = 0., maxd2 = 0.;
		Standard_Integer k;
		
		localok = Standard_True;
		Standard_Real tole1 = BRep_Tool::Tolerance(E1);
		for (k = 2; localok && k < 9; k++)	{ 
		  Standard_Real u = VParaOnEdge1 + k*du1;  // voyons deja voir si ca marche
		  gp_Pnt P1;
		  //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 Begin
		  if (!ConS.IsNull()) {
		    P1 = ConS->Value(u);
		    P1.Transform(L.Transformation());
		  } 
		  else {
		    gp_Pnt2d aP2d  = C1.Value(u);
		    P1 = HS->Value(aP2d.X(), aP2d.Y());
		  }
		  //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 End
		  Standard_Real d1 = Lig.Distance(P1);
		  if (d1 > maxd1) {
		    maxd1 = d1;
		  }
		  if (d1 > tole1*2.0){
		    localok = Standard_False;
		  }
		}
		//-- meme chose pour edge2
		//  Modified by skv - Wed Jul 23 12:22:20 2003 OCC1764 Begin
		gp_Dir aTmpDir(P3d2.XYZ().Subtracted(VertexLePlusProche.XYZ()));
		
		Lig.SetDirection(aTmpDir);
		//  Modified by skv - Wed Jul 23 12:22:23 2003 OCC1764 End
		Standard_Real tole2 = BRep_Tool::Tolerance(E2);
		for (k = 2; localok && k < 9; k++) {
		  Standard_Real u = VParaOnEdge2 + k*du2;  // voyons deja voir si ca marche
		  gp_Pnt        P2;
		  //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 Begin
		  if (!ConS2.IsNull()) {
		    P2 = ConS2->Value(u);
		    P2.Transform(L2.Transformation());
		  }
		  else {
		    gp_Pnt2d aP2d  = C2.Value(u);
		    P2 = HS->Value(aP2d.X(), aP2d.Y());
		  }
		  //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 End
		  Standard_Real d2 = Lig.Distance(P2);
		  if (d2 > maxd2) {
		    maxd2 = d2;
		  }
		  if (d2 > tole2*2.0){
		    localok = Standard_False;
		  }
		}
#ifdef DEB
		if(localok) { 
		  printf("--- BRepCheck Wire: AutoIntersection Phase2 -> Bon \n");
		  printf("--- distance Point Vertex : %10.7g (tol %10.7g)\n",distauvtxleplusproche,tolvtt);
		  printf("--- Erreur Max sur E1 : %10.7g  Tol_Edge:%10.7g\n",maxd1,tole1);
		  printf("--- Erreur Max sur E2 : %10.7g  Tol_Edge:%10.7g\n",maxd2,tole2);
		  fflush(stdout);
		}
		else { 
		  printf("--- BRepCheck Wire: AutoIntersection Phase2 -> Erreur \n");
		  printf("--- distance Point Vertex : %10.7g (tol %10.7g)\n",distauvtxleplusproche,tolvtt);
		  printf("--- Erreur Max sur E1 : %10.7g  Tol_Edge:%10.7g\n",maxd1,tole1);
		  printf("--- Erreur Max sur E2 : %10.7g  Tol_Edge:%10.7g\n",maxd2,tole2);
		  fflush(stdout);
		}
#endif
	      } //end of else (construction of the line Lig)
	    } //end of if (localok == Standard_False && !CommonVertices.IsEmpty())
	    //
	    if(localok==Standard_False)	  { 
	      retE1=E1;
	      retE2=E2;
	      if (Update) {
		BRepCheck::Add(myMap(myShape),BRepCheck_SelfIntersectingWire);
		}
#ifdef DEB
	      static Standard_Integer numpoint1=0;
	      cout<<"point p"<<++numpoint1<<" "<<P3d.X()<<" "<<P3d.Y()<<" "<<P3d.Z()<<endl;
	      cout.flush();
#endif
	      delete [] tabDom;
	      return(BRepCheck_SelfIntersectingWire);
	    } //-- localok == False
	  } //end of if(Tr1.PositionOnCurve() == IntRes2d_Middle || Tr2.PositionOnCurve() == IntRes2d_Middle)
	} //end of for (Standard_Integer p=1; p <= nbp; p++)    
	////
	//// **** Segments of intersection **** ////
	for (Standard_Integer s = 1; s <= nbs; ++s) {
	  const IntRes2d_IntersectionSegment& Seg = Inter.Segment(s);
	  if (Seg.HasFirstPoint() && Seg.HasLastPoint())   { 
	    Standard_Boolean localok;
	    Standard_Integer k;
	    IntRes2d_IntersectionPoint PSeg [2];
	    IntRes2d_Position aPCR1, aPCR2;
	    //
	    localok = Standard_False;
	    PSeg[0] = Seg.FirstPoint();
	    PSeg[1] = Seg.LastPoint();
	    // At least one of extremities of the segment must be inside
	    // the tolerance of a common vertex
	    for (k = 0; k < 2; ++k) {
	      IP_ParamOnFirst  = PSeg[k].ParamOnFirst();
	      IP_ParamOnSecond = PSeg[k].ParamOnSecond();
	      Tr1 = PSeg[k].TransitionOfFirst();
	      Tr2 = PSeg[k].TransitionOfSecond();
	      aPCR1=Tr1.PositionOnCurve();
	      aPCR2=Tr2.PositionOnCurve();
	      //
	      if(aPCR1!=IntRes2d_Middle && aPCR2!=IntRes2d_Middle)  {
		GeomAbs_CurveType aCT1, aCT2;
		//ZZ
		aCT1=C1.GetType();
		aCT2=C2.GetType();
		if (aCT1==GeomAbs_Line && aCT2==GeomAbs_Line) {
		  // check for the two lines coincidence
		  Standard_Real aPAR_T, aT11, aT12, aT21, aT22, aT1m, aT2m;
		  Standard_Real aD2, aTolE1, aTolE2,  aTol2, aDot;
		  gp_Lin2d aL1, aL2;
		  gp_Pnt2d aP1m;
		  //
		  aPAR_T=0.43213918;
		  //
		  aTolE1=BRep_Tool::Tolerance(E1);
		  aTolE2=BRep_Tool::Tolerance(E2);
		  aTol2=aTolE1+aTolE2;
		  aTol2=aTol2*aTol2;
		  //
		  aL1=C1.Line();
		  aL2=C2.Line();
		  //
		  aT11=PSeg[0].ParamOnFirst();
		  aT12=PSeg[1].ParamOnFirst();
		  aT21=PSeg[0].ParamOnSecond();
		  aT22=PSeg[1].ParamOnSecond();
		  //
		  aT1m=(1.-aPAR_T)*aT11 + aPAR_T*aT12;
		  aP1m=C1.Value(aT1m);
		  //
		  aD2=aL2.SquareDistance(aP1m);
		  if (aD2<aTol2) {
		    aT2m=ElCLib::Parameter(aL2, aP1m);
		    if (aT2m>aT21 && aT2m<aT22) {
		      const gp_Dir2d& aDir1=aL1.Direction();
		      const gp_Dir2d& aDir2=aL2.Direction();
		      aDot=aDir1*aDir2;
		      if (aDot<0.) {
			aDot=-aDot;
		      }
		      //
		      if ((1.-aDot)<5.e-11){//0.00001 rad
			localok = Standard_False;
			break;// from for (k = 0; k < 2; ++k){...
		      }
		    }//if (aT2m>aT21 && aT2m<aT22) {
		  }//if (aD2<aTol2) {
		}//if (aCT1==GeomAbs_Line && aCT2==GeomAbs_Line) {
		//ZZ
		localok = Standard_True;
		break;
	      }
	      //
	      Standard_Real f,l, tolvtt;
	      TopLoc_Location L, L2;
	      const Handle(Geom_Curve)& ConS = BRep_Tool::Curve(E1,L,f,l);    
	      const Handle(Geom_Curve)& ConS2 = BRep_Tool::Curve(E2,L2,f,l);    
	      //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 Begin
	      if (!ConS.IsNull()) { 
		P3d = ConS->Value(IP_ParamOnFirst); 
		P3d.Transform(L.Transformation());
	      } else {
		gp_Pnt2d aP2d  = C1.Value(IP_ParamOnFirst);
		P3d = HS->Value(aP2d.X(), aP2d.Y());
	      }
	      if (!ConS2.IsNull()) {
		P3d2 = ConS2->Value(IP_ParamOnSecond); 
		P3d2.Transform(L2.Transformation());
	      } else {
		gp_Pnt2d aP2d  = C2.Value(IP_ParamOnSecond);
		P3d2 = HS->Value(aP2d.X(), aP2d.Y());
	      }
	      //  Modified by Sergey KHROMOV - Mon Apr 15 12:34:22 2002 End
	      itl.Initialize( CommonVertices );
	      for (; itl.More(); itl.Next()) {
		Standard_Real p3dvttDistanceP3d, p3dvttDistanceP3d2;
		gp_Pnt p3dvtt;
		//
		const TopoDS_Vertex& vtt = TopoDS::Vertex(itl.Value());
		p3dvtt = BRep_Tool::Pnt(vtt);
		tolvtt =  BRep_Tool::Tolerance(vtt);
		tolvtt=1.1*tolvtt;
		tolvtt=tolvtt*tolvtt;
		p3dvttDistanceP3d  = p3dvtt.SquareDistance(P3d);
		p3dvttDistanceP3d2 = p3dvtt.SquareDistance(P3d2);
		if (p3dvttDistanceP3d <= tolvtt && p3dvttDistanceP3d2 <= tolvtt) { 
		  localok = Standard_True;
		  break;
		}
	      }
	      if (localok == Standard_True) {
		break;
	      }
	    } //end of for (k = 0; k < 2; k++)
	    //
	    if(localok==Standard_False)	  { 
	      retE1=E1;
	      retE2=E2;
	      if (Update) {
		BRepCheck::Add(myMap(myShape),BRepCheck_SelfIntersectingWire);
	      }
#ifdef DEB
	      static Standard_Integer numpoint1=0;
	      cout<<"point p"<<++numpoint1<<" "<<P3d.X()<<" "<<P3d.Y()<<" "<<P3d.Z()<<endl;
	      cout.flush();
#endif
	      delete [] tabDom;
	      return(BRepCheck_SelfIntersectingWire);
	    } //-- localok == False
	  } //end of if(Seg.HasFirstPoint() && Seg.HasLastPoint())
	} //end of for (Standard_Integer s = 1; s <= nbs; p++)
      } //-- Inter.IsDone()
    } //end of for( j = i+1; j<=Nbedges; j++)
  } //end of for(i = 1; i <= Nbedges; i++)
  //
  delete [] tabDom;
  if (Update) {
    BRepCheck::Add(myMap(myShape),BRepCheck_NoError);
  }
  //
  return (BRepCheck_NoError);
}
//=======================================================================
//function : GeometricControls
//purpose  : 
//=======================================================================
void BRepCheck_Wire::GeometricControls(const Standard_Boolean B)
{
  if (myGctrl != B) {
    if (B) {
      myCdone = Standard_False;
    }
    myGctrl = B;
  }
}
//=======================================================================
//function : GeometricControls
//purpose  : 
//=======================================================================
Standard_Boolean BRepCheck_Wire::GeometricControls() const
{
  return myGctrl;
}


//=======================================================================
//function : Propagate
//purpose  : fill <mapE> with edges connected to <edg> through vertices
//           contained in <mapVE>
//=======================================================================
static void Propagate(const TopTools_IndexedDataMapOfShapeListOfShape& mapVE,
		      const TopoDS_Shape& edg,
		      TopTools_MapOfShape& mapE)
{
  if (mapE.Contains(edg)) {
    return;
  }
  mapE.Add(edg); // attention, si oriented == Standard_True, edg doit
                 // etre FORWARD ou REVERSED. Ce n`est pas verifie.
                 // =============
                 // attention, if oriented == Standard_True, <edg> must
                 // be FORWARD or REVERSED. That is not checked.
  
  TopExp_Explorer ex;
  for (ex.Init(edg,TopAbs_VERTEX); ex.More(); ex.Next()) {
    const TopoDS_Vertex& vtx = TopoDS::Vertex(ex.Current());
    // debug jag sur vertex
    Standard_Integer indv = mapVE.FindIndex(vtx);
    if (indv != 0) {
      for (TopTools_ListIteratorOfListOfShape itl(mapVE(indv)); itl.More(); itl.Next()) {
	if (!itl.Value().IsSame(edg) &&
	    !mapE.Contains(itl.Value())) {
	  Propagate(mapVE,itl.Value(),mapE);
	}
      }
    }
  }
}
//=======================================================================
//function : GetOrientation
//purpose  : 
//=======================================================================

static TopAbs_Orientation GetOrientation(const TopTools_MapOfShape& mapE,
					 const TopoDS_Edge& edg)
{
  TopTools_MapIteratorOfMapOfShape itm(mapE);
  for ( ; itm.More(); itm.Next()) {
    if (itm.Key().IsSame(edg)) {
      break;
    }
  }
  return itm.Key().Orientation();
}
//=======================================================================
//function : ChoixUV
//purpose  : 
//=======================================================================
 void ChoixUV(const TopoDS_Vertex& V,
	      const TopoDS_Edge& Edg,
	      const TopoDS_Face& F,
	      TopTools_ListOfShape& L)
{
  TopTools_ListIteratorOfListOfShape It( L );
  while (It.More())
    {
      if (Edg.IsSame( It.Value() ))
	L.Remove( It );
      else
	It.Next();
    }

  Standard_Integer index = 0, imin = 0;
  TopoDS_Edge Evois;
  gp_Pnt2d PntRef, Pnt;
  gp_Vec2d DerRef, Der;
  Standard_Real MinAngle, MaxAngle, angle;
  Standard_Real gpResolution=gp::Resolution();
  TopAbs_Orientation aVOrientation, aEdgOrientation;
#ifndef DEB
  Standard_Real dist2d = 0, p = 0;
#else
  Standard_Real dist2d, p;
#endif
  Standard_Real f, l, parpiv;
  Standard_Real tolv = BRep_Tool::Tolerance(V);
  BRepAdaptor_Surface Ads(F,Standard_False); // no restriction
  Standard_Real ures = Ads.UResolution(tolv);
  Standard_Real vres = Ads.VResolution(tolv);
  Standard_Real tol = Max(ures,vres);
  if(tol<=0.0) { 
#ifdef DEB 
    //-- lbr le 29 jan 98 
    cout<<"BRepCheck_Wire : UResolution et VResolution = 0.0 (Face trop petite ?)"<<endl;cout.flush();
#endif
  }
  else {
    tol += tol; //pour YFR.
  }
  //
  Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(Edg, F, f, l);
  if (C2d.IsNull()) {// JAG 10.12.96
    return;
  }
  
  aVOrientation=V.Orientation();
  aEdgOrientation=Edg.Orientation();

  parpiv =(aVOrientation==aEdgOrientation) ? f : l;
      
  MinAngle = RealLast();
  MaxAngle = RealFirst();

  CurveDirForParameter(C2d, parpiv, PntRef, DerRef);

  if (aVOrientation != aEdgOrientation){
    DerRef.Reverse();
  }
  //
  It.Initialize(L);
  for (; It.More(); It.Next()) {
    index++;
    const TopoDS_Edge& aE=TopoDS::Edge(It.Value());
    C2d = BRep_Tool::CurveOnSurface(aE, F, f, l);
    if(C2d.IsNull()) {
      continue;
    }

    p =(aVOrientation != aE.Orientation()) ? f : l;
    //
    Pnt = C2d->Value(p);
    dist2d = Pnt.Distance( PntRef );
    if (dist2d > tol){
      continue;
    }
    //
    CurveDirForParameter(C2d, p, Pnt, Der);
    
    if (aVOrientation == aE.Orientation()){
      Der.Reverse();
    }
    
    if (DerRef.Magnitude() <= gpResolution || 
	Der.Magnitude() <= gpResolution){
      continue;
    }
    //
    angle = DerRef.Angle( Der );
    angle *= -1.;
    if (angle < 0.)
      angle += 2.*PI;
    
    if (F.Orientation() == TopAbs_FORWARD) { 
      if (angle < MinAngle) {
	imin = index;
	MinAngle = angle;
      }
    } 
    else { //F.Orientation() != TopAbs_FORWARD
      if (angle > MaxAngle){
	imin = index;
	MaxAngle = angle;
      }
    }
  }//end of for
  //
  // Mise a jour ledge
  if (imin == 0)
    if (L.Extent() == 1) {
      Standard_Boolean onjette = 0; //all right
      Evois = TopoDS::Edge(L.First());
      if (dist2d > tol) {
#ifdef DEB 
	cout<<"BRepCheckWire : controle fermeture en 2d --> faux"<<endl;cout.flush();
#endif
	if(Evois.IsNull() || BRep_Tool::Degenerated(Edg) ||
	   BRep_Tool::Degenerated(Evois)){
	  onjette = 1; //bad
	}
	else {
	  Ads.Initialize(F);
	  Standard_Real dumax = 0.01 * (Ads.LastUParameter() - Ads.FirstUParameter());
	  Standard_Real dvmax = 0.01 * (Ads.LastVParameter() - Ads.FirstVParameter());
	  Standard_Real dumin = Abs(Pnt.X() - PntRef.X());
	  Standard_Real dvmin = Abs(Pnt.Y() - PntRef.Y());
	  if(dumin > dumax || dvmin > dvmax){
	    onjette = 1;
	  }
	  else {
	    BRepAdaptor_Curve bcEdg(Edg,F);
	    BRepAdaptor_Curve bcEvois(Evois,F);
	    gp_Pnt pEdg = bcEdg.Value(parpiv);
	    gp_Pnt pEvois = bcEvois.Value(p);
	    Standard_Real d3d = pEvois.Distance(pEdg);
#ifdef DEB
	    cout<<"point P            "<<pEdg.X()<<" "<<pEdg.Y()<<" "<<pEdg.Z()<<endl;
	    cout<<"distance 3d      : "<<d3d<<endl;
	    cout<<"tolerance vertex : "<<tolv<<endl;
	    cout.flush();
#endif
	    //if(d3d > tolv){
	    if(d3d > 2.*tolv){
	      onjette = 1;
	    }
#ifdef DEB
	    else
	      cout<<"controle fermeture en 3d --> ok"<<endl;cout.flush();
#endif
	  }
	}
      } //if (dist2d > tol)
      else {//angle was not defined but points are close
	onjette = 0;
      }
      if(onjette) {
#ifdef DEB
	cout<<"controle fermeture en 3d --> faux"<<endl;cout.flush();
#endif
	L.Clear();
      }
    }
    else {
      L.Clear();
    }
  else  {
    index = 1;
    while (index < imin) {
      L.RemoveFirst();
      index++;
    }
    It.Initialize(L);
    It.Next();
    while (It.More())
      L.Remove(It);
  }
}
//=======================================================================
//function : CurveDirForParameter
//purpose  : 
//=======================================================================
void CurveDirForParameter(const Handle(Geom2d_Curve)& aC2d,
			  const Standard_Real aPrm,
			  gp_Pnt2d& Pnt,
			  gp_Vec2d& aVec2d)
{
  Standard_Real aTol=gp::Resolution();
  Standard_Integer i;

  aC2d->D1(aPrm, Pnt, aVec2d);
  //
  if (aVec2d.Magnitude() <= aTol) {
    for (i = 2; i <= 100; i++){
      aVec2d = aC2d->DN(aPrm, i);
      if (aVec2d.Magnitude() > aTol) {
	break;
      }
    }
  }
}

//  Modified by Sergey KHROMOV - Wed May 22 10:44:06 2002 OCC325 Begin
//=======================================================================
//function : GetPnts2d
//purpose  : this function returns the parametric points of theVertex on theFace.
//           If theVertex is a start and end vertex of theEdge hasSecondPnt
//           becomes Standard_True and aPnt2 returns the second parametric point.
//           Returns Standard_True if paraametric points are successfully found.
//=======================================================================

static Standard_Boolean GetPnt2d(const TopoDS_Vertex    &theVertex,
				 const TopoDS_Edge      &theEdge,
				 const TopoDS_Face      &theFace,
				       gp_Pnt2d         &aPnt)
{
  Handle(Geom2d_Curve) aPCurve;
  Standard_Real        aFPar;
  Standard_Real        aLPar;
  Standard_Real        aParOnEdge;
  TopoDS_Vertex        aFirstVtx;
  TopoDS_Vertex        aLastVtx;

  TopExp::Vertices(theEdge, aFirstVtx, aLastVtx);

  if (!theVertex.IsSame(aFirstVtx) && !theVertex.IsSame(aLastVtx))
    return Standard_False;

  aPCurve = BRep_Tool::CurveOnSurface(theEdge, theFace, aFPar, aLPar);

  if (aPCurve.IsNull())
    return Standard_False;

  aParOnEdge = BRep_Tool::Parameter(theVertex, theEdge);
  aPnt       = aPCurve->Value(aParOnEdge);

  return Standard_True;
}

//=======================================================================
//function : Closed2dForPeriodicFace
//purpose  : Checks the distance between first point of the first edge
//           and last point of the last edge in 2d for periodic face.
//=======================================================================
static Standard_Boolean IsClosed2dForPeriodicFace
                        (const TopoDS_Face   &theFace,
			 const gp_Pnt2d      &theP1,
			 const gp_Pnt2d      &theP2,
			 const TopoDS_Vertex &theVertex)
{
// Check 2d distance for periodic faces with seam edge.
// Searching for seam edges
  TopTools_ListOfShape aSeamEdges;
  TopTools_MapOfShape  NotSeams;
  TopTools_MapOfShape  ClosedEdges;
  TopExp_Explorer      anExp(theFace, TopAbs_EDGE);

  for (;anExp.More(); anExp.Next()) {
    TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current());

    if (NotSeams.Contains(anEdge))
      continue;

    if (!IsOriented(anEdge) ||
	!BRep_Tool::IsClosed(anEdge, theFace)) {
      NotSeams.Add(anEdge);
      continue;
    }

    if (!ClosedEdges.Add(anEdge))
      aSeamEdges.Append(anEdge);
  }

  if (aSeamEdges.Extent() == 0)
    return Standard_True;

// check if theVertex lies on one of the seam edges
  BRepAdaptor_Surface aFaceSurface (theFace, Standard_False);
  Standard_Real       aTol      = BRep_Tool::Tolerance(theVertex);
  Standard_Real       aUResol   = aFaceSurface.UResolution(aTol);
  Standard_Real       aVResol   = aFaceSurface.VResolution(aTol);
  Standard_Real       aVicinity = Sqrt(aUResol*aUResol + aVResol*aVResol);
  Standard_Real       aDistP1P2 = theP1.Distance(theP2);


  TopTools_ListIteratorOfListOfShape anIter(aSeamEdges);

  for (; anIter.More(); anIter.Next()) {
    TopoDS_Edge aSeamEdge = TopoDS::Edge(anIter.Value());

    anExp.Init(aSeamEdge, TopAbs_VERTEX);
    for (; anExp.More(); anExp.Next()) {
      const TopoDS_Shape &aVtx = anExp.Current();

// We found an edge. Check the distance between two given points
//  to be lower than the computed tolerance.
      if (IsOriented(aVtx) && aVtx.IsSame(theVertex)) {
	gp_Pnt2d         aPnt1;
	gp_Pnt2d         aPnt2;
	Standard_Real    a2dTol;

	if (!GetPnt2d(theVertex, aSeamEdge, theFace, aPnt1))
	  continue;

	aSeamEdge = TopoDS::Edge(aSeamEdge.Reversed());

	if (!GetPnt2d(theVertex, aSeamEdge, theFace, aPnt2))
	  continue;

	a2dTol = aPnt1.Distance(aPnt2)*1.e-2;
	a2dTol = Max(a2dTol, aVicinity);

	if (aDistP1P2 > a2dTol)
	  return Standard_False;
      }
    }
  }

  return Standard_True;
}
//  Modified by Sergey KHROMOV - Thu Jun 20 10:58:05 2002 End