Coin / src / io / SoInput.cpp

   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
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
/**************************************************************************\
 * Copyright (c) Kongsberg Oil & Gas Technologies AS
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/

/*!
  \class SoInput SoInput.h Inventor/SoInput.h
  \brief The SoInput class is an abstraction of file import functionality.
  \ingroup general

  This class takes care of most of the chores of doing data import in Coin.
  It puts a layer of abstraction over the read operations to make it
  transparent for the rest of the Coin code whether or not we're reading
  from a file, from a memory buffer or from stdin.

  SoInput also takes care of checking file validity, aswell as handling
  information about features in the various file formats which are
  supported.

  Example usage:
  \code
  int
  main(void)
  {
    SoDB::init();

    SoInput in;
    if (in.openFile("fab_model.iv")) {
      SoSeparator * root = SoDB::readAll(&in);
      if (root) {
        // Do stuff with the imported scene graph here
        // ...
        return 0;
      }
    }

    return 1;
  }
  \endcode


  Important note: there are several public and protected methods which
  makes it possible to pass in or get returned FILE* structures in
  this class. Do \e not use these methods when the Coin library has
  been compiled as an MSWindows DLL, as passing FILE* instances back
  or forth to DLLs is dangerous and will most likely cause a
  crash. This is an intrinsic limitation for MSWindows DLLs.


  This class supports one environment variable called
  COIN_SOINPUT_SEARCH_GLOBAL_DICT.  When set to "1", the global
  dictionary is searched after the current file dictionary when
  resolving USE keywords. This makes it possible to reference nodes in
  other files. The reason for introducing this feature is that the
  SoFile node rereads the file whenever the name field changes.  The
  first time the file is read, it's possible to reference nodes in the
  parent file, using the USE keyword. But, when the file is reread
  this is no longer possible, since the reading now starts at the
  SoFile node, with an empty dictionary.

  \sa SoOutput, SoDB
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif // HAVE_UNISTD_H
#ifdef HAVE_SYS_TYPES_H
/* According to Coin user Ralf Corsepius, at least SunOS4 needs to
   include sys/types.h before netinet/in.h. There have also been a
   problem report for FreeBSD which seems to indicate that the same
   dependency exists on that platform aswell. */
#include <sys/types.h>
#endif // HAVE_SYS_TYPES_H
#include <ctype.h>

#include <Inventor/SoInput.h>

#include <Inventor/C/tidbits.h>
#include <Inventor/SbName.h>
#include <Inventor/SoDB.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/errors/SoReadError.h>
#include <Inventor/fields/SoField.h>
#include <Inventor/lists/SbStringList.h>
#include <Inventor/misc/SoProto.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/threads/SbStorage.h>

#include "misc/SbHash.h"
#include "tidbitsp.h"
#include "glue/zlib.h"
#include "coindefs.h" // COIN_STUB(), COIN_OBSOLETED()
#include "io/SoInputP.h"
#include "io/SoInput_FileInfo.h"

// This (POSIX-compliant) macro is missing from the Win32 API header
// files for MSVC++ 6.0.
#ifndef S_ISDIR
 // The _S_IFDIR bitpattern is not in the POSIX standard, but MSVC++
 // header files has it.
 #ifdef _S_IFDIR
 #define S_ISDIR(s) (s & _S_IFDIR)
 #else // Ai.
 #error Can neither find nor make an S_ISDIR macro to test stat structures.
 #endif // !_S_IFDIR
#endif // !S_ISDIR

// *************************************************************************

SbStringList * SoInput::dirsearchlist = NULL;

static SbStorage * soinput_tls = NULL;

struct soinput_tls_data {
  SbStringList * searchlist;
  int instancecount;
};

static void
soinput_construct_tls_data(void * closure)
{
  soinput_tls_data * data = (soinput_tls_data*) closure;
  data->searchlist = new SbStringList;
  data->instancecount = 0;
}

static void
soinput_destruct_tls_data(void * closure)
{
  soinput_tls_data * data = (soinput_tls_data*) closure;

  int n = data->searchlist->getLength();
  for (int i = 0; i < n; i++) {
    delete (*data->searchlist)[i];
  }
  delete data->searchlist;
}

// *************************************************************************

SbBool
SoInputP::debug(void)
{
  static int dbg = -1;
  if (dbg == -1) {
    const char * env = coin_getenv("COIN_DEBUG_IMPORT");
    dbg = (env && (atoi(env) > 0)) ? 1 : 0;
  }
  return dbg;
}

SbBool
SoInputP::debugBinary(void)
{
  static int debug = -1;
  if (debug == -1) {
    const char * env = coin_getenv("COIN_DEBUG_BINARY_INPUT");
    debug = (env && (atoi(env) > 0)) ? 1 : 0;
  }
  return debug ? TRUE : FALSE;
}

// *************************************************************************
/*
  Important note: Up until Coin 3.1.1 we used to have a bug in SoInput
  when reading files from other files (SoFile/SoVRMLInline++). The SoInput
  dictionary was global for all files pushed onto the SoInput filestack,
  and DEFs in extra files could therefore overwrite DEFs in the original
  file. This minimal case reproduces this bug:

  #Inventor V2.1 ascii

  Switch {
    whichChild -1
    DEF cube Cube {}
  }

  File { name "minimal_ref.iv" }
  USE cube

  minimal_ref.iv looks something like this:

  #Inventor V2.1 ascii
  DEF cube Info {}

  In older versions of Coin you'll not see the Cube when loading the first
  file.

 */
// *************************************************************************


// Helper function that pops the stack when the current file is at
// EOF.  Then it returns the file at the top of the stack.
SoInput_FileInfo *
SoInputP::getTopOfStackPopOnEOF(void)
{
  SoInput_FileInfo * fi = owner->getTopOfStack();
  assert(fi); // Should always have a top of stack, because the last
              // element on the stack is never removed until the
              // SoInput is closed

  // Pop the stack if end of current file
  if (fi->isEndOfFile()) {
    (void) owner->popFile(); // Only pops if more than one file is on
                             // the stack.
    fi = owner->getTopOfStack();
    assert(fi);
  }

  return fi;
}

// Helperfunctions to handle different filetypes (Inventor, VRML 1.0
// and VRML 2.0).
//
// VRML 1.0 identifiers are defined as:
//
//  VRML 1.0 Node names must not begin with a digit, and must
//  not contain spaces or control characters, single or double
//  quote characters, backslashes, curly braces, the sharp (#)
//  character, the plus (+) character or the period character.
//
//  Field names start with lower case letters, Node types start
//  with upper case. The remainder of the characters may be any
//  printable ascii (21H-7EH) except curly braces {}, square
//  brackets [], single ' or double " quotes, sharp #, backslash
//  \\ plus +, period . or ampersand &.
//
//  In addition to this, we found ',' to be an invalid character in
//  VRML 1.0 names. This was made apparent when reading the following
//  fields on an unknown node:
//
//   fields [SFString test, SFFloat length]
//
//  If ',' is to be a valid character in a name, then the name
//  of the first field would become 'test,', and not just 'test'
//
// The grammar for VRML2 identifiers is:
//
//  nodeNameId ::= Id ;
//  nodeTypeId ::= Id ;
//  fieldId ::= Id ;
//
//  Id ::= IdFirstChar | IdFirstChar IdRestChars ;
//
//  IdFirstChar ::= Any ISO-10646 character encoded using UTF-8
//  except: 0x30-0x39, 0x0-0x20, 0x22, 0x23, 0x27, 0x2b, 0x2c,
//  0x2d, 0x2e, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x7f ;
//
//  IdRestChars ::= Any number of ISO-10646 characters except:
//  0x0-0x20, 0x22, 0x23, 0x27, 0x2c, 0x2e, 0x5b, 0x5c, 0x5d,
//  0x7b, 0x7d, 0x7f ;

SbBool
SoInputP::isNameStartChar(unsigned char c, SbBool validIdent)
{
  if (validIdent) return SbName::isIdentStartChar(c);
  return (c > 0x20); // Not control characters
}

SbBool
SoInputP::isNameStartCharVRML1(unsigned char c, SbBool validIdent)
{
  static unsigned char invalid_vrml1_table[256];
  static unsigned char valid_ident_invalid_vrml1_table[256];

  static int isNameStartCharVRML1Initialized = FALSE;
  if (!isNameStartCharVRML1Initialized) {
    const unsigned char invalid_vrml1[] = {
      0x22, 0x23, 0x27, 0x2b, 0x2c, 0x2e, 0x5c, 0x7b, 0x7d, 0x00 }; // 0x7d = 125
    //'"',  '#',  ''',  '+',  ',',  '.',  '\',  '{',  '}'

    // Differences from invalid_vrml1: '&' , '[', and ']' are now invalid
    const unsigned char valid_ident_invalid_vrml1[] = {
      0x22, 0x23, 0x26, 0x27, 0x2b, 0x2c, 0x2e, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x00 }; // 0x7d = 125
    //'"',  '#',   '&', ''',  '+',  ',',  '.',  '[',  '\',   ']',  '{',  '}'

    for (int c = 0; c < 256; ++c) {
      invalid_vrml1_table[c] = 0;
      valid_ident_invalid_vrml1_table[c] = 0;
    }

    const unsigned char * ptr = invalid_vrml1;
    while (*ptr) { invalid_vrml1_table[*ptr] = 1; ++ptr; }
    ptr = valid_ident_invalid_vrml1;
    while (*ptr) { valid_ident_invalid_vrml1_table[*ptr] = 1; ++ptr; }

    isNameStartCharVRML1Initialized = TRUE;
  }

  if (c <= 0x20) return FALSE; // Control characters
  if (c >= 0x30 && c <= 0x39) return FALSE; // Digits

  if (validIdent) return (valid_ident_invalid_vrml1_table[c] == 0);
  return (invalid_vrml1_table[c] == 0);
}

