summaryrefslogtreecommitdiff
path: root/src/STEPCAFControl/STEPCAFControl_Reader.cxx
blob: 17e4290e58f841ca5a1d0ccc097a32f7e5bda07d (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
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
// File:	STEPCAFControl_Reader.cxx
// Created:	Tue Aug 15 12:42:41 2000
// Author:	Andrey BETENEV
//		<abv@doomox.nnov.matra-dtv.fr>

#include <STEPCAFControl_Reader.ixx>

#include <Quantity_Color.hxx>
#include <TCollection_HAsciiString.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopoDS_Compound.hxx>

#include <Transfer_TransientProcess.hxx>
#include <TransferBRep.hxx>
#include <Transfer_Binder.hxx>
#include <Interface_InterfaceModel.hxx>
#include <XSControl_TransferReader.hxx>

#include <StepBasic_Product.hxx>
#include <StepBasic_ProductDefinition.hxx>
#include <StepBasic_ProductDefinitionRelationship.hxx>
#include <StepBasic_ProductDefinitionFormation.hxx>
#include <StepShape_ContextDependentShapeRepresentation.hxx>
#include <StepShape_ShapeDefinitionRepresentation.hxx>
#include <StepShape_ShapeDefinitionRepresentation.hxx>
#include <StepRepr_ProductDefinitionShape.hxx>
#include <StepRepr_PropertyDefinition.hxx>
#include <StepRepr_ShapeAspect.hxx>
#include <StepRepr_MeasureRepresentationItem.hxx>
#include <StepRepr_DescriptiveRepresentationItem.hxx>
#include <StepVisual_StyledItem.hxx>
#include <StepAP214_AppliedExternalIdentificationAssignment.hxx>

#include <STEPConstruct.hxx>
#include <STEPConstruct_Styles.hxx>
#include <STEPConstruct_ExternRefs.hxx>
#include <STEPConstruct_UnitContext.hxx>
#include <STEPCAFControl_Controller.hxx>
#include <STEPCAFControl_DataMapOfSDRExternFile.hxx>

#include <TDataStd_Name.hxx>
#include <TDF_Label.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <XCAFDoc_DimTolTool.hxx>
#include <XCAFDoc_MaterialTool.hxx>
#include <XCAFDoc_DataMapOfShapeLabel.hxx>
#include <STEPConstruct_ValidationProps.hxx>
#include <StepRepr_Representation.hxx>
#include <XCAFDoc_Area.hxx>
#include <XCAFDoc_Volume.hxx>
#include <XCAFDoc_Centroid.hxx>
#include <StepVisual_PresentationLayerAssignment.hxx>
#include <TColStd_HSequenceOfTransient.hxx>
#include <StepVisual_LayeredItem.hxx>
#include <XCAFDoc_LayerTool.hxx>
#include <Interface_EntityIterator.hxx>
#include <StepRepr_ShapeRepresentationRelationship.hxx>
#include <STEPConstruct_Assembly.hxx>
#include <TDF_Tool.hxx>
#include <StepVisual_Invisibility.hxx>
#include <TDataStd_UAttribute.hxx>
#include <XCAFDoc.hxx>
#include <OSD_Path.hxx>
#include <TColStd_SequenceOfHAsciiString.hxx>

#include <TDataStd_TreeNode.hxx>
#include <TNaming_NamedShape.hxx>
#include <BRep_Builder.hxx>

#include <STEPCAFControl_DataMapOfShapePD.hxx>
#include <STEPCAFControl_DataMapOfPDExternFile.hxx>
#include <StepVisual_PresentationStyleByContext.hxx>
#include <StepVisual_StyleContextSelect.hxx>
#include <StepRepr_RepresentedDefinition.hxx>
#include <StepRepr_CharacterizedDefinition.hxx>
#include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
#include <XCAFDoc_GraphNode.hxx>
#include <STEPCAFControl_Reader.hxx>

// skl 21.08.2003 for reading G&DT
#include <StepShape_DimensionalSize.hxx>
#include <StepDimTol_GeometricTolerance.hxx>
#include <StepShape_EdgeCurve.hxx>
#include <StepShape_DimensionalCharacteristicRepresentation.hxx>
#include <StepShape_ShapeDimensionRepresentation.hxx>
#include <StepRepr_ValueRange.hxx>
#include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
#include <StepBasic_MeasureWithUnit.hxx>
#include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
#include <StepDimTol_ModifiedGeometricTolerance.hxx>
#include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
//#include <StepRepr_CompoundItemDefinition.hxx>
//#include <StepRepr_CompoundItemDefinitionMember.hxx>
#include <TColStd_HArray1OfTransient.hxx>
#include <StepRepr_HArray1OfRepresentationItem.hxx>
#include <TColStd_IndexedDataMapOfTransientTransient.hxx>
//#include <StepBasic_ConversionBasedUnit.hxx>
#include <StepBasic_Unit.hxx>
#include <StepBasic_NamedUnit.hxx>
#include <StepBasic_SiUnit.hxx>
#include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
#include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
#include <StepBasic_DerivedUnit.hxx>
#include <StepBasic_DerivedUnitElement.hxx>
#include <StepBasic_MeasureValueMember.hxx>

//#include <TDataStd_Real.hxx>
//#include <TDataStd_Constraint.hxx>
//#include <TDataStd_ConstraintEnum.hxx>
//#include <TNaming_Tool.hxx>
//#include <AIS_InteractiveObject.hxx>
//#include <TPrsStd_ConstraintTools.hxx>
//#include <AIS_DiameterDimension.hxx>
//#include <TPrsStd_Position.hxx>
//#include <TPrsStd_AISPresentation.hxx>
//#include <TNaming_Builder.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <StepShape_AdvancedFace.hxx>
#include <StepDimTol_HArray1OfDatumReference.hxx>
#include <StepDimTol_DatumReference.hxx>
#include <StepDimTol_Datum.hxx>
#include <StepDimTol_DatumFeature.hxx>
#include <StepRepr_ShapeAspectRelationship.hxx>

#include <StepDimTol_AngularityTolerance.hxx>
#include <StepDimTol_CircularRunoutTolerance.hxx>
#include <StepDimTol_CoaxialityTolerance.hxx>
#include <StepDimTol_ConcentricityTolerance.hxx>
#include <StepDimTol_ParallelismTolerance.hxx>
#include <StepDimTol_PerpendicularityTolerance.hxx>
#include <StepDimTol_SymmetryTolerance.hxx>
#include <StepDimTol_TotalRunoutTolerance.hxx>
#include <StepDimTol_CylindricityTolerance.hxx>
#include <StepDimTol_FlatnessTolerance.hxx>
#include <StepDimTol_LineProfileTolerance.hxx>
#include <StepDimTol_PositionTolerance.hxx>
#include <StepDimTol_RoundnessTolerance.hxx>
#include <StepDimTol_StraightnessTolerance.hxx>
#include <StepDimTol_SurfaceProfileTolerance.hxx>

#include <StepShape_SolidModel.hxx>
#include <StepShape_ShellBasedSurfaceModel.hxx>
#include <StepShape_GeometricSet.hxx>

//#include <BRepTools.hxx>


//=======================================================================
//function : STEPCAFControl_Reader
//purpose  : 
//=======================================================================

STEPCAFControl_Reader::STEPCAFControl_Reader ():
       myColorMode( Standard_True ),
       myNameMode ( Standard_True ),
       myLayerMode( Standard_True ),
       myPropsMode( Standard_True ),
       myGDTMode  ( Standard_True ),
       myMatMode  ( Standard_True )
{
  STEPCAFControl_Controller::Init();
  myFiles = new STEPCAFControl_DictionaryOfExternFile;
}


//=======================================================================
//function : STEPCAFControl_Reader
//purpose  : 
//=======================================================================

STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
					      const Standard_Boolean scratch) :
       myColorMode( Standard_True ),
       myNameMode ( Standard_True ),
       myLayerMode( Standard_True ),
       myPropsMode( Standard_True ),
       myGDTMode  ( Standard_True ),
       myMatMode  ( Standard_True )
{
  STEPCAFControl_Controller::Init();
  Init ( WS, scratch );
}