SbBool
SoInputP::isNameStartCharVRML2(unsigned char c, SbBool validIdent)
{
  static unsigned char invalid_vrml2_table[256];
  static unsigned char valid_ident_invalid_vrml2_table[256];

  static int isNameStartCharVRML2Initialized = FALSE;
  if (!isNameStartCharVRML2Initialized) {
    const unsigned char invalid_vrml2[] = {
      0x22, 0x23, 0x27, 0x2b, 0x2c, 0x2d, 0x2e, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x7f, 0x00 }; // 0x7f = 127
    //'"',  '#',  ''',  '+',  ',',  '-',  '.',  '[',  '\',  ']',  '{',  '}',  ''

    const unsigned char * valid_ident_invalid_vrml2 = invalid_vrml2;

    for (int c = 0; c < 256; ++c) {
      invalid_vrml2_table[c] = 0;
      valid_ident_invalid_vrml2_table[c] = 0;
    }

    const unsigned char * ptr = invalid_vrml2;
    while (*ptr) { invalid_vrml2_table[*ptr] = 1; ++ptr; }
    ptr = valid_ident_invalid_vrml2;
    while (*ptr) { valid_ident_invalid_vrml2_table[*ptr] = 1; ++ptr; }

    isNameStartCharVRML2Initialized = TRUE;
  }

  if (c <= 0x20) return FALSE; // Control characters
  if (c >= 0x30 && c <= 0x39) return FALSE; // Digits

  if (validIdent) return (valid_ident_invalid_vrml2_table[c] == 0);

  // For Coin to be able to load VRML97 (invalid) files that have
  // been generated with illegal names, '+' is considered a valid
  // startcharacter.
  static int non_strict = -1;
  if (non_strict == -1) {
    const char * env = coin_getenv("COIN_NOT_STRICT_VRML97");
    non_strict = env && (atoi(env) > 0);
  }

  if (c == '+' && non_strict) // '+' is considered valid
    return TRUE;

  return (invalid_vrml2_table[c] == 0);
}

// Helperfunction to handle different filetypes (Inventor, VRML 1.0
// and VRML 2.0).
//
// See SoInputP::isIdentStartChar for more information
SbBool
SoInputP::isNameChar(unsigned char c, SbBool validIdent)
{
  if (validIdent) return SbName::isIdentChar(c);
  return (c > 0x20); // Not control characters
}

SbBool
SoInputP::isNameCharVRML1(unsigned char c, SbBool validIdent)
{
  static unsigned char invalid_vrml1_table[256];
  static unsigned char valid_ident_invalid_vrml1_table[256];

  static int isNameCharVRML1Initialized = FALSE;
  if (!isNameCharVRML1Initialized) {
    const unsigned char invalid_vrml1[] = {
      0x22, 0x23, 0x27, 0x2b, 0x2c, 0x2e, 0x5c, 0x7b, 0x7d, 0x00 }; // 0x7d = 125
    //'"',  '#',  ''',  '+',  ',',  '.',  '\',  '{',  '}'

    // Differences from invalid_vrml1: '&' , '[', and ']' are now invalid
    const unsigned char valid_ident_invalid_vrml1[] = {
      0x22, 0x23, 0x26, 0x27, 0x2b, 0x2c, 0x2e, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x00 }; // 0x7d = 125
    //'"',  '#',   '&', ''',  '+',  ',',  '.',  '[',  '\',   ']',  '{',  '}'

    for (int c = 0; c < 256; ++c) {
      invalid_vrml1_table[c] = 0;
      valid_ident_invalid_vrml1_table[c] = 0;
    }

    const unsigned char * ptr = invalid_vrml1;
    while (*ptr) { invalid_vrml1_table[*ptr] = 1; ++ptr; }
    ptr = valid_ident_invalid_vrml1;
    while (*ptr) { valid_ident_invalid_vrml1_table[*ptr] = 1; ++ptr; }

    isNameCharVRML1Initialized = TRUE;
  }

  if (c <= 0x20) return FALSE; // Control characters

  if (validIdent) return (valid_ident_invalid_vrml1_table[c] == 0);
  return (invalid_vrml1_table[c] == 0);
}

SbBool
SoInputP::isNameCharVRML2(unsigned char c, SbBool validIdent)
{
  static unsigned char invalid_vrml2_table[256];
  static unsigned char valid_ident_invalid_vrml2_table[256];

  static int isNameCharVRML2Initialized = FALSE;
  if (!isNameCharVRML2Initialized) {
    // Compared to isIdentStartChar, '+' and '-' have now become valid characters.
    const unsigned char invalid_vrml2[] = {
      0x22, 0x23, 0x27, 0x2c, 0x2e, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x7f, 0x00 }; // 0x7f = 127
    //'"',  '#',  ''',  ',',  '.',  '[',  '\',  ']',  '{',  '}',  ''

    const unsigned char * valid_ident_invalid_vrml2 = invalid_vrml2;

    for (int c = 0; c < 256; ++c) {
      invalid_vrml2_table[c] = 0;
      valid_ident_invalid_vrml2_table[c] = 0;
    }

    const unsigned char * ptr = invalid_vrml2;
    while (*ptr) { invalid_vrml2_table[*ptr] = 1; ++ptr; }
    ptr = valid_ident_invalid_vrml2;
    while (*ptr) { valid_ident_invalid_vrml2_table[*ptr] = 1; ++ptr; }

    isNameCharVRML2Initialized = TRUE;
  }

  if (c <= 0x20) return FALSE; // Control characters

  if (validIdent) return (valid_ident_invalid_vrml2_table[c] == 0);
  return (invalid_vrml2_table[c] == 0);
}

// *************************************************************************

#define PRIVATE(obj) (obj->pimpl)

// *************************************************************************

/*!
  Constructor. If no filepointer is set, input will be read from stdin.
 */
SoInput::SoInput(void)
{
  this->constructorsCommon();
}

/*!
  A constructor which copies the reference mappings from \a dictIn upon
  initialization.
 */
SoInput::SoInput(SoInput * dictIn)
{
  if (dictIn && dictIn->filestack.getLength()) {
    PRIVATE(this)->copied_references = dictIn->getTopOfStack()->getReferences();
  }
  this->constructorsCommon();
}

/*!
  \COININTERNAL
  Do common tasks for the constructors.
*/
void
SoInput::constructorsCommon(void)
{
  // In general, we force app programmers to call SoDB::init(),
  // directly or indirectly, before using any other part of the Coin
  // API. We grant slack in one particular spot, though: it should be
  // possible to construct an SoInput before SoDB::init() has been
  // invoked from app code, as it is common to just have an SoInput on
  // the stack of the main() function.
  //
  // But since SoInput uses threads, which needs to be initialized, we
  // need to check for SoDB::init() here, and invoke it if it was not
  // yet called.
  if (!SoDB::isInitialized()) { SoDB::init(); }

  PRIVATE(this) = new SoInputP(this);

  /* It is not possible to "pass" C library data from the application
     to a MSWin .DLL, so this is necessary to get hold of the stderr
     FILE*. Just using fprintf(stderr, ...) or fprintf(stdout, ...)
     directly might result in a crash when Coin has been compiled as a
     .DLL. */
  this->setFilePointer(coin_get_stdin());

  soinput_tls_data * data = (soinput_tls_data *)soinput_tls->get();
  if (data->instancecount == 0) {
    const SbStringList & dir = *SoInput::dirsearchlist;
    for (int i = 0; i < dir.getLength(); i++) {
      data->searchlist->append(new SbString(dir[i]->getString()));
    }
  }
  data->instancecount++;
}

/*!
  Destructor. Runs SoInput::closeFile() to close any open files.
*/
SoInput::~SoInput(void)
{
  this->closeFile();

  // FIXME: this causes a crash if SoDB::cleanup() was already called,
  // as the atexit-function destructed soinput_tls. This can
  // e.g. happen for the following, common main() structure:
  //
  // int main(void) {
  //   SoDB::init();
  //   [...]
  //   SoInput in;
  //   [...]
  //   SoDB::cleanup();
  //   return 0;
  // }
  //
  // 20041022 mortene.
  soinput_tls_data * data = (soinput_tls_data *)soinput_tls->get();

  data->instancecount--;
  if (data->instancecount == 0) {
    for (int i = 0; i < data->searchlist->getLength(); i++) {
      delete (*data->searchlist)[i];
    }
    data->searchlist->truncate(0);
  }

  delete PRIVATE(this);
}

/*!
  Adds a ROUTE from /a fromnode's \fromfield, to \a tonode's
  tofield. This makes it possible to defines ROUTEs in files
  before the \a fromnode or \a tonode is parsed.

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.0
*/
void
SoInput::addRoute(const SbName & fromnode, const SbName & fromfield,
                  const SbName & tonode, const SbName & tofield)
{
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);

  info->addRoute(fromnode, fromfield,
                   tonode, tofield);
}

/*!
  Searches for PROTO named \a name. This function will only return
  PROTOs that have been read by the current SoInput instance.

  \since Coin 2.3
*/
SoProto *
SoInput::findProto(const SbName & name)
{
  SoInput_FileInfo * info = this->getTopOfStack();
  if (info) {
    return info->findProto(name);
  }
  return NULL;
}

/*!
  Adds a Proto which should be active in the current scope.

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.0
*/
void
SoInput::addProto(SoProto * proto)
{
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);
  proto->ref(); // the PROTO is unref'ed when the file is popped
  info->addProto(proto);
}

/*!
  Pushed a Proto onto the Proto stack. The Proto stack is used during
  VRML2 file parsing.

  \COIN_FUNCTION_EXTENSION

  \sa popProto()
  \since Coin 2.0
*/
void
SoInput::pushProto(SoProto * proto)
{
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);
  info->pushProto(proto);
}

/*!
  Pops a Proto off the Proto stack.

  \COIN_FUNCTION_EXTENSION

  \sa pushProto()
  \since Coin 2.0
*/
void
SoInput::popProto(void)
{
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);
  info->popProto();
}

/*!
  Returns the Proto at the top of the Proto stack.

  \COIN_FUNCTION_EXTENSION

  \sa pushProto()
  \since Coin 2.0
*/
SoProto *
SoInput::getCurrentProto(void) const
{
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);
  return info->getCurrentProto();
}

/*!
  Checks if the next bytes in \a in is the IS keyword. Returns \c TRUE
  if the IS keyword was found, \a readok will be set to \c FALSE if
  some error occured while searching for the IS keyword.

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.0
*/
SbBool
SoInput::checkISReference(SoFieldContainer * container,
                          const SbName & fieldname, SbBool & readok)
{
  readok = TRUE;
  SoProto * proto = this->getCurrentProto();
  SbBool foundis = FALSE;
  if (proto) {
    // The reason for this specific parsing code is that we need
    // to put back whitespace when the IS keyword isn't found.
    // SoInput::read(SbName) skips whitespace automatically...
    // pederb, 2001-10-26
    SbString putback;
    const int STATE_WAIT_I = 0;
    const int STATE_EXPECT_S = 1;
    const int STATE_EXPECT_SPACE = 2;
    const int STATE_FOUND = 3;
    const int STATE_NOTFOUND = 4;
    int state = STATE_WAIT_I;
    do {
      char c;
      readok = this->read(c, FALSE);
      putback += c;
      if (readok) {
        switch (state) {
        case STATE_WAIT_I:
          if (c == 'I') state = STATE_EXPECT_S;
          else if (!coin_isspace(c)) state = STATE_NOTFOUND;
          break;
        case STATE_EXPECT_S:
          if (c == 'S') state = STATE_EXPECT_SPACE;
          else state = STATE_NOTFOUND;
          break;
        case STATE_EXPECT_SPACE:
          if (coin_isspace(c)) state = STATE_FOUND;
          else state = STATE_NOTFOUND;
          break;
        default:
          assert(0 && "should not happen");
          break;
        }
      }
    } while (readok && state != STATE_FOUND && state != STATE_NOTFOUND);

    if (state == STATE_FOUND) {
      foundis = TRUE;
      SbName iname;
      readok = this->read(iname, TRUE);
      if (readok) {
        assert(container->isOfType(SoNode::getClassTypeId()));
        proto->addISReference((SoNode*) container, fieldname, iname);
      }
    }
    else {
      assert(state == STATE_NOTFOUND);
      this->putBack(putback.getString());
      foundis = FALSE;
    }
  }
  return foundis;
}

/*!
  Uses the given file pointer as the input file. The input stack of
  files will be emptied first. Closing a file passed in by it's file
  pointer is the library user's responsibility.

  Important note: do \e not use this method when the Coin library has
  been compiled as an MSWindows DLL, as passing FILE* instances back
  or forth to DLLs is dangerous and will most likely cause a
  crash. This is an intrinsic limitation for MSWindows DLLs.

  Note that it is not allowed to pass a FILE* to a gzip-compressed
  file under Mac OS X.

  \sa openFile(), closeFile()
*/
void
SoInput::setFilePointer(FILE * newFP)
{
  this->closeFile();

  const char * name = (newFP == coin_get_stdin()) ? "<stdin>" : "";
  SoInput_Reader * reader = NULL;

  // delay creating the reader if we're reading from
  // stdin. SoInput_FileInfo will create it when we know that we're
  // actually going to read from stdin
  if (newFP != coin_get_stdin()) {
    reader = SoInput_Reader::createReader(newFP, SbString(name));
  }
  SoInput_FileInfo * newfile =
    new SoInput_FileInfo(reader, PRIVATE(this)->copied_references);
  if (newfile) this->filestack.insert(newfile, 0);
}

/*!
  Open the given file, and make it the only one in the file stack. If
  \a okIfNotFound is \c FALSE, show a warning message if the file could
  not be opened.

  Returns \c TRUE if file could be opened for reading, \c FALSE
  otherwise.

  Note: even if your attempt at opening a file is unsuccessful,
  the SoInput instance will \e not default to reading from stdin after
  a call has been made to this method.

  \sa setFilePointer(), pushFile(), closeFile()
*/
SbBool
SoInput::openFile(const char * fileName, SbBool okIfNotFound)
{
  this->closeFile();

  SbString fullname;
  FILE * fp = this->findFile(fileName, fullname);
  if (fp) {
    SoInput_Reader * reader = SoInput_Reader::createReader(fp, fullname);
    assert(reader);
    SoInput_FileInfo * newfile =
      new SoInput_FileInfo(reader, PRIVATE(this)->copied_references);
    this->filestack.insert(newfile, 0);

    SoInput::addDirectoryFirst(SoInput::getPathname(fullname).getString());
    return TRUE;
  }

  if (!okIfNotFound) { SoReadError::post(this, fullname.getString()); }

  return FALSE;
}

/*!
  Push a new file on top of the stack. Further read operations will take
  place with the new file until it reaches end-of-file, upon when the
  file will be popped of the stack and we'll continue with the next file
  in the stack.

  Returns \c TRUE if the file could be opened for reading, \c FALSE
  otherwise.

  \sa openFile()
*/
SbBool
SoInput::pushFile(const char * filename)
{
  // Get rid of default stdin filepointer if it has not yet been read
  // from. The reason for this is that <stdin> is put on the stack as
  // the default reader by the constructor.  If pushFile is called
  // before <stdin> is read from, it should not be used for reading,
  // so we remove it.  This case happens e.g. when running the code:
  //
  // SoFile * f = new SoFile;
  // f->name = "nonexistant.iv";
  //
  // The name-field has a callback function that calls
  // File::readNamedFile, which calls pushFile. No other files than
  // the pushed file should end up on the stack.
  if (this->filestack.getLength() == 1 &&
      this->filestack[0]->ivFilePointer() == coin_get_stdin() &&
      !PRIVATE(this)->usingstdin) {

    this->closeFile();
  }

  SbString fullname;
  FILE * fp = this->findFile(filename, fullname);
  if (fp) {
    SoInput_Reader * reader = SoInput_Reader::createReader(fp, fullname);
    SoInput_FileInfo * newfile =
      new SoInput_FileInfo(reader, PRIVATE(this)->copied_references);
    this->filestack.insert(newfile, 0);

    SoInput::addDirectoryFirst(SoInput::getPathname(fullname).getString());
    return TRUE;
  }

  SoReadError::post(this, fullname.getString());

  return FALSE;
}

/*!
  Removes all files from the internal stack. Any files opened by
  openFile() or pushFile() will also be closed, but not the files
  coming from setFilePointer() -- which are the responsibility of the
  caller.

  You usually don't need to call this method explicitly, as it will
  automatically be triggered by the SoInput destructor to close any
  open files when the SoInput instance goes out of scope.

  \sa setFilePointer(), openFile(), pushFile()
*/
void
SoInput::closeFile(void)
{
  // Remove all entries, including the default <stdin>.
  while (this->filestack.getLength() > 0) {
    if (!this->fromBuffer() && (this->getCurFile() != coin_get_stdin())) {
      SbString s = SoInput::getPathname(this->getTopOfStack()->ivFilename());
      if (s.getLength()) SoInput::removeDirectory(s.getString());
    }
    delete this->getTopOfStack();
    this->filestack.remove(0);
  }
}

/*!
  Checks to see if the current file is a valid file which can be read
  by the Coin library.

  When reading files through e.g. SoDB::readAll(), this is
  automatically checked for you, so application code should usually
  not need to use this method.
*/
SbBool
SoInput::isValidFile(void)
{
  if (this->getTopOfStack() == NULL) return FALSE;

  // Abstract away the stupidity of providing both isValidFile() and
  // isValidBuffer().
  if (this->getTopOfStack()->isMemBuffer()) return this->isValidBuffer();

  float ver = this->getIVVersion();
  if (ver != 0.0f) return TRUE;
  return FALSE;
}

/*!
  Returns \c TRUE if the current text buffer represents a valid
  iv-file which can be read by the Coin library.

  When reading files through e.g. SoDB::readAll(), this is
  automatically checked for you, so application code should usually
  not need to use this method.
*/
SbBool
SoInput::isValidBuffer(void)
{
  if (this->getTopOfStack() == NULL) return FALSE;

  // Abstract away the stupidity of providing both isValidFile() and
  // isValidBuffer().
  if (!this->getTopOfStack()->isMemBuffer()) return this->isValidFile();

  // Set "validate header" argument to FALSE, as memory buffers should
  // be possible to read even with no header.
  return this->checkHeader(FALSE);
}

/*!
  Returns file pointer of the file on top of the input stack. If the
  "file" is actually a memory buffer, returns \c NULL.

  Important note: do \e not use this method when the Coin library has
  been compiled as an MSWindows DLL, as passing FILE* instances back
  or forth to DLLs is dangerous and will most likely cause a
  crash. This is an intrinsic limitation for MSWindows DLLs.

  \sa getCurFileName()
*/
FILE *
SoInput::getCurFile(void) const
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  return fi->isMemBuffer() ? NULL : fi->ivFilePointer();
}

/*!
  Returns the name of the file on top of the input stack. \c NULL will
  be returned if the toplevel "file" is a memory buffer.

  \sa getCurFile()
*/
const char *
SoInput::getCurFileName(void) const
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  return fi->isMemBuffer() ? NULL : fi->ivFilename().getString();
}

/*!
  Sets up the input stream for reading from the strings pointed to by a
  NULL-terminated array of string pointers.  It is intended for reading
  memory-inlined scene graphs.

  The rationale for this function is that there is a compiler portability
  problem with compiling large, static string buffers.  Some compilers
  have fixed max-lengths on this feature, just over 1KB, which obviously
  becomes a problem real fast.  This method lets you specify the buffer
  as an array of smaller string buffers, typically one string for each
  line in the Inventor file.

  \code
  SoNode *
  makeSceneGraph(void) {
    static const char * inlinescenegraph[] = {
      "#Inventor V2.1 ascii\n",
      "\n",
      "Separator {\n",
      "  Cube {\n",
      "  }\n",
      "}\n",
      NULL
    };
    SoInput in;
    if ( !in.setStringArray(inlinescenegraph) ) return NULL;
    return SoDB::readAll(&in);
  }
  \endcode

  \sa setBuffer()

  \COIN_FUNCTION_EXTENSION

  \since Coin 2.1
*/
void
SoInput::setStringArray(const char * strings[])
{
  size_t bufsize = 0;
  size_t i;
  for (i = bufsize = 0; strings[i] != NULL; i++ )
    bufsize += strlen(strings[i]);
  char * buf = new char [bufsize + 1];
  for (i = bufsize = 0; strings[i] != NULL; i++ ) {
    const size_t len = strlen(strings[i]);
    memcpy(buf+bufsize, strings[i], len);
    bufsize += len;
  }
  this->setBuffer(buf, bufsize);
  SoInput_FileInfo * info = this->getTopOfStack();
  assert(info);
  info->setDeleteBuffer(buf);
}