//=======================================================================
//function : Init
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
				  const Standard_Boolean scratch)
{
// necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
  myReader.SetWS (WS,scratch);
  myFiles = new STEPCAFControl_DictionaryOfExternFile;
}


//=======================================================================
//function : ReadFile
//purpose  : 
//=======================================================================

IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
{
  return myReader.ReadFile ( filename );
}


//=======================================================================
//function : NbRootsForTransfer
//purpose  : 
//=======================================================================

Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
{
  return myReader.NbRootsForTransfer();
}


//=======================================================================
//function : TransferOneRoot
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
						         Handle(TDocStd_Document) &doc) 
{
  TDF_LabelSequence Lseq;
  return Transfer ( myReader, num, doc, Lseq );
}


//=======================================================================
//function : Transfer
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
{
  TDF_LabelSequence Lseq;
  return Transfer ( myReader, 0, doc, Lseq );
}


//=======================================================================
//function : Perform
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
						 Handle(TDocStd_Document) &doc)
{
  if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
  return Transfer ( doc );
}
  

//=======================================================================
//function : Perform
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
						 Handle(TDocStd_Document) &doc)
{
  if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
  return Transfer ( doc );
}
  

//=======================================================================
//function : ExternFiles
//purpose  : 
//=======================================================================

const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
{
  return myFiles;
}
	

//=======================================================================
//function : ExternFile
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
						    Handle(STEPCAFControl_ExternFile) &ef) const
{
  ef.Nullify();
  if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
    return Standard_False;
  ef = myFiles->Item ( name );
  return Standard_True;
}


//=======================================================================
//function : Reader
//purpose  : 
//=======================================================================

STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
{
  return myReader;
}
  

//=======================================================================
//function : Reader
//purpose  : 
//=======================================================================

const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
{
  return myReader;
}
  

//=======================================================================
//function : FillShapesMap
//purpose  : auxiliary: fill a map by all compounds and their components
//=======================================================================

static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
{
  TopoDS_Shape S0 = S;
  TopLoc_Location loc;
  S0.Location ( loc );
  map.Add ( S0 );
  if ( S.ShapeType() != TopAbs_COMPOUND ) return;
  for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
    FillShapesMap ( it.Value(), map );
}


//=======================================================================
//function : Transfer
//purpose  : basic working method
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
						  const Standard_Integer nroot,
						  Handle(TDocStd_Document) &doc,
						  TDF_LabelSequence &Lseq,
						  const Standard_Boolean asOne)
{
  reader.ClearShapes();
  Standard_Integer i;
  
  // Read all shapes
  Standard_Integer num = reader.NbRootsForTransfer();
  if ( num <=0 ) return Standard_False;
  if ( nroot ) {
    if ( nroot > num ) return Standard_False;
    reader.TransferOneRoot ( num );
  }
  else {
    for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
  }
  num = reader.NbShapes();
  if ( num <=0 ) return Standard_False;

  // Fill a map of (top-level) shapes resulting from that transfer
  // Only these shapes will be considered further
  TopTools_MapOfShape ShapesMap, NewShapesMap;
  for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
  
  // Collect information on shapes originating from SDRs
  // this will be used to distinguish compounds representing assemblies
  // from the ones representing hybrid models and shape sets
  STEPCAFControl_DataMapOfShapePD ShapePDMap;
  STEPCAFControl_DataMapOfPDExternFile PDFileMap;
  Handle(Interface_InterfaceModel) Model = reader.Model();
  Handle(Transfer_TransientProcess) TP = reader.WS()->TransferReader()->TransientProcess();
  Standard_Integer nb = Model->NbEntities();

  Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;

  for (i = 1; i <= nb; i ++) {
    Handle(Standard_Transient) enti = Model->Value(i);
    if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
      // sequence for acceleration ReadMaterials
      SeqPDS->Append(enti);
    }
    if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
      Handle(StepBasic_ProductDefinition) PD = 
        Handle(StepBasic_ProductDefinition)::DownCast(enti);
      Standard_Integer index = TP->MapIndex(PD);
      if ( index >0 ) {
        Handle(Transfer_Binder) binder = TP->MapItem (index);
        TopoDS_Shape S = TransferBRep::ShapeResult(binder);
        if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
          NewShapesMap.Add(S);
          ShapePDMap.Bind ( S, PD ); 
          Handle(STEPCAFControl_ExternFile) EF;
          PDFileMap.Bind ( PD, EF );
        }
      }
    }
    if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
      Standard_Integer index = TP->MapIndex(enti);
      if ( index >0 ) {
        Handle(Transfer_Binder) binder = TP->MapItem (index);
        TopoDS_Shape S = TransferBRep::ShapeResult(binder);
        if ( ! S.IsNull() && ShapesMap.Contains(S) )
          NewShapesMap.Add(S);
      }
    }
  }

  // get directory name of the main file
  OSD_Path mainfile ( reader.WS()->LoadedFile() );
  mainfile.SetName ( "" );
  mainfile.SetExtension ( "" );
  TCollection_AsciiString dpath;
  mainfile.SystemName ( dpath );

  // Load external references (only for relevant SDRs)
  // and fill map SDR -> extern file
  STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
  ExtRefs.LoadExternRefs();
  for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
    // check extern ref format
    Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
    if ( ! format.IsNull() ) {
      static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
      static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
      if ( ! format->IsSameString ( ap203, Standard_False ) && 
	   ! format->IsSameString ( ap214, Standard_False ) ) {
#ifdef DEB
	cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
#else
	continue;
#endif
      }
    }
#ifdef DEB
    else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
#endif
    
    // get and check filename of the current extern ref
    const Standard_CString filename = ExtRefs.FileName(i);

cout<<"filename="<<filename<<endl;

    if ( ! filename || ! filename[0] ) {
#ifdef DEB
      cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
#endif
      continue; // not a valid extern ref
    }

    // compute true path to the extern file
    TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
    if ( fullname.Length() <= 0 ) fullname = filename;

/*    
    char fullname[1024];
    char *mainfile = reader.WS()->LoadedFile();
    if ( ! mainfile ) mainfile = "";
    Standard_Integer slash = 0;
    for ( Standard_Integer k=0; mainfile[k]; k++ )
      if ( mainfile[k] == '/' ) slash = k;
    strncpy ( fullname, mainfile, slash );
    sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
*/
    
    // get and check PD associated with the current extern ref
    Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
    if ( PD.IsNull() ) continue; // not a valid extern ref
    if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
    
    // read extern file (or use existing data) and record its data
    Handle(STEPCAFControl_ExternFile) EF = 
      ReadExternFile ( filename, fullname.ToCString(), doc );
    PDFileMap.Bind ( PD, EF );
  }
  
  // and insert them to the document
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
  if ( STool.IsNull() ) return Standard_False;
  XCAFDoc_DataMapOfShapeLabel map;
  if ( asOne )
    Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
  else {
    for ( i=1; i <= num; i++ ) {
      Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
    }
  }
  
  // read colors
  if ( GetColorMode() )
    ReadColors ( reader.WS(), doc, PDFileMap, map );
  
  // read names
  if ( GetNameMode() )
    ReadNames ( reader.WS(), doc, PDFileMap, map );

  // read validation props
  if ( GetPropsMode() )
    ReadValProps ( reader.WS(), doc, PDFileMap, map );

  // read layers
  if ( GetLayerMode() )
    ReadLayers ( reader.WS(), doc );
  
  // read SHUO entities from STEP model
  if ( GetSHUOMode() )
    ReadSHUOs ( reader.WS(), doc, PDFileMap, map );

  // read GDT entities from STEP model
  if(GetGDTMode())
    ReadGDTs(reader.WS(),doc);

  // read Material entities from STEP model
  if(GetMatMode())
    ReadMaterials(reader.WS(),doc,SeqPDS);

  //  cout << "Ready !!" << endl;
  
  return Standard_True;
}

//=======================================================================
//function : AddShape
//purpose  : 
//=======================================================================

TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
					   const Handle(XCAFDoc_ShapeTool) &STool,
                                           const TopTools_MapOfShape &NewShapesMap,
					   const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
					   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
					   XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
{
  // if shape has already been mapped, just return corresponding label
  if ( ShapeLabelMap.IsBound ( S ) ) {
    return ShapeLabelMap.Find ( S );
  }
  
  // if shape is located, create instance
  if ( ! S.Location().IsIdentity() ) {
    TopoDS_Shape S0 = S;
    TopLoc_Location loc;
    S0.Location ( loc );
    AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
    TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
    ShapeLabelMap.Bind ( S, L );
    return L;
  }
  
  // if shape is not compound, simple add it
  if ( S.ShapeType() != TopAbs_COMPOUND ) {
    TDF_Label L = STool->AddShape ( S, Standard_False );
    ShapeLabelMap.Bind ( S, L );
    return L;
  }
  
  // for compounds, compute number of subshapes and check whether this is assembly
  Standard_Boolean isAssembly = Standard_False;
  Standard_Integer nbComponents = 0;
  TopoDS_Iterator it;
  for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
    TopoDS_Shape Sub0 = it.Value();
    TopLoc_Location loc;
    Sub0.Location ( loc );
    if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
  }

//  if(nbComponents>0) isAssembly = Standard_True;
  
  // check whether it has associated external ref
  TColStd_SequenceOfHAsciiString SHAS;
  if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
    Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
    if ( ! EF.IsNull() ) {
      // (store information on extern refs in the document)
      SHAS.Append(EF->GetName());
      // if yes, just return corresponding label
      if ( ! EF->GetLabel().IsNull() ) {
	// but if components >0, ignore extern ref!
	if ( nbComponents <=0 ) {
	  ShapeLabelMap.Bind ( S, EF->GetLabel() );
          STool->SetExternRefs(EF->GetLabel(),SHAS);
	  return EF->GetLabel();
	}
      }
#ifdef DEB
      if ( ! EF->GetLabel().IsNull() )
        cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
      else if ( nbComponents <=0 ) 
	cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
#endif
    }
  }
  
  // add compound either as a whole,
  if ( ! isAssembly ) {
    TDF_Label L = STool->AddShape ( S, Standard_False );
    if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
    ShapeLabelMap.Bind ( S, L );
    return L;
  }
  
  // or as assembly, component-by-component
  TDF_Label L = STool->NewShape();
  for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
    TopoDS_Shape Sub0 = it.Value();
    TopLoc_Location loc;
    Sub0.Location ( loc );
    TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
    if ( ! subL.IsNull() ) {
      STool->AddComponent ( L, subL, it.Value().Location() );
    }
  }
  if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
  ShapeLabelMap.Bind ( S, L );
  //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941

  return L;
}

//=======================================================================
//function : ReadExternFile
//purpose  : 
//=======================================================================

Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
									 const Standard_CString fullname, 
									 Handle(TDocStd_Document)& doc) 
{
  // if the file is already read, associate it with SDR
  if ( myFiles->HasItem ( file, Standard_True ) ) {
    return myFiles->Item ( file );
  }

#ifdef DEB
  cout << "Reading extern file: " << fullname << endl;
#endif
 
  // create new WorkSession and Reader
  Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
  newWS->SelectNorm ( "STEP" );
  STEPControl_Reader sr ( newWS, Standard_False );
  
  // start to fill the resulting ExternFile structure
  Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
  EF->SetWS ( newWS );
  EF->SetName ( new TCollection_HAsciiString ( file ) );
  
  // read file
  EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
  
  // transfer in single-result mode
  if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
    TDF_LabelSequence labels;
    EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
    if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
  }
  
  // add read file to dictionary
  myFiles->SetItem ( file, EF );
  
  return EF;
}


//=======================================================================
//function : SetColorToSubshape
//purpose  : auxilary
//=======================================================================
static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
			       const TopoDS_Shape & S,
			       const Quantity_Color& col,
			       const XCAFDoc_ColorType type)
{
  for (TopoDS_Iterator it(S); it.More(); it.Next())
    if (! CTool->SetColor( it.Value(), col, type)) break;
}


//=======================================================================
//function : findStyledSR
//purpose  : auxilary
//=======================================================================
static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
                          Handle(StepShape_ShapeRepresentation)& aSR)
{
  // search Shape Represenatation for component styled item
  for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
    Handle(StepVisual_PresentationStyleByContext) PSA = 
      Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
    if ( PSA.IsNull() )
      continue;
    StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
    Handle(StepShape_ShapeRepresentation) aCurrentSR = 
      Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
    if ( aCurrentSR.IsNull() )
      continue;
    aSR = aCurrentSR;
      break;
  }
}