/*!
  Sets up the input stream for reading from a memory buffer. Closes all
  open files in the file stack first.

  In the original SGI Inventor API this method was designed as "char * bufpointer",
  Coin followed this until Coin 3, but changed the signature to const from Coin 4.0.
*/
void
SoInput::setBuffer(const void * bufpointer, size_t bufsize)
{
  this->closeFile();
  SoInput_Reader * reader = NULL;

  unsigned char * header = (unsigned char*) bufpointer;
  if ((bufsize >= 2) && (header[0] == 0x1f) && (header[1] == 0x8b)) {
    if (cc_zlibglue_available()) {
      reader = new SoInput_GZMemBufferReader(bufpointer, bufsize);
    }
    else {
      SoDebugError::postWarning("SoInput::setBuffer",
                                "Buffer seems to be in gzip format, but zlib support is "
                                "not available.");
    }
  }
  if (reader == NULL) {
    reader = new SoInput_MemBufferReader(bufpointer, bufsize);
  }
  SoInput_FileInfo * newfile =
    new SoInput_FileInfo(reader, PRIVATE(this)->copied_references);
  this->filestack.insert(newfile, 0);
}

/*!
  Returns number of bytes read so far from the current file or memory
  buffer.
  You can only use this method while you're reading the file.
  When the reading has finished, the current file is popped off the
  file stack, and a more or less random number is returned. You
  should use the stat() system call to find the size of a file (or
  fseek() and ftell()).
*/
size_t
SoInput::getNumBytesRead(void) const
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  return fi->getNumBytesParsedSoFar();
}

/*!
  Returns header of current file.
*/
SbString
SoInput::getHeader(void)
{
  (void) this->checkHeader();
  SoInput_FileInfo * fi = this->getTopOfStack();

  return fi ? fi->ivHeader() : SbString("");
}

/*!
  Returns the library version needed to read a file with the given header.
  If the header of the current file is not valid, this method returns
  \a 0.0f.
*/
float
SoInput::getIVVersion(void)
{
  if ( (this->filestack.getLength()==0) || !this->checkHeader()) { return 0.0f; }
  return this->getTopOfStack()->ivVersion();
}

/*!
  Returns \c TRUE if the current file is in binary format.
*/
SbBool
SoInput::isBinary(void)
{
  (void) this->checkHeader(); // Make sure the file header has been
                              // read. checkHeader calls
                              // SoInput_FileInfo::readHeader

  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  return fi->isBinary();
}

/*!
  Get next character in current stream. Returns \c FALSE on end of file.

  \sa read()
*/
SbBool
SoInput::get(char & c)
{
  // It is essential that this method pops on EOF, because this
  // feature is used in e.g SoFile::readNamedFile
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  return (this->checkHeader() && // Strip off file header, if any.
          fi->get(c));
}

/*!
  Returns next character in current stream. Don't use this method -- SoInput
  is supposed to \e hide whether or not you are reading from file or memory.
  It is only included for compatibility reasons.
*/
SbBool
SoInput::getASCIIBuffer(char & c)
{
  return this->get(c);
}

/*!
  Returns next character in current stream. Don't use this method -- SoInput
  is supposed to \e hide whether or not you are reading from file or memory.
  It is only included for compatibility reasons.
*/
SbBool
SoInput::getASCIIFile(char & c)
{
  return this->get(c);
}

/*!
  Reads an  unsigned integer in hexidecimal format from the current stream.
  Note that no error checking is done to see if it actually is a hex
  format value.

  A number in hexadecimal format must have the "0x" prefix.

  Returns \c FALSE if end of file is encountered.
*/
SbBool
SoInput::readHex(uint32_t & l)
{
  assert(!this->isBinary());

  // FIXME: this is a tremendously stupid function. Should obsolete it.

  // FIXME: no checking for array overwriting. Dangerous. 19990625 mortene.
  char buffer[1024];
  char * bufptr = buffer;

  if (this->readChar(bufptr, '0')) {
    if (this->readChar(bufptr + 1, 'x')) {
      bufptr += 2 + this->readHexDigits(bufptr + 2);
    }
  }

  *bufptr = '\0';
  sscanf(buffer, "%x", &l);
  return TRUE;
}

/*!
  Skips whitespace and reads next character in input stream.
  Returns \c FALSE if encountering end of file.
*/
SbBool
SoInput::read(char & c)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();

  if (!this->checkHeader()) return FALSE;

  return (fi->skipWhiteSpace() && fi->get(c));
}

/*!
  Reads next character in input stream, returns \c FALSE if encountering
  end of file. If \a skip is \c TRUE, skips whitespace before reading a
  character.
*/
SbBool
SoInput::read(char & c, SbBool skip)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();

  if (!this->checkHeader()) return FALSE;

  SbBool ok = TRUE;
  if (skip) ok = fi->skipWhiteSpace();
  return (ok && fi->get(c));
}


/*!
  Skips whitespace and extracts string. A string can be placed
  within quotes, in which case we will return all characters between
  the quotes (including spaces, tabs, newlines, etc). A quote character
  (i.e. ``"'') can also be part of the string, but must then be preceded
  by a ``\'' character.

  A string not contained in quotes is terminated by the first following
  whitespace character.

  Returns \c FALSE upon encountering end of file (EOF) before the
  string is fully parsed, or any other error. Note: This function does
  not return \c FALSE when encountering all EOFs. When multiple files
  are on the stack and a string is being parsed (the parser has found
  one or more valid characters) and EOF is encountered, the parsing
  stops and the read string along with \c TRUE is returned. The next
  time the read method is called, the stack is popped and a read
  string from the next file is returned - not always returning \c
  FALSE between the files (though it might on certain
  circumstances). The solution to this is to test for end of file
  after each successive read operation.
*/
SbBool
SoInput::read(SbString & s)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();

  if (!this->checkHeader()) return FALSE;

  ////////////////////
  // Binary read
  ////////////////////

  if (fi->isBinary()) { // Checkheader has already been called
    // This is just a guess at a sensible limit, to help detect
    // corrupted files and to avoid those leading to attempts at
    // allocating gigabytes of memory.
    const unsigned int MAXSTRLEN = 10 * 1024;

    unsigned int slen;
    if (!this->read(slen)) { return FALSE; }
    if (slen == 0) { s = ""; return TRUE; }

    // Inventor V1.0 binary files seems to have 0xffffffff as some
    // sort of end-of-file tag, so handle that case.
    if (slen == 0xffffffff) {
      char c;
      (void)fi->get(c); // sets the EOF flag as a side-effect
      if (fi->isEndOfFile()) { return FALSE; }
      fi->putBack(c);
    }

    // Sanity check
    if (slen > MAXSTRLEN) {
      SoReadError::post(this, "String too long (%u characters) -- "
                        "file probably corrupt.", slen);
      return FALSE;
    }

    char buffer[MAXSTRLEN+4+1];
    if (!fi->getChunkOfBytes((unsigned char *)buffer, ((slen+3)/4)*4)) { return FALSE; }
    buffer[slen] = '\0';
    s = buffer;
    return TRUE;
  }


  ////////////////////
  // ASCII read
  ////////////////////

  if (!fi->skipWhiteSpace()) return FALSE;

  s.makeEmpty();

  char c;
  if (!fi->get(c)) return FALSE;

  SbBool quoted = (c == '\"');
  if (!quoted) fi->putBack(c);

  // FIXME: the following code could have been much cleaner if we'd
  // used SbString::operator+=(char) for each char instead of going
  // through the tmp buffer. SbString::operator+=(char) uses strlen()
  // for each invocation, though, so that'd give us rather nasty
  // algorithm-time on the SoInput::read(SbString) operations. The
  // correct fix is to first avoid the strlen() invocations in
  // SbString, then simplify this code. 20020506 mortene.

  char bufStore[256];
  int bytesLeft;
  unsigned int totallen = 0;
  do {
    char * buf = bufStore;
    bytesLeft = sizeof(bufStore) - 1;

    while (bytesLeft > 0) {
      if (!fi->get(*buf)) {
        if ((totallen == 0) || quoted) {
          if (quoted) {
            SoReadError::post(this, "Missing terminating quote-character (\")");
          }
          return FALSE;
        }
        // This method does not return FALSE on all EOFs. When having
        // started reading the last String, and encountering EOF at
        // the end of this, it simply stops reading and returns
        // TRUE. The next time, it just pops the stack and starts
        // reading on the next file. Not returning FALSE.
        break;
      }

      if (quoted) {
        if (*buf == '\"') break;

        if (*buf == '\\') {
          if (!fi->get(c)) return FALSE;
          if (c == '\"') {
            // VRML 2.0 allows for strings to contain literal
            // newlines, Inventor/VRML V1.0 doesn't.  This also checks
            // for a special case in Inventor/VRML 1.0 files where the
            // last two characters of a line containing a quoted
            // string is \". In this case, the backslash should be
            // considered literal and the quote should terminate the
            // string.
            if (!this->isFileVRML2() && fi->get(c)) {
              fi->putBack(c);
              if (c == '\n') fi->putBack('\"');
              else *buf = '\"';
            }
            else {
              *buf = c;
            }
          }
          // In VRML V2.0, backslashes must be quoted.
          else if (c != '\\' || !this->isFileVRML2()) {
            fi->putBack(c);
          }
        }
      }
      // Unquoted strings end on first encountered whitespace
      else if (fi->isSpace(*buf)) {
        fi->putBack(*buf);
        break;
      }

      buf++; totallen++;
      bytesLeft--;
    }

    *buf = '\0';
    s += bufStore;

  } while (bytesLeft == 0);

  return TRUE;
}