//=======================================================================
//function : ReadColors
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
						    Handle(TDocStd_Document)& Doc,
                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
{
  STEPConstruct_Styles Styles ( WS );
  if ( ! Styles.LoadStyles() ) {
#ifdef DEB
    cout << "Warning: no styles are found in the model" << endl;
#endif
    return Standard_False;
  }
  // searching for invisible items in the model
  Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
  Styles.LoadInvisStyles( aHSeqOfInvisStyle );
  
  Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
  if ( CTool.IsNull() ) return Standard_False;

  // parse and search for color attributes
  Standard_Integer nb = Styles.NbStyles();
  for ( Standard_Integer i=1; i <= nb; i++ ) {
    Handle(StepVisual_StyledItem) style = Styles.Style ( i );
    if ( style.IsNull() ) continue;
    
    Standard_Boolean IsVisible = Standard_True;
    // check the visibility of styled item.
    for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
      if ( style != aHSeqOfInvisStyle->Value( si ) )
        continue;
      // found that current style is invisible.
#ifdef DEB
      cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
#endif
      IsVisible = Standard_False;
      break;
    }

    Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
    // check if it is component style
    Standard_Boolean IsComponent = Standard_False;
    if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
      continue;
    
    // find shape
    TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(), style->Item() );
    Standard_Boolean isSkipSHUOstyle = Standard_False;
    // take shape with real location.
    while ( IsComponent ) {
      // take SR of NAUO
      Handle(StepShape_ShapeRepresentation) aSR;
      findStyledSR( style, aSR );
      // search for SR along model
      if (aSR.IsNull())
        break;
//       Handle(Interface_InterfaceModel) Model = WS->Model();
      Handle(XSControl_TransferReader) TR = WS->TransferReader();
      Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
      Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
      Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
      for (subs.Start(); subs.More(); subs.Next()) {
        aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
        if ( aSDR.IsNull() )
          continue;
        StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
        Handle(StepRepr_ProductDefinitionShape) PDS = 
          Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
        if ( PDS.IsNull() )
          continue;
        StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
        
        Handle(StepRepr_AssemblyComponentUsage) ACU = 
          Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
        // PTV 10.02.2003 skip styled item that refer to SHUO
        if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
          isSkipSHUOstyle = Standard_True;
          break;
        }
        Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
          Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
        if ( NAUO.IsNull() )
          continue;
        
        TopoDS_Shape aSh;
        // PTV 10.02.2003 to find component of assembly CORRECTLY
        STEPConstruct_Tool Tool( WS );
        TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
        aSh = CTool->ShapeTool()->GetShape(aShLab);
//         Handle(Transfer_Binder) binder = TP->Find(NAUO);
//         if ( binder.IsNull() || ! binder->HasResult() )
//           continue;
//         aSh = TransferBRep::ShapeResult ( TP, binder );
        if (!aSh.IsNull()) {
          S = aSh;
          break;
        }
      }
      break;
    }
    if (isSkipSHUOstyle)
      continue; // skip styled item which refer to SHUO
    
    if ( S.IsNull() ) {
#ifdef DEB
      cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is not mapped to shape" << endl;
#endif
      continue;
    }
    
    if ( ! SurfCol.IsNull() ) {
      Quantity_Color col;
      Styles.DecodeColor ( SurfCol, col );
      if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
	SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
    }
    if ( ! BoundCol.IsNull() ) {
      Quantity_Color col;
      Styles.DecodeColor ( BoundCol, col );
      if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
	SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
    }
    if ( ! CurveCol.IsNull() ) {
      Quantity_Color col;
      Styles.DecodeColor ( CurveCol, col );
      if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
	SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
    }
    if ( !IsVisible ) {
      // sets the invisibility for shape.
      TDF_Label aInvL;
      if ( CTool->ShapeTool()->Search( S, aInvL ) )
        CTool->SetVisibility( aInvL, Standard_False );
    }
  }
  CTool->ReverseChainsOfTreeNodes();
  return Standard_True;
}

//=======================================================================
//function : GetLabelFromPD
//purpose  : 
//=======================================================================

static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
				 const Handle(XCAFDoc_ShapeTool) &STool,
				 const Handle(Transfer_TransientProcess) &TP,
				 const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
				 const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
{
  TDF_Label L;
  if ( PDFileMap.IsBound ( PD ) ) {
    Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
    if ( ! EF.IsNull() ) {
      L = EF->GetLabel();
      if ( ! L.IsNull() ) return L;
    }
  }

  TopoDS_Shape S;
  Handle(Transfer_Binder) binder = TP->Find(PD);
  if ( binder.IsNull() || ! binder->HasResult() ) return L;
  S = TransferBRep::ShapeResult ( TP, binder );
  if ( S.IsNull() ) return L;

  if ( S.IsNull() ) return L;
  if ( ShapeLabelMap.IsBound ( S ) )
    L = ShapeLabelMap.Find ( S );
  if ( L.IsNull() )
    STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
  return L;
}

//=======================================================================
//function : FindInstance
//purpose  : 
//=======================================================================

TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
					       const Handle(XCAFDoc_ShapeTool) &STool,
					       const STEPConstruct_Tool &Tool,
					       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
					       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
{
  TDF_Label L;
  
  // get shape resulting from CDSR (in fact, only location is interesting)
  Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
  Handle(Transfer_Binder) binder = TP->Find(NAUO);
  if ( binder.IsNull() || ! binder->HasResult() ) {
#ifdef DEB
    cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
#endif
    return L;
  }
  
  TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
  if ( S.IsNull() ) {
#ifdef DEB
    cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
#endif
    return L;
  }

  // find component`s original label
  Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
  if ( PD.IsNull() ) return L;
  TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
  if ( Lref.IsNull() ) return L;
  
  // find main shape (assembly) label
  PD.Nullify();
  PD = NAUO->RelatingProductDefinition();
  if ( PD.IsNull() ) return L;
  TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
  if ( L0.IsNull() ) return L;
  
  // if CDSR and NAUO are reversed, swap labels
  Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
  Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
  for (subs1.Start(); subs1.More(); subs1.Next()) {
    Handle(StepRepr_ProductDefinitionShape) PDS = 
      Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
    if(PDS.IsNull()) continue;
    Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
    for (subs2.Start(); subs2.More(); subs2.Next()) {
      Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
        Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
      if (CDSRtmp.IsNull()) continue;
      CDSR = CDSRtmp;
    }
  }
  if (CDSR.IsNull()) return L;
//  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
//    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
//  }
  
  // iterate on components to find proper one
  TDF_LabelSequence seq;
  XCAFDoc_ShapeTool::GetComponents ( L0, seq );
  for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
    TDF_Label Lcomp = seq(k), Lref2;
    if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
	Lref2 == Lref &&
	S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
      L = Lcomp;
  }
  
  return L;
}

//=======================================================================
//function : ReadNames
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
						   Handle(TDocStd_Document)& Doc,
						   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
						   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
{
  // get starting data
  Handle(Interface_InterfaceModel) Model = WS->Model();
  Handle(XSControl_TransferReader) TR = WS->TransferReader();
  Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
  if ( STool.IsNull() ) return Standard_False;
  STEPConstruct_Tool Tool ( WS );

  // iterate on model to find all SDRs and CDSRs
  Standard_Integer nb = Model->NbEntities();
  Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
  Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
  Handle(TCollection_HAsciiString) name;
  TDF_Label L;
  for (Standard_Integer i = 1; i <= nb; i++) {
    Handle(Standard_Transient) enti = Model->Value(i);

    // get description of NAUO
    if ( enti->DynamicType() == tNAUO ) {
      L.Nullify();
      Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
	Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
      if(NAUO.IsNull()) continue;
      Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
      for (subs.Start(); subs.More(); subs.Next()) {
        Handle(StepRepr_ProductDefinitionShape) PDS = 
          Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
        if(PDS.IsNull()) continue;
        Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
        if ( PDR.IsNull() ) continue;
        if ( PDR->HasDescription() && 
            PDR->Description()->Length() >0 ) name = PDR->Description();
        else if ( PDR->Name()->Length() >0 ) name = PDR->Name();
        else name = PDR->Id();
      }
      // find proper label
      L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
      if ( L.IsNull() ) continue;
      TCollection_ExtendedString str ( name->String() );
      TDataStd_Name::Set ( L, str );
    }

    // for PD get name of associated product
    if ( enti->DynamicType() == tPD ) {
      L.Nullify();
      Handle(StepBasic_ProductDefinition) PD = 
	Handle(StepBasic_ProductDefinition)::DownCast(enti);
      if(PD.IsNull()) continue;
      Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
      if(Prod->Name()->UsefullLength()>0) name = Prod->Name();
      else name = Prod->Id();
      L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
      if ( L.IsNull() ) continue;
      TCollection_ExtendedString str ( name->String() );
      TDataStd_Name::Set ( L, str );
    }
    // set a name to the document
    //TCollection_ExtendedString str ( name->String() );
    //TDataStd_Name::Set ( L, str );
  }

  return Standard_True;
}

//=======================================================================
//function : GetLabelFromPD
//purpose  : 
//=======================================================================

static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
                                 const Handle(XCAFDoc_ShapeTool) &STool,
                                 const STEPConstruct_ValidationProps &Props,
                                 const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
                                 const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
{
  TDF_Label L;
  if ( PDFileMap.IsBound ( PD ) ) {
    Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
    if ( ! EF.IsNull() ) {
      L = EF->GetLabel();
      if ( ! L.IsNull() ) return L;
    }
  }
  TopoDS_Shape S = Props.GetPropShape ( PD );
  if ( S.IsNull() ) return L;
  if ( ShapeLabelMap.IsBound ( S ) )
    L = ShapeLabelMap.Find ( S );
  if ( L.IsNull() )
    STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
  return L;
}

//=======================================================================
//function : ReadValProps
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
						      Handle(TDocStd_Document)& Doc,
						      const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
						      const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
{
  // get starting data
  Handle(Interface_InterfaceModel) Model = WS->Model();
  Handle(XSControl_TransferReader) TR = WS->TransferReader();
  Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
  if ( STool.IsNull() ) return Standard_False;

  // load props from the STEP model
  TColStd_SequenceOfTransient props;
  STEPConstruct_ValidationProps Props ( WS );
  if ( ! Props.LoadProps ( props ) ) {
#ifdef DEB
    cout << "Warning: no validation props found in the model" << endl;
#endif
    return Standard_False;
  }

  // interpret props one by one
  for (Standard_Integer i = 1; i <= props.Length(); i ++) {
    Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
      Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
    if ( PDR.IsNull() ) continue;

    TDF_Label L;

    Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
    Interface_EntityIterator subs = Props.Graph().Shareds(PD);
    for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
      if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
        Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
        if(PDS.IsNull()) continue;
        // find corresponding NAUO
        Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
        Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
        for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
          if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
            NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
        }
        if ( !NAUO.IsNull() ) {
          L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
          if ( L.IsNull() ) continue;
        }
        else {
          // find corresponding ProductDefinition:
          Handle(StepBasic_ProductDefinition) ProdDef;
          Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
          for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
            if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
              ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
          }
          if ( ProdDef.IsNull() ) continue;
          L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
        }
      }

      if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
        Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
        if(SA.IsNull()) continue;
        // find ShapeRepresentation
        Handle(StepShape_ShapeRepresentation) SR;
        Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
        for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
          Handle(StepRepr_PropertyDefinition) PropD1 = 
            Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
          if(PropD1.IsNull()) continue;
          Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
          for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
            Handle(StepShape_ShapeDefinitionRepresentation) SDR =
              Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
            if(SDR.IsNull()) continue;
            SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
          }
        }
        if(SR.IsNull()) continue;
        Handle(Transfer_Binder) binder;
        for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
          if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
            Handle(StepShape_SolidModel) SM = 
              Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
            binder = TP->Find(SM);
          }
          else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
            Handle(StepShape_ShellBasedSurfaceModel) SBSM =
              Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
            binder = TP->Find(SBSM);
          }
          else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
            Handle(StepShape_GeometricSet) GS =
              Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
            binder = TP->Find(GS);
          }
        }
        if ( binder.IsNull() || ! binder->HasResult() ) continue;
        TopoDS_Shape S;
        S = TransferBRep::ShapeResult ( TP, binder );
        if(S.IsNull()) continue;
        if ( ShapeLabelMap.IsBound ( S ) )
          L = ShapeLabelMap.Find ( S );
        if ( L.IsNull() )
          STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
      }
    }

    if(L.IsNull()) continue;
      
    // decode validation properties
    Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
    for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
      Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
      Standard_Boolean isArea;
      Standard_Real val;
      gp_Pnt pos;
      if ( Props.GetPropReal ( ent, val, isArea ) ) {
	if ( isArea ) XCAFDoc_Area::Set ( L, val );
	else XCAFDoc_Volume::Set ( L, val );
      }
      else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
	XCAFDoc_Centroid::Set ( L, pos );
      }
    }
  }
  return Standard_True;
}

//=======================================================================
//function : ReadLayers
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
						    Handle(TDocStd_Document)& Doc) const
{
  Handle(Interface_InterfaceModel) Model = WS->Model();
  Handle(XSControl_TransferReader) TR = WS->TransferReader();
  Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
  if ( STool.IsNull() ) return Standard_False;
  Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
  if ( LTool.IsNull() ) return Standard_False;
  
  Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
  Standard_Integer nb = Model->NbEntities();
  Handle(TCollection_HAsciiString) name;
  
  for (Standard_Integer i = 1; i <= nb; i ++) {
    Handle(Standard_Transient) enti = Model->Value(i);
    if ( ! enti->IsKind ( tSVPLA ) ) continue;
    Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
      Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
    
    Handle(TCollection_HAsciiString) descr = SVPLA->Description();
    Handle(TCollection_HAsciiString) hName = SVPLA->Name();
    TCollection_ExtendedString aLayerName ( hName->String() );
     
    // find a target shape and its label in the document
    for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
      StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
      Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
      if ( binder.IsNull() || ! binder->HasResult() ) continue;
      
      TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
      if ( S.IsNull() ) continue;
	
      TDF_Label shL;
      if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
      LTool->SetLayer ( shL, aLayerName );
    }
    
    // check invisibility
    Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
    for (subs.Start(); subs.More(); subs.Next()) {
      if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
#ifdef DEB
      cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
#endif
      //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
      TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
      Handle(TDataStd_UAttribute) aUAttr;
      aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
    }
  }
  return Standard_True;
}