/*!
  Read a name from the current stream and place it in \a n.

  This method should not be used specifically to read all instances of
  SbName. The semantics of the interface is such that it is designed
  to handle identifier tokens from the Inventor / VRML file
  formats. I.e. cases where node names, node types and field names are
  to be read. If your goal is to read the value of a SbName field that
  is not any of the above, and at least when the string might be
  quoted, then you should most likely use SoInput::read(SbString &)
  instead.

  If \a validIdent is \c TRUE the name needs to be a valid identifier
  (no reserved characters etc), while \a validIdent equal to \c FALSE
  means we'll just read characters for the next word until we hit
  whitespace or one of the "{"/"}" delimiters.

  Returns \c FALSE on encountering end of file before a full name has
  been read -- if \a validIdent is also \c FALSE. If \a validIdent is
  passed as \c TRUE, the return value will be \c FALSE if no valid name
  was found, but \e not necessarily on end of file.
*/
SbBool
SoInput::read(SbName & n, SbBool validIdent)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!this->checkHeader()) return FALSE;

  const enum CodePath { INVENTOR, VRML1, VRML2 } codepath =
    fi->isFileVRML2() ? VRML2 : (fi->isFileVRML1() ? VRML1 : INVENTOR);

  // Binary format.
  if (fi->isBinary()) { // Checkheader has already been called
    SbString s;
    if (!this->read(s)) return FALSE;

    n = s;
    const int strlength = s.getLength();

    switch (codepath) {
    case INVENTOR:
      if (validIdent && strlength > 0) {
        if (!SoInputP::isNameStartChar(s[0], validIdent)) return FALSE;
        for (int i = 1; i < strlength; i++)
          if (!SoInputP::isNameChar(s[i], validIdent)) return FALSE;
      }
      break;
    case VRML1:
      if (validIdent && strlength > 0) {
        if (!SoInputP::isNameStartCharVRML1(s[0], validIdent)) return FALSE;
        for (int i = 1; i < strlength; i++)
          if (!SoInputP::isNameCharVRML1(s[i], validIdent)) return FALSE;
      }
    case VRML2:
      if (validIdent && strlength > 0) {
        if (!SoInputP::isNameStartCharVRML2(s[0], validIdent)) return FALSE;
        for (int i = 1; i < strlength; i++)
          if (!SoInputP::isNameCharVRML2(s[i], validIdent)) return FALSE;
      }
    default:
      assert(!"invalid code path");
      break;
    }

    return TRUE;
  }
  // ASCII format.
  else {
    if (!fi->skipWhiteSpace()) return FALSE;

    SbString s;
    char buf[256];
    char * b = buf;
    char c;
    SbBool gotchar = FALSE;

    switch (codepath) {
    case INVENTOR:
      if ((gotchar = fi->get(c)) && SoInputP::isNameStartChar(c, validIdent)) {
        *b++ = c;
        while ((gotchar = fi->get(c)) && SoInputP::isNameChar(c, validIdent)) {
          *b++ = c;
          if (b - buf == 255) {
            *b = '\0';
            s += buf;
            b = buf;
          }
        }
      }
      break;
    case VRML1:
      if ((gotchar = fi->get(c)) && SoInputP::isNameStartCharVRML1(c, validIdent)) {
        *b++ = c;
        while ((gotchar = fi->get(c)) && SoInputP::isNameCharVRML1(c, validIdent)) {
          *b++ = c;
          if (b - buf == 255) {
            *b = '\0';
            s += buf;
            b = buf;
          }
        }
      }
      break;
    case VRML2:
      if ((gotchar = fi->get(c)) && SoInputP::isNameStartCharVRML2(c, validIdent)) {
        *b++ = c;
        while ((gotchar = fi->get(c)) && SoInputP::isNameCharVRML2(c, validIdent)) {
          *b++ = c;
          if (b - buf == 255) {
            *b = '\0';
            s += buf;
            b = buf;
          }
        }
      }
      break;
    default:
      assert(!"invalid code path");
      break;
    }
    // This behavior is pretty silly, but this is how it is supposed
    // to work, apparently -- _not_ returning FALSE upon end-of-file.
    if (gotchar) fi->putBack(c);

    *b = '\0';
    s += buf;
    n = SbName(s);

#if 0 // debug
    SoDebugError::postInfo("SoInput::read",
                           "string read: ``%s''", s.getString());
#endif // debug

    if (s.getLength() == 0) return FALSE;
  }

  return TRUE;
}

// FIXME: should we maybe do bounds-testing on the read-in data
// to warn if the data doesn't fit in the storage type?
// std::numeric_limits<type>::max() ought to be all the information
// needed.  20070520 larsa
#define READ_NUM(reader, readType, num, type) \
  SoInput_FileInfo * fi = this->getTopOfStack(); \
  assert(fi); \
  if (!fi->skipWhiteSpace()) return FALSE; \
  readType _tmp; \
  if (!fi->reader(_tmp)) return FALSE; \
  num = (type) _tmp;

#define READ_INTEGER(num, type) \
READ_NUM(readInteger, int32_t, num, type)

#define READ_UNSIGNED_INTEGER(num, type) \
READ_NUM(readUnsignedInteger, uint32_t, num, type)

#define READ_REAL(num, type) \
READ_NUM(readReal, double, num, type)

/*!
  Read integer from current file or buffer position and place it in \a i.
  Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(int & i)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    i = tmp;
    return TRUE;
  }
  else {
    READ_INTEGER(i, int);
  }
  return TRUE;
}

/*!
  Read unsigned integer from current file or buffer position and place
  it in \a i. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(unsigned int & i)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    i = tmp;
    return TRUE;
  }
  else {
    READ_UNSIGNED_INTEGER(i, unsigned int);
  }
  return TRUE;
}

/*!
  Read short integer from current file or buffer position and place
  it in \a s. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(short & s)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    s = (short) tmp;
    return TRUE;
  }
  else {
    READ_INTEGER(s, short);
  }
  return TRUE;
}

/*!
  Read unsigned short integer from current file or buffer position and place
  it in \a s. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(unsigned short & s)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    s = (unsigned short) tmp;
    return TRUE;
  }
  else {
    READ_UNSIGNED_INTEGER(s, unsigned short);
  }
  return TRUE;
}

/*!
  Read signed byte integer from current file or buffer position and place
  it in \a b. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::readByte(int8_t & b)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    b = (int8_t) tmp;
    return TRUE;
  }
  else {
    READ_INTEGER(b, int8_t);
  }
  return TRUE;
}

/*!
  Read unsigned byte integer from current file or buffer position and place
  it in \a b. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::readByte(uint8_t & b)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    int32_t tmp;
    if (!this->readBinaryArray(&tmp, 1)) return FALSE;
    b = (uint8_t) tmp;
    return TRUE;
  }
  else {
    READ_UNSIGNED_INTEGER(b, uint8_t);
  }
  return TRUE;
}

/*!
  Read float value from current file or buffer position and place
  it in \a f. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(float & f)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    if (!this->readBinaryArray(&f, 1)) { return FALSE; }
  }
  else {
    READ_REAL(f, float);
  }
  if (!coin_finite((double)f)) {
    SoReadError::post(this,
                      "Detected non-valid floating point number, replacing "
                      "with 0.0f");
    f = 0.0f;
    // We don't return FALSE, thereby allowing the read process to
    // continue, as a convenience for the application programmer.
  }
  return TRUE;
}

/*!
  Read double value from current file or buffer position and place
  it in \a d. Returns \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::read(double & d)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);

  if (fi->isBinary()) { // Assume checkheader has been called
    if (!this->readBinaryArray(&d, 1)) { return FALSE; }
  }
  else {
    READ_REAL(d, double);
  }
  if (!coin_finite(d)) {
    SoReadError::post(this,
                      "Detected non-valid floating point number, replacing "
                      "with 0.0");
    d = 0.0;
    // We don't return FALSE, thereby allowing the read process to
    // continue, as a convenience for the application programmer.
  }
  return TRUE;
}

#ifdef __CYGWIN__
#include <boost/static_assert.hpp>

SbBool
SoInput::read(long int & i)
{
  BOOST_STATIC_ASSERT(sizeof(long int) == sizeof(int));
  return read(reinterpret_cast<int &>(i));
}

SbBool
SoInput::read(unsigned long int & i)
{
  BOOST_STATIC_ASSERT(sizeof(unsigned long int) == sizeof(unsigned int));
  return read(reinterpret_cast<unsigned int &>(i));
}
#endif //__CYGWIN

/*!
  Reads \a length characters from the current stream into \a c. Returns
  \c FALSE if end of file is encountered before the given number of bytes
  could be read.
 */
SbBool
SoInput::readBinaryArray(unsigned char * c, int length)
{
  return (this->checkHeader() &&
          this->getTopOfStack()->getChunkOfBytes(c, length));
}

/*!
  Reads \a length 32-bit integers from the current stream into \a l. Returns
  \c FALSE if end of file is encountered before the given number of integers
  could be read.
 */
SbBool
SoInput::readBinaryArray(int32_t * l, int length)
{
  assert(length > 0);
  if (!this->checkHeader() ||
      !this->getTopOfStack()->getChunkOfBytes((unsigned char *)l,
                                              length * sizeof(int32_t)))
    return FALSE;

  this->convertInt32Array((char *)l, l, length);
  return TRUE;
}

/*!
  Reads \a length floats from the current stream into \a f. Returns
  \c FALSE if end of file is encountered before the given number of
  binary float values could be read.
 */
SbBool
SoInput::readBinaryArray(float * f, int length)
{
  assert(length > 0);
  if (!this->checkHeader() ||
      !this->getTopOfStack()->getChunkOfBytes((unsigned char *)f,
                                              length * sizeof(float)))
    return FALSE;

  this->convertFloatArray((char *)f, f, length);

  return TRUE;
}

/*!
  Reads \a length double floats from the current stream into \a d.
  Returns \c FALSE if end of file is encountered before the given number of
  binary double float values could be read.
 */
SbBool
SoInput::readBinaryArray(double * d, int length)
{
  assert(length > 0);
  if (!this->checkHeader() ||
      !this->getTopOfStack()->getChunkOfBytes((unsigned char *)d,
                                              length * sizeof(double)))
    return FALSE;

  this->convertDoubleArray((char *)d, d, length);
  return TRUE;
}

/*!
  Returns \c TRUE if we are at the end of the current stream, otherwise
  \c FALSE.
 */
SbBool
SoInput::eof(void) const
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  if (!fi) return TRUE;
  return fi->isEndOfFile();
}

/*!
  Places the current line number location and file name in a string
  which is to be used in the output upon read errors.
 */
void
SoInput::getLocationString(SbString & str) const
{
  if (this->filestack.getLength() == 0) {
    str = "";
    return;
  }

  const char * filename = this->getCurFileName();

  // FIXME: hack to cast away constness. Ugly. 19990713 mortene.
  if (((SoInput *)this)->isBinary()) {
    str.sprintf("\tOccurred at position %lu in binary file %s",
                (unsigned long int) this->getTopOfStack()->getNumBytesParsedSoFar(),
                filename ? filename : "<memory>");
  }
  else {
    str.sprintf("\tOccurred at line %3d in %s",
                this->getTopOfStack()->lineNr(),
                filename ? filename : "<memory>");
  }
}

/*!
  Insert character \a c in stream at the current position.
 */
void
SoInput::putBack(const char c)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  fi->putBack(c);
}

/*!
  Insert string \a str in stream at the current position.
 */
void
SoInput::putBack(const char * str)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  fi->putBack(str);
}

/*!
  Adds a name<->SoBase mapping to our dictionary.

  \sa findReference(), removeReference()
 */
void
SoInput::addReference(const SbName & name, SoBase * base,
                      SbBool addToGlobalDict)
{
  SoProto * proto = this->getCurrentProto();
  if (proto) {
    proto->addReference(name, base);
  }
  else {
    this->getTopOfStack()->addReference(name, base, addToGlobalDict);
  }
}

/*!
  Removes a name<->SoBase mapping from our dictionary.

  \sa findReference(), addReference()
 */
void
SoInput::removeReference(const SbName & name)
{
  SoProto * proto = this->getCurrentProto();
  if (proto) {
    proto->removeReference(name);
  }
  else {
    this->getTopOfStack()->removeReference(name);
  }
}

/*!
  Finds an SoBase derived object which has been mapped to \a name earlier
  during the import process.

  The Coin library will by default only search through the previously
  loaded nodes from the \e same file. By setting the environment
  variable \c COIN_SOINPUT_SEARCH_GLOBAL_DICT to "1", you can force
  the import process to search for USE-references through \e all nodes
  that has been loaded or otherwise instantiated.

  \sa addReference(), removeReference()
 */
SoBase *
SoInput::findReference(const SbName & name) const
{
  SoProto * proto = this->getCurrentProto();
  if (proto) {
    return proto->findReference(name);
  }
  else {
    SoBase * base = this->getTopOfStack()->findReference(name);
    if (base) return base;

    static int COIN_SOINPUT_SEARCH_GLOBAL_DICT = -1;
    if (COIN_SOINPUT_SEARCH_GLOBAL_DICT < 0) {
      const char * env = coin_getenv("COIN_SOINPUT_SEARCH_GLOBAL_DICT");
      if (env) COIN_SOINPUT_SEARCH_GLOBAL_DICT = atoi(env);
      else COIN_SOINPUT_SEARCH_GLOBAL_DICT = 0;
    }

    if (COIN_SOINPUT_SEARCH_GLOBAL_DICT) {
      return SoBase::getNamedBase(name, SoNode::getClassTypeId());
    }
  }
  return NULL;
}

/*!
  Add a directory to the search list. The added directory will be searched
  before any of the other directories in the list.

  \sa addDirectoryLast(), addEnvDirectoriesFirst(), addEnvDirectoriesLast()
  \sa removeDirectory(), clearDirectories()
 */
void
SoInput::addDirectoryFirst(const char * dirName)
{
  SoInput::addDirectoryIdx(0, dirName);
}

/*!
  Add a directory to the search list. The added directory will be searched
  after any of the other directories in the list.

  \sa addDirectoryFirst(), addEnvDirectoriesFirst(), addEnvDirectoriesLast()
  \sa removeDirectory(), clearDirectories()
 */
void
SoInput::addDirectoryLast(const char * dirName)
{
  SoInput::addDirectoryIdx(-1, dirName);
}

/*!
  \COININTERNAL

  Add a directory to the search list at the specified index value. An index
  of -1 means append.
 */
void
SoInput::addDirectoryIdx(const int idx, const char * dirName)
{
  assert(idx > -2);
  if (strlen(dirName) == 0) return; // Don't add empty dirs
  SbStringList * dirs = SoInput::dirsearchlist;

  if (soinput_tls) {
    soinput_tls_data * data = (soinput_tls_data *)soinput_tls->get();
    if (data->instancecount) { dirs = data->searchlist; }
  }

  assert(idx <= dirs->getLength());
  // NB: note that it _should_ be possible to append/insert the same
  // directory name multiple times, as this is an easy way of
  // "stacking" names when doing recursive SoDB::readAll() calls or
  // using SoInput::pushFile(). So don't try to "fix" or change this
  // aspect of adding entries to the directory search list. --mortene

  SbString * ns = new SbString(dirName);
  if (idx == -1) dirs->append(ns);
  else if (idx != -1) dirs->insert(ns, idx);
}

/*!
  Add in front of the list all directories in the environment
  variable \a envVarName. The \a separator string should contain all
  characters to be interpreted as separators in the environment variable
  string list. The default separators are ':', tab and space.

  \sa addDirectoryFirst(), addDirectoryLast()
  \sa addEnvDirectoriesLast()
  \sa removeDirectory(), clearDirectories()
 */
void
SoInput::addEnvDirectoriesFirst(const char * envVarName,
                                const char * separator)
{
  SoInput::addEnvDirectoriesIdx(0, envVarName, separator);
}

/*!
  Add at the end of the list all directories in the environment
  variable \a envVarName. The \a separator string should contain all
  characters to be interpreted as separators in the environment variable
  string list. The default separators are ':', tab and space.

  \sa addDirectoryFirst(), addDirectoryLast()
  \sa addEnvDirectoriesFirst()
  \sa removeDirectory(), clearDirectories()
 */
void
SoInput::addEnvDirectoriesLast(const char * envVarName,
                               const char * separator)
{
  SoInput::addEnvDirectoriesIdx(SoInput::dirsearchlist->getLength(),
                                envVarName,
                                separator);
}

/*!
  \COININTERNAL

  Add environment variable directory list, starting at index \a startidx.
 */
void
SoInput::addEnvDirectoriesIdx(int startidx,
                              const char * envVarName,
                              const char * separator)
{
  const char * p = coin_getenv(envVarName);
  if (!p) {
#if COIN_DEBUG
    SoDebugError::postWarning("SoInput::addEnvDirectoriesFirst",
                              "Tried to add directories from nonexistent "
                              "environment variable '%s'.",
                              envVarName);
#endif // COIN_DEBUG
    return;
  }

  // FIXME: the following "tokenizer" code could perhaps be factored
  // out and moved to e.g. SbStringList? 20030820 mortene.

  if (separator == NULL) {
    // use default separators if NULL
    separator = ":\t ";
  }
  const char * end = p + strlen(p);

  while (p < end) {
    const char * hit = strpbrk(p, separator);

    if (hit && hit != p) {
      const ptrdiff_t offset = hit - p;
      SbString add = SbString(p).getSubString(0, (int)(offset - 1));
      SoInput::addDirectoryIdx(startidx++, add.getString());
      p = hit+1;
    }
    else if (hit) { // more than one separator in a row
      p++;
    }
    else { // last entry
      SoInput::addDirectoryIdx(startidx, p);
      p = end;
    }
  }
}

/*!
  Remove the given directory from the directory search list.

  The search list is scanned from last to first for the directory name,
  so directories can easily be "stacked" by pushing with addDirectoryLast()
  and then removed with this method.

  \sa addDirectoryFirst(), addDirectoryLast()
  \sa addEnvDirectoriesFirst(), addEnvDirectoriesLast()
  \sa clearDirectories()
 */
void
SoInput::removeDirectory(const char * dirName)
{
  SbStringList * dirs = SoInput::dirsearchlist;

  if (soinput_tls) {
    soinput_tls_data * data = (soinput_tls_data *)soinput_tls->get();
    if (data->instancecount) { dirs = data->searchlist; }
  }

  // dirsearchlist might be null if user called SoDB::cleanup()
  if (dirs) {
    int idx = dirs->getLength() - 1;
    for (; idx >= 0; idx--) {
      if (*((*dirs)[idx]) == dirName) break;
    }

    if (idx >=0) {
      delete (*dirs)[idx]; // Dealloc SbString object
      dirs->remove(idx);
    }
#if COIN_DEBUG
    else {
      SoDebugError::postWarning("SoInput::removeDirectory",
                                "Tried to remove nonexistent directory '%s'"
                                " in directory search list.", dirName);
    }
#endif // COIN_DEBUG
  }
}

/*!
  Remove all entries from the directory search list.

  \sa addDirectoryFirst(), addDirectoryLast()
  \sa addEnvDirectoriesFirst(), addEnvDirectoriesLast()
  \sa removeDirectory()
 */
void
SoInput::clearDirectories(void)
{
  while (SoInput::dirsearchlist->getLength() > 0) {
    delete (*SoInput::dirsearchlist)[0];
    SoInput::dirsearchlist->remove(0);
  }
}

/*!
  Returns the list of directories which'll be searched upon loading
  Coin and VRML format files. Directory searches will be done whenever
  any external references appears in a file, for instance to texture images.
 */