//=======================================================================
//function : ReadSHUOs
//purpose  : 
//=======================================================================

static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
                                           const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
                                           const Handle(XCAFDoc_ShapeTool)& STool,
                                           const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
                                           const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
                                           TDF_LabelSequence& aLabels)
{
  Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
  Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
  for (subs.Start(); subs.More(); subs.Next()) {
    if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
      subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
      break;
    }
  }
  if (subSHUO.IsNull())
    return Standard_False;
  
  Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
    Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subSHUO->NextUsage());
  if (NUNAUO.IsNull())
    return Standard_False;
//   Handle(Interface_InterfaceModel) Model = WS->Model();
//   Handle(XSControl_TransferReader) TR = WS->TransferReader();
//   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
//   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
//   if ( binder.IsNull() || ! binder->HasResult() )
//     return Standard_False;
//   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
  // get label of NAUO next level
  TDF_Label NULab;
  STEPConstruct_Tool Tool( WS );
  NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
//   STool->Search(NUSh, NUlab);
  if (NULab.IsNull())
    return Standard_False;
  aLabels.Append( NULab );
  // and check by recurse.
  findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
  return Standard_True;
}


//=======================================================================
//function : setSHUOintoDoc
//purpose  : auxilary
//=======================================================================
static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
                                 const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
                                 const Handle(XCAFDoc_ShapeTool)& STool,
                                 const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
                                 const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
{
  TDF_Label aMainLabel;
  // get upper usage NAUO from SHUO.
  Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
    Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
  Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
    Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->NextUsage());
  if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
#ifdef DEB
    cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
#endif
    return aMainLabel;
  }
//   Handle(Interface_InterfaceModel) Model = WS->Model();
//   Handle(XSControl_TransferReader) TR = WS->TransferReader();
//   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
//   TopoDS_Shape UUSh, NUSh;
//   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
//   if ( binder.IsNull() || ! binder->HasResult() )
//     return aMainLabel;
//   UUSh = TransferBRep::ShapeResult ( TP, binder );
//   binder = TP->Find(NUNAUO);
//   if ( binder.IsNull() || ! binder->HasResult() )
//     return aMainLabel;
//   NUSh = TransferBRep::ShapeResult ( TP, binder );

  // get first labels for first SHUO attribute
  TDF_Label UULab, NULab;
  STEPConstruct_Tool Tool( WS );
  UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
  NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
  
//   STool->Search(UUSh, UULab);
//   STool->Search(NUSh, NULab);
  if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
  //create sequence fo labels to set SHUO structure into the document
  TDF_LabelSequence ShuoLabels;
  ShuoLabels.Append( UULab );
  ShuoLabels.Append( NULab );
  // add all other labels of sub SHUO entities
  findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
  // last accord for SHUO
  Handle(XCAFDoc_GraphNode) anSHUOAttr;
  if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
    aMainLabel = anSHUOAttr->Label();
  
  return aMainLabel;
}


//=======================================================================
//function : ReadSHUOs
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
                                                   Handle(TDocStd_Document)& Doc,
                                                   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
                                                   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
{
  // the big part code duplication from ReadColors.
  // It is possible to share this code functionality, just to decide how ???
  Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
  Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
  
  STEPConstruct_Styles Styles ( WS );
  if ( ! Styles.LoadStyles() ) {
#ifdef DEB
    cout << "Warning: no styles are found in the model" << endl;
#endif
    return Standard_False;
  }
  // searching for invisible items in the model
  Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
  Styles.LoadInvisStyles( aHSeqOfInvisStyle );
  // parse and search for color attributes
  Standard_Integer nb = Styles.NbStyles();
  for ( Standard_Integer i=1; i <= nb; i++ ) {
    Handle(StepVisual_StyledItem) style = Styles.Style ( i );
    if ( style.IsNull() ) continue;
    
    Standard_Boolean IsVisible = Standard_True;
    // check the visibility of styled item.
    for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
      if ( style != aHSeqOfInvisStyle->Value( si ) )
        continue;
      // found that current style is invisible.
#ifdef DEB
      cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
#endif
      IsVisible = Standard_False;
      break;
    }

    Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
    // check if it is component style
    Standard_Boolean IsComponent = Standard_False;
    if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
      continue;
    if (!IsComponent)
      continue;
    Handle(StepShape_ShapeRepresentation) aSR;
    findStyledSR( style, aSR );
    // search for SR along model
    if ( aSR.IsNull() )
      continue;
    Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
    Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
    for (subs.Start(); subs.More(); subs.Next()) {
      aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
      if ( aSDR.IsNull() )
        continue;
      StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
      Handle(StepRepr_ProductDefinitionShape) PDS = 
        Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
      if ( PDS.IsNull() )
        continue;
      StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
      Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
        Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
      if ( SHUO.IsNull() )
        continue;
      
      // set the SHUO structure to the document
      TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
      if ( aLabelForStyle.IsNull() ) {
#ifdef DEB
        cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
#endif
        continue;
      }
      // now set the style to the SHUO main label.
      if ( ! SurfCol.IsNull() ) {
        Quantity_Color col;
        Styles.DecodeColor ( SurfCol, col );
        CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
      }
      if ( ! BoundCol.IsNull() ) {
        Quantity_Color col;
        Styles.DecodeColor ( BoundCol, col );
        CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
      }
      if ( ! CurveCol.IsNull() ) {
        Quantity_Color col;
        Styles.DecodeColor ( CurveCol, col );
        CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
      }
      if ( !IsVisible )
        // sets the invisibility for shape.
        CTool->SetVisibility( aLabelForStyle, Standard_False );
      
    } // end search SHUO by SDR
  } // end iterates on styles
      
  return Standard_True;
}


//=======================================================================
//function : GetLengthConversionFactor
//purpose  : 
//=======================================================================
static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
                                                  Standard_Real& afact)
{
  afact=1.;
  if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
  Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
    Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
  Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
  afact = MWUCBU->ValueComponent();
  StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
  if(anUnit2.CaseNum(anUnit2.Value())==1) {
    Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
    if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
      Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
      if(SU->Name()==StepBasic_sunMetre) {
        if(SU->HasPrefix()) 
	  afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
	// convert m to mm
	afact *= 1000.;
      }
    }
  }
  return Standard_True;
}