const SbStringList &
SoInput::getDirectories(void)
{
  if (soinput_tls) {
    soinput_tls_data * data = (soinput_tls_data *)soinput_tls->get();
    if (data->instancecount) { return *data->searchlist; }
  }

  return *SoInput::dirsearchlist;
}

/*!
  Initialize static variables in class. Called from SoDB::init().
*/
void
SoInput::init(void)
{
  coin_atexit((coin_atexit_f *)SoInput::clean, CC_ATEXIT_NORMAL);

  // This will catch multiple initClass() calls (unless there's a
  // removeDirectories() in between them, which is unlikely to happen
  // inadvertently).
  assert(SoInput::dirsearchlist == NULL);

  SoInput::dirsearchlist = new SbStringList;
  SoInput::addDirectoryFirst(".");

  soinput_tls = new SbStorage(sizeof(soinput_tls_data),
                              soinput_construct_tls_data,
                              soinput_destruct_tls_data);
}

// Clean out static variables in class (to aid in searching for memory
// leaks).
void
SoInput::clean(void)
{
  SoInput::clearDirectories();
  delete SoInput::dirsearchlist;
  SoInput::dirsearchlist = NULL;

  delete soinput_tls; soinput_tls = NULL;
}

/*!
  Finds and returns the part of the given filename which is the
  directory path name.
 */
SbString
SoInput::getPathname(const char * const filename)
{
  // FIXME: this method would be a prime candidate for the planned
  // SbFile class of filesystem abstractions to hide system
  // differences. 20011021 mortene.

#ifdef HAVE__SPLITPATH

  char drive[_MAX_DRIVE];
  char dir[_MAX_DIR];

  _splitpath(filename, drive, dir, NULL, NULL);

  SbString s(drive);
  s += dir;
  return s;

#else // HAVE__SPLITPATH

  const char * ptr = strrchr(filename, '/');
  if (ptr == NULL) return SbString("");

  SbString s = filename;
  return s.getSubString(0, ptr-filename);

#endif // !HAVE__SPLITPATH
}

/*!
  Finds and returns the part of the given filename which is the
  directory path name.
 */
SbString
SoInput::getPathname(const SbString & s)
{
  return SoInput::getPathname(s.getString());
}

/*!
  Finds and returns the part of the given filename which is the base name
  (i.e. the filename without the leading directory path).
 */
SbString
SoInput::getBasename(const char * const filename)
{
  // FIXME: this method would be a prime candidate for the planned
  // SbFile class of filesystem abstractions to hide system
  // differences. 20011021 mortene.

#ifdef HAVE__SPLITPATH

  char fname[_MAX_FNAME];
  char ext[_MAX_EXT];

  _splitpath(filename, NULL, NULL, fname, ext);

  SbString s(fname);
  s += ext;
  return s;

#else // UNIX systems

  const char * ptr = strrchr(filename, '/');
  if (ptr == NULL) return SbString(filename);

  SbString s = filename;
  return s.getSubString(ptr - filename + 1, -1);

#endif // UNIX
}

/*!
  Finds and returns the part of the given filename which is the base name
  (i.e. the filename without the leading directory path).
 */
SbString
SoInput::getBasename(const SbString & s)
{
  return SoInput::getBasename(s.getString());
}

// internal method used for testing if a file exists
static SbBool
test_filename(const SbString & filename)
{
  FILE * fp = fopen(filename.getString(), "rb");
#if COIN_DEBUG && 0 // flip 1<->0 to turn texture search trace on or off
  SoDebugError::postInfo("test_filename", "file search: %s (%s)\n",
                         filename.getString(), fp ? "hit" : "miss");
#endif // !COIN_DEBUG

  if (fp != NULL) {
    fclose(fp);
    return TRUE;
  }
  return FALSE;
}

/*!
  Given a \a basename for a file and an array of \a directories to
  search, returns the full name of the file found.

  In addition to looking at the root of each directory in \a
  directories, all \a subdirectories is also searched for each item in
  \a directories.

  If no file matching \a basename could be found in any of the
  directories, returns an empty string.

  This method is a Coin extension, not part of the original Inventor
  API.
*/
SbString
SoInput::searchForFile(const SbString & basename,
                       const SbStringList & directories,
                       const SbStringList & subdirectories)
{
  int i;

  if (test_filename(basename)) return basename;

  SbString fullname = basename;

  SbBool trypath = TRUE;
  const char * strptr = basename.getString();
  const char * lastunixdelim = strrchr(strptr, '/');
  const char * lastdosdelim = strrchr(strptr, '\\');
  if (!lastdosdelim) {
    lastdosdelim = strrchr(strptr, ':');
    if (lastdosdelim) trypath = FALSE;
  }
  const char * lastdelim = SbMax(lastunixdelim, lastdosdelim);

  if (lastdelim && trypath) {
    SbString tmpstring;
    for (i = 0; i < directories.getLength(); i++) {
      SbString dirname(directories[i]->getString());
      int dirlen = dirname.getLength();

      if (dirlen > 0 &&
          dirname[dirlen-1] != '/' &&
          dirname[dirlen-1] != '\\' &&
          dirname[dirlen-1] != ':') {
        dirname += "/";
      }

      tmpstring.sprintf("%s%s", dirname.getString(),
                        fullname.getString());
      if (test_filename(tmpstring)) return tmpstring;
    }
  }

  const ptrdiff_t offset = lastdelim - strptr;
  SbString base = lastdelim ?
    basename.getSubString((int)(offset + 1), -1) :
    basename;

  for (i = 0; i < directories.getLength(); i++) {
    SbString dirname(directories[i]->getString());
    int dirlen = dirname.getLength();

    if (dirlen > 0 &&
        dirname[dirlen-1] != '/' &&
        dirname[dirlen-1] != '\\' &&
        dirname[dirlen-1] != ':') {
      dirname += "/";
    }
    fullname.sprintf("%s%s", dirname.getString(),
                     base.getString());
    if (test_filename(fullname)) return fullname;
    for (int j = 0; j < subdirectories.getLength(); j++) {
      fullname.sprintf("%s%s/%s", dirname.getString(),
                       subdirectories[j]->getString(),
                       base.getString());
      if (test_filename(fullname)) return fullname;
    }
  }
  // none found
  return SbString("");
}


/*!
  Changes the file format version number for the stream at the top of the
  stack.
 */
void
SoInput::setIVVersion(float version)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  fi->setIvVersion(version);
}

/*!
  This function has been obsoleted in Coin.
*/
void
SoInput::initFile(FILE * /* newFP */, const char * /* fileName */,
                  SbString * /* fullName */,
                  SbBool /* openedHere */, SbDict * /* refDict */)
{
  COIN_OBSOLETED();
}

/*!
  Returns \c TRUE if the current stream has had it's header parsed.
  If it hasn't, this method will attempt to read the header and returns
  \c TRUE if it could be done.

  If \a bValidateBufferHeader is \c TRUE, the returned flag will also
  be \c FALSE if the file stream header was not of a supported file
  format type.
*/
SbBool
SoInput::checkHeader(SbBool bValidateBufferHeader)
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  if (!fi) {
    SoDebugError::post("SoInput::checkHeader", "no files on the stack");
    return FALSE;
  }

  // Make a note if reading is attempted on <stdin>. By marking if
  // <stdin> is being read from or not, we have a pretty good way of
  // telling if the user want to use <stdin> to read from or not when
  // a new file is pushed on the stack.
  if (this->filestack.getLength() == 1 &&
      fi->ivFilePointer() == coin_get_stdin() &&
      !PRIVATE(this)->usingstdin) {

    PRIVATE(this)->usingstdin = TRUE;
  }

  return fi->readHeader(this) && (!bValidateBufferHeader || fi->ivVersion() != 0.0f);
}

/*!
  Returns \c TRUE if the current input stream is fetching data from a
  memory buffer, or \c FALSE if the input is from a file.
*/
SbBool
SoInput::fromBuffer(void) const
{
  SoInput_FileInfo * fi = this->getTopOfStack();
  assert(fi);
  return fi->isMemBuffer() ? TRUE : FALSE;
}

/*!
  Move file pointer past whitespace in the current file or buffer.
  Returns \c FALSE if end of file is encountered.
 */
SbBool
SoInput::skipWhiteSpace(void)
{
  // FIXME: pop file on EOF? don't think so, but please let me
  // know if I'm wrong. jornskaa 20040702
  return (this->checkHeader() && this->getTopOfStack()->skipWhiteSpace());
}

/*!
  Pop the topmost file off the stack. Returns \c FALSE if there was no
  files on the stack to pop. A file is only popped when there is more
  than one file on the stack.

  \sa pushFile(), openFile(), closeFile()
 */
SbBool
SoInput::popFile(void)
{
  if (this->filestack.getLength() == 0) return FALSE;

  SoInput_FileInfo * topofstack = this->getTopOfStack();

  // connect routes before applying post callbacks
  topofstack->connectRoutes(this);

  // unreference Proto definitions
  topofstack->unrefProtos();

  // apply post callback, even if we're not going to pop
  topofstack->applyPostCallback(this);
  // If only one file is on the stack, don't pop it
  if (this->filestack.getLength() == 1) return FALSE;

  if (topofstack->ivFilePointer()) {
    const char * filename = topofstack->ivFilename().getString();
    SbString path = SoInput::getPathname(filename);
    if (path.getLength()) SoInput::removeDirectory(path.getString());
  }
  delete topofstack;
  this->filestack.remove(0);
  return TRUE;
}

/*!
  This function has been obsoleted in Coin.
 */
size_t
SoInput::freeBytesInBuf(void) const
{
  COIN_OBSOLETED();
  return 0;
}

/*!
  Reads 32-bit signed integer value from the current stream. Returns
  \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::readInteger(int32_t & l)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readInteger(l);
}

/*!
  Reads 32-bit unsigned integer value from the current stream. Returns
  \c FALSE if we hit end of file prematurely.
 */
SbBool
SoInput::readUnsignedInteger(uint32_t & l)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readUnsignedInteger(l);
}

/*!
  Reads a double-precision floating point value from the current stream.
  Returns \c FALSE if we hit end of file prematurely or if no valid string
  representing a value could be read.
 */
SbBool
SoInput::readReal(double & d)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readReal(d);
}

/*!
  Reads a set of bytes from the stream making up an unsigned integer and
  puts them at \a str.

  Returns \c FALSE if no string representing an unsigned integer could be
  read.
 */
SbBool
SoInput::readUnsignedIntegerString(char * str)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readUnsignedIntegerString(str);
}

/*!
  Read decimal base digits from the current input stream into \a str and
  returns the number of characters read.
 */
int
SoInput::readDigits(char * str)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readDigits(str);
}

/*!
  Read hexadecimal base digits from the current input stream into \a str and
  returns the number of characters read.
 */
int
SoInput::readHexDigits(char * str)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readHexDigits(str);
}

/*!
  Reads the next character in stream and compares it to \a charToRead.
  Returns \c 1 on success, \c 0 on failure. Failure may come from either
  end of file, or from the next character in the stream being different
  than \a charToRead.
 */
int
SoInput::readChar(char * s, char charToRead)
{
  SoInput_FileInfo * fi = PRIVATE(this)->getTopOfStackPopOnEOF();
  if (!fi) return FALSE;
  return fi->readChar(s, charToRead);
}

/*!
  This function has been obsoleted in Coin.
 */
SbBool
SoInput::makeRoomInBuf(size_t /* nBytes */)
{
  COIN_OBSOLETED();
  return FALSE;
}

/*!
  Convert the bytes at \a from (which must be a short integer in network
  format (i.e. most significant byte first)) to a short integer in native
  format which is put at the \a s pointer.
 */
void
SoInput::convertShort(char * from, short * s)
{
  *s = (short) (coin_ntoh_uint16(*((uint16_t*)from)));
}

/*!
  Convert the bytes at \a from (which must be a 32-bit integer in network
  format (i.e. most significant byte first)) to a 32-bit integer in native
  format which is put at the \a l pointer.
 */
void
SoInput::convertInt32(char * from, int32_t * l)
{
  *l = (int32_t) (coin_ntoh_uint32(*((uint32_t*)from)));
}

/*!
  Convert the bytes at \a from (which must be a single-precision floating
  point number in network format) to a single-precision floating point
  number in native format which is put at the \a f pointer.
 */
void
SoInput::convertFloat(char * from, float * f)
{
  *f = coin_ntoh_float_bytes(from);
}

/*!
  Convert the bytes at \a from (which must be a double-precision floating
  point number in network format) to a double-precision floating point
  number in native format which is put at the \a d pointer.
 */
void
SoInput::convertDouble(char * from, double * d)
{
  *d = coin_ntoh_double_bytes(from);
}

/*!
  Convert a block of short numbers in network format to native format.

  \sa convertShort()
 */
void
SoInput::convertShortArray(char * from, short * to, int len)
{
  for (int i=0; i < len; i++) {
    this->convertShort(from, to);
    from += sizeof(short);
    to++;
  }
}

/*!
  Convert a block of 32-bit integer numbers in network format to native format.

  \sa convertInt32()
 */
void
SoInput::convertInt32Array(char * from, int32_t * to, int len)
{
  for (int i=0; i < len; i++) {
    this->convertInt32(from, to);
    from += sizeof(int32_t);
    to++;
  }
}

/*!
  Convert a block of single-precision floating point numbers in
  network format to native format.

  \sa convertFloat()
 */
void
SoInput::convertFloatArray(char * from, float * to, int len)
{
  for (int i=0; i < len; i++) {
    this->convertFloat(from, to);
    from += sizeof(float);
    to++;
  }
}

/*!
  Convert a block of double-precision floating point numbers in
  network format to native format.

  \sa convertDouble()
 */
void
SoInput::convertDoubleArray(char * from, double * to, int len)
{
  for (int i=0; i < len; i++) {
    this->convertDouble(from, to);
    from += sizeof(double);
    to++;
  }
}

/*!
  Returns \c TRUE if current file is a VRML V1.0 file.

  \COIN_FUNCTION_EXTENSION
*/
SbBool
SoInput::isFileVRML1(void)
{
  (void) this->checkHeader();
  SoInput_FileInfo * fi = this->getTopOfStack();
  if (fi) return fi->isFileVRML1();
  return FALSE;
}

/*!
  Returns \c TRUE if current file is a VRML 2 / VRML97 file.

  \COIN_FUNCTION_EXTENSION
*/
SbBool
SoInput::isFileVRML2(void)
{
  (void) this->checkHeader();
  SoInput_FileInfo * fi = this->getTopOfStack();
  if (fi) return fi->isFileVRML2();
  return FALSE;
}

/*!
  This function has been obsoleted in Coin.
*/
void
SoInput::resetFilePointer(FILE * /* fptr */)
{
  COIN_OBSOLETED();
}

/*!
  This function is part of the TGS Inventor API, but is not
  implemented in Coin.
*/
SbBool
SoInput::isFileURL(const char * /* url */)
{
  COIN_STUB();
  return FALSE;
}

/*!
  This function is part of the TGS Inventor API, but is not
  implemented in Coin.
*/
char *
SoInput::URLToFile(char * /* out_buf */, const char * /* in_buf */)
{
  COIN_STUB();
  return NULL;
}

/*!
  This function is part of the TGS Inventor API, but is not
  implemented in Coin.
*/
SbBool
SoInput::IsURL(const char * /* c_strng */)
{
  COIN_STUB();
  return FALSE;
}

/*!
  Set up the directory search path directly with the list of directories
  in \a dirs. Note that "." should be part of the directory list if you
  want to handle files specified by a relative path.
 */
void
SoInput::setDirectories(SbStringList * dirs)
{
  // Dealloc SbString objects
  for (int i=0; i < SoInput::dirsearchlist->getLength(); i++)
    delete (*SoInput::dirsearchlist)[i];

  (*SoInput::dirsearchlist) = *dirs;
}

/*!
  \COININTERNAL

  Return the currently active stream.
*/
#if 0
SoInput_FileInfo *
SoInput::getTopOfStack(void) const
{
  if (this->filestack.getLength() == 0) {
    SoDebugError::post("SoInput::getTopOfStack", "no files in stack");
    return NULL;
  }
  return this->filestack[0];
}
#endif

/*!
  Scan through the include directories in order and try to find a file
  with the given name in any one of them. If file is found, put the
  full name with complete path from current directory of process into
  \a fullname, open the file and return the file pointer.

  If the file could either not be found or not opened for reading,
  return \c NULL.

  Important note: do \e not use this method when the Coin library has
  been compiled as an MSWindows DLL, as passing FILE* instances back
  or forth to DLLs is dangerous and will most likely cause a
  crash. This is an intrinsic limitation for MSWindows DLLs.
 */
FILE *
SoInput::findFile(const char * basename, SbString & fullname)
{
  // This function has an undocumented feature in Coin: upon error, an
  // error message with the reason why it could not be opened will be
  // placed in the \a fullname argument. Keep this undocumented, to
  // avoid incompatibility problems with SGI/TGS Inventor for app
  // programmers.  -mortene.

  fullname = "";

  if (strlen(basename) < 1) {
    SoDebugError::post("SoInput::findFile", "Was asked to find a file with no name!");
    return NULL;
  }

  const char * env = coin_getenv("COIN_DEBUG_SOINPUT_FINDFILE");
  const SbBool DEBUG_FILE_SEARCHING = env && (atoi(env) > 0);
  if (DEBUG_FILE_SEARCHING) {
    cc_string str;
    cc_string_construct(&str);
    SbBool ok = coin_getcwd(&str);
    if (!ok) {
      SoDebugError::post("SoInput::findFile",
                         "Couldn't get current working directory: %s",
                         cc_string_get_text(&str));
    }
    else {
      SoDebugError::postInfo("SoInput::findFile",
                             "Current working directory: '%s'",
                             cc_string_get_text(&str));
    }
    cc_string_clean(&str);
  }

  SbStringList sl = SoInput::getDirectories();

  // Make sure we try from cwd first.
  SbString relativepath("");
  sl.insert(&relativepath, 0);

  FILE * fp = NULL;
  for (int diridx = 0; diridx < sl.getLength(); diridx++) {
    SbString n = * sl[diridx];
    const int namelen = n.getLength();
    if ((namelen && n[namelen - 1] != '/' && n[namelen - 1] != '\\') &&
        (basename[0] != '/' && basename[0] != '\\')) {
      n += "/";
    }
    n += basename;

    struct stat buf;
    if ((stat(n.getString(), &buf) == 0) && !S_ISDIR(buf.st_mode)) {
      fp = fopen(n.getString(), "rb");
      if (fp != NULL) {
        if (DEBUG_FILE_SEARCHING) {
          SoDebugError::postInfo("SoInput::findFile", "successfully fopened '%s'", n.getString());
        }
        fullname = n;
        return fp;
      }
      else {
        const SbBool same = strcmp(basename, n.getString()) == 0;
        SbString s;
        if (!same) { s.sprintf(" as '%s'", n.getString()); }

        fullname.sprintf("Found '%s'%s, but was unable to open it: '%s'",
                         basename, s.getString(), strerror(errno));
      }
    }
  }

  // If file was not found, list all directories where we looked for
  // it.
  SbBool foundbutcouldntopen = fullname.getLength() > 0;
  if (!foundbutcouldntopen) {
    cc_string str;
    cc_string_construct(&str);
    SbBool ok = coin_getcwd(&str);
    fullname.sprintf("Could not find '%s' in any of the "
                     "following directories (from cwd '%s'):",
                     basename, ok ? cc_string_get_text(&str) : "<unknown>");
    cc_string_clean(&str);

    for (int diridx = 0; diridx < sl.getLength(); diridx++) {
      fullname += "\n\t'";
      fullname += * sl[diridx];
      fullname += "'";
    }
  }

  return NULL;
}

#undef READ_NUM
#undef READ_INTEGER
#undef READ_UNSIGNED_INTEGER
#undef READ_REAL
#undef PRIVATE
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.