//=======================================================================
//function : GetMassConversionFactor
//purpose  : 
//=======================================================================
static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
                                                Standard_Real& afact)
{
  afact=1.;
  if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
  Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
    Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
  Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
  afact = MWUCBU->ValueComponent();
  StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
  if(anUnit2.CaseNum(anUnit2.Value())==1) {
    Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
    if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
      Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
      if(SU->Name()==StepBasic_sunGram) {
        if(SU->HasPrefix())
	  afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
      }
    }
  }
  return Standard_True;
}


//=======================================================================
//function : ReadDatums
//purpose  : auxilary
//=======================================================================
static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
                                   const Handle(XCAFDoc_DimTolTool) &DGTTool,
                                   const Interface_Graph &graph,
                                   Handle(Transfer_TransientProcess) &TP,
                                   const TDF_Label TolerL,
                                   const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
{
  if(GTWDR.IsNull()) return Standard_False;
  Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
  if(HADR.IsNull()) return Standard_False;
  for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
    Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
    Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
    if(aDatum.IsNull()) continue;
    Interface_EntityIterator subs4 = graph.Sharings(aDatum);
    for(subs4.Start(); subs4.More(); subs4.Next()) {
      Handle(StepRepr_ShapeAspectRelationship) SAR = 
        Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
      if(SAR.IsNull()) continue;
      Handle(StepDimTol_DatumFeature) DF = 
        Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
      if(DF.IsNull()) continue;
      Interface_EntityIterator subs5 = graph.Sharings(DF);
      Handle(StepRepr_PropertyDefinition) PropDef;
      for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
        PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
      }
      if(PropDef.IsNull()) continue;
      Handle(StepShape_AdvancedFace) AF;
      subs5 = graph.Sharings(PropDef);
      for(subs5.Start(); subs5.More(); subs5.Next()) {
        Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
          Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
        if(!SDR.IsNull()) {
          Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
          if( !Repr.IsNull() && Repr->NbItems()>0 ) {
            Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
            AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
          }
        }
      }
      if(AF.IsNull()) return Standard_False;
      Standard_Integer index = TP->MapIndex(AF);
      TopoDS_Shape aSh;
      if(index >0) {
        Handle(Transfer_Binder) binder = TP->MapItem(index);
        aSh = TransferBRep::ShapeResult(binder);
      }
      if(aSh.IsNull()) continue; 
      TDF_Label shL;
      if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
      DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
    }
  }
  return Standard_True;
}


//=======================================================================
//function : ReadGDTs
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession) &WS,
                                                 Handle(TDocStd_Document)& Doc) const
{
  Handle(Interface_InterfaceModel) Model = WS->Model();
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
  Handle(XSControl_TransferReader) TR = WS->TransferReader();
  Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
  Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( Doc->Main() );
  if ( DGTTool.IsNull() ) return Standard_False;
  
  Standard_Integer nb = Model->NbEntities();
  const Interface_Graph& graph = TP->Graph();
  for(Standard_Integer i=1; i<=nb; i++) {
    Handle(Standard_Transient) ent = Model->Value(i);
    if(ent->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))) {
      Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(ent);
      // find RepresentationItem for current ShapeAspect
      Handle(StepRepr_RepresentationItem) RI;
      Handle(StepRepr_PropertyDefinition) PropD;
      Interface_EntityIterator subs3 = graph.Sharings(SA);
      for(subs3.Start(); subs3.More() && PropD.IsNull(); subs3.Next()) {
        PropD = Handle(StepRepr_PropertyDefinition)::DownCast(subs3.Value());
      }
      if(PropD.IsNull()) continue;
      Interface_EntityIterator subs4 = graph.Sharings(PropD);
      for(subs4.Start(); subs4.More(); subs4.Next()) {
        Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
          Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
        if(!SDR.IsNull()) {
          Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
          if( !Repr.IsNull() && Repr->NbItems()>0 ) {
            RI = Repr->ItemsValue(1);
          }
        }
      }
      if(RI.IsNull()) continue;
      // read DGT entities:
      subs3 = graph.Sharings(SA);
      for(subs3.Start(); subs3.More(); subs3.Next()) {
        if(subs3.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
          // read dimensions
          Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
          if(EC.IsNull()) continue;
          Handle(TCollection_HAsciiString) aName;
          Handle(StepShape_DimensionalSize) DimSize = 
            Handle(StepShape_DimensionalSize)::DownCast(subs3.Value());
          Standard_Real dim1=-1.,dim2=-1.;
          subs4 = graph.Sharings(DimSize);
          for(subs4.Start(); subs4.More(); subs4.Next()) {
            Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
              Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
            if(!DimCharR.IsNull()) {
              Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
              if(!SDimR.IsNull() && SDimR->NbItems()>0) {
                Handle(StepRepr_RepresentationItem) RI = SDimR->ItemsValue(1);
                Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(RI);
                if(!VR.IsNull()) {
                  aName = VR->Name();
                  //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
                  //if(CID.IsNull()) continue;
                  //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
                  //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
                  //if(CIDM.IsNull()) continue;
                  //if(CIDM->ArrTransient().IsNull()) continue;
                  //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
                  //if(CID.CaseMem(CIDM)==1)
                  //  HARI = CID.ListRepresentationItem();
                  //if(CID.CaseMem(CIDM)==2)
                  //  HARI = CID.SetRepresentationItem();
                  Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
                  if(HARI.IsNull()) continue;
                  if(HARI->Length()>0) {
                    Handle(StepRepr_RepresentationItem) RI1 =
                      Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(1));
                    if(RI1.IsNull()) continue;
                    if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
                      Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
                        Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
                      dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
                      StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
                      Standard_Real afact=1.;
                      if(anUnit.IsNull()) continue;
                      if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
                      Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
                      if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
                    }
                  }
                  if(HARI->Length()>1) {
                    Handle(StepRepr_RepresentationItem) RI2 =
                      Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(2));
                    if(RI2.IsNull()) continue;
                    if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
                      Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
                        Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
                      dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
                      StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
                      Standard_Real afact=1.;
                      if(anUnit.IsNull()) continue;
                      if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
                      Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
                      if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
                    }
                  }
                }
              }
            }
          }
          if(dim1<0) continue;
          if(dim2<0) dim2=dim1;
          //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
          // now we know edge_curve and value range therefore
          // we can create corresponding D&GT labels
          Standard_Integer index = TP->MapIndex(EC);
          TopoDS_Shape aSh;
          if(index >0) {
            Handle(Transfer_Binder) binder = TP->MapItem(index);
            aSh = TransferBRep::ShapeResult(binder);
          }
          if(aSh.IsNull()) continue; 
          TDF_Label shL;
          if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
          Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
          arr->SetValue(1,dim1);
          arr->SetValue(2,dim2);
          DGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
        }
        // read tolerances and datums
        else if(subs3.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
          Handle(StepDimTol_GeometricTolerance) GT =
            Handle(StepDimTol_GeometricTolerance)::DownCast(subs3.Value());
          // read common data for tolerance
          //Standard_Real dim = GT->Magnitude()->ValueComponent();
          Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
          if(dim3.IsNull()) continue;
          Standard_Real dim = dim3->ValueComponent();
          StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
          Standard_Real afact=1.;
          if(anUnit.IsNull()) continue;
          if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
          Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
          if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
          //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
          Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
          arr->SetValue(1,dim);
          Handle(TCollection_HAsciiString) aName = GT->Name();
          Handle(TCollection_HAsciiString) aDescription = GT->Description();
          Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
          if(AF.IsNull()) continue;
          Standard_Integer index = TP->MapIndex(AF);
          TopoDS_Shape aSh;
          if(index >0) {
            Handle(Transfer_Binder) binder = TP->MapItem(index);
            aSh = TransferBRep::ShapeResult(binder);
          }
          if(aSh.IsNull()) continue; 
          TDF_Label shL;
          if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
          // read specific data for tolerance
          if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
            Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
              Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(subs3.Value());
            Standard_Integer kind=20;
            Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
              GTComplex->GetModifiedGeometricTolerance();
            if(!MGT.IsNull()) {
              kind = kind + MGT->Modifier()+1;
            }
            TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
            // translate datums connected with this tolerance
            Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
              GTComplex->GetGeometricToleranceWithDatumReference();
            if(!GTWDR.IsNull()) {
              ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
            }
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
            Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
              Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(subs3.Value());
            if(GTWDR.IsNull()) continue;
            Standard_Integer kind = 0;
            if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
            else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
            //cout<<"GTWDR: kind="<<kind<<endl;
            TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
            ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
            Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
              Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(subs3.Value());
            Standard_Integer kind = 35 + MGT->Modifier();
            DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
            DGTTool->SetDimTol(shL,38,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
            DGTTool->SetDimTol(shL,39,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
            DGTTool->SetDimTol(shL,40,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
            DGTTool->SetDimTol(shL,41,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
            DGTTool->SetDimTol(shL,42,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
            DGTTool->SetDimTol(shL,43,arr,aName,aDescription);
          }
          else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
            DGTTool->SetDimTol(shL,44,arr,aName,aDescription);
          }
        }
      }
    }
  }

  return Standard_True;
}


//=======================================================================
//function : FindSolidForPDS
//purpose  : auxilary
//=======================================================================

static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
                                                    const Interface_Graph &graph)
{
  Handle(StepShape_SolidModel) SM;
  Interface_EntityIterator subs = graph.Sharings(PDS);
  Handle(StepShape_ShapeRepresentation) SR;
  for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
    Handle(StepShape_ShapeDefinitionRepresentation) SDR =
      Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
    if(SDR.IsNull()) continue;
    SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
    if(SR.IsNull()) continue;
    for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
      SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
    }
    if(SM.IsNull()) {
      Interface_EntityIterator subs1 = graph.Sharings(SR);
      for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
        Handle(StepRepr_RepresentationRelationship) RR =
          Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
        if(RR.IsNull()) continue;
        Handle(StepShape_ShapeRepresentation) SR2;
        if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
        else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
        if(SR2.IsNull()) continue;
        for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
          SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
        }
      }
    }
  }
  return SM;
}


//=======================================================================
//function : ReadMaterials
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
                                                      Handle(TDocStd_Document)& Doc,
                                                      const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
{
  Handle(Interface_InterfaceModel) Model = WS->Model();
  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
  Handle(XSControl_TransferReader) TR = WS->TransferReader();
  Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
  Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
  if(MatTool.IsNull()) return Standard_False;
  
  const Interface_Graph& graph = TP->Graph();
  for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
    Handle(StepRepr_ProductDefinitionShape) PDS =
      Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
    if(PDS.IsNull()) continue;
    Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
    Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
    Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
    Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
    Standard_Real aDensity=0;
    Interface_EntityIterator subs = graph.Sharings(PDS);
    for(subs.Start(); subs.More(); subs.Next()) {
      Handle(StepRepr_PropertyDefinition) PropD =
        Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
      if(PropD.IsNull()) continue;
      Interface_EntityIterator subs1 = graph.Sharings(PropD);
      for(subs1.Start(); subs1.More(); subs1.Next()) {
        Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
          Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
        if(PDR.IsNull()) continue;
        Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
        if(Repr.IsNull()) continue;
        Standard_Integer ir;
        for(ir=1; ir<=Repr->NbItems(); ir++) {
          Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
          if(RI.IsNull()) continue;
          if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
            // find name and description for material
            Handle(StepRepr_DescriptiveRepresentationItem) DRI =
              Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
            aName = DRI->Name();
            aDescription = DRI->Description();
          }
          if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
            // try to find density for material
            Handle(StepRepr_MeasureRepresentationItem) MRI =
              Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
            aDensity = MRI->Measure()->ValueComponent();
            aDensName = MRI->Name();
            aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
            StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
            if(!aUnit.IsNull()) {
              Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
              if(DU.IsNull()) continue;
              for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
                Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
                Handle(StepBasic_NamedUnit) NU = DUE->Unit();
                Standard_Real afact=1.;
                if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
                  if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
                  // transfer length value for Density from millimeter to santimeter
                  // in order to result density has dimension gram/(sm*sm*sm)
                  aDensity = aDensity*1000.;
                }
                if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
                  if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
                }
              }
            }
          }
        }
      }
    }
    if( aName->Length()==0 ) continue;
    // find shape label amd create Material link
    TopoDS_Shape aSh;
    Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
    if(!SM.IsNull()) {
      Standard_Integer index = TP->MapIndex(SM);
      if(index >0) {
        Handle(Transfer_Binder) binder = TP->MapItem(index);
        if(!binder.IsNull())
          aSh = TransferBRep::ShapeResult(binder);
      }
    }
    if(aSh.IsNull()) continue; 
    TDF_Label shL;
    if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
    MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
  }

  return Standard_True;
}


//=======================================================================
//function : SetColorMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
{
  myColorMode = colormode;
}

//=======================================================================
//function : GetColorMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
{
  return myColorMode;
}

//=======================================================================
//function : SetNameMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
{
  myNameMode = namemode;
}

//=======================================================================
//function : GetNameMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
{
  return myNameMode;
}

//=======================================================================
//function : SetLayerMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
{
  myLayerMode = layermode;
}

//=======================================================================
//function : GetLayerMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
{
  return myLayerMode;
}

//=======================================================================
//function : SetPropsMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
{
  myPropsMode = propsmode;
}

//=======================================================================
//function : GetPropsMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
{
  return myPropsMode;
}

//=======================================================================
//function : SetSHUOMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
{
  mySHUOMode = mode;
}

//=======================================================================
//function : GetSHUOMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
{
  return mySHUOMode;
}

//=======================================================================
//function : SetGDTMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
{
  myGDTMode = gdtmode;
}

//=======================================================================
//function : GetGDTMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
{
  return myGDTMode;
}


//=======================================================================
//function : SetMatMode
//purpose  : 
//=======================================================================

void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
{
  myMatMode = matmode;
}

//=======================================================================
//function : GetMatMode
//purpose  : 
//=======================================================================

Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
{
  return myMatMode;
}