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

/***********************************************************
Copyright 1987, 1988, 1990 by Digital Equipment Corporation, Maynard

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

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

Copyright 1987, 1988, 1990, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from The Open Group.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include	<stdio.h>
#include	<ctype.h>
#include	"Xlibint.h"
#include	<X11/Xresource.h>
#include	"Xlcint.h"
#ifdef XTHREADS
#include	"locking.h"
#endif
#include	<X11/Xos.h>
#include	<sys/stat.h>
#include "Xresinternal.h"
#include "Xresource.h"

/*

These Xrm routines allow very fast lookup of resources in the resource
database.  Several usage patterns are exploited:

(1) Widgets get a lot of resources at one time.  Rather than look up each from
scratch, we can precompute the prioritized list of database levels once, then
search for each resource starting at the beginning of the list.

(2) Many database levels don't contain any leaf resource nodes.  There is no
point in looking for resources on a level that doesn't contain any.  This
information is kept on a per-level basis.

(3) Sometimes the widget instance tree is structured such that you get the same
class name repeated on the fully qualified widget name.  This can result in the
same database level occuring multiple times on the search list.  The code below
only checks to see if you get two identical search lists in a row, rather than
look back through all database levels, but in practice this removes all
duplicates I've ever observed.

Joel McCormack

*/

/*

The Xrm representation has been completely redesigned to substantially reduce
memory and hopefully improve performance.

The database is structured into two kinds of tables: LTables that contain
only values, and NTables that contain only other tables.

Some invariants:

The next pointer of the top-level node table points to the top-level leaf
table, if any.

Within an LTable, for a given name, the tight value always precedes the
loose value, and if both are present the loose value is always right after
the tight value.

Within an NTable, all of the entries for a given name are contiguous,
in the order tight NTable, loose NTable, tight LTable, loose LTable.

Bob Scheifler

*/

static XrmQuark XrmQString, XrmQANY;

typedef	Bool (*DBEnumProc)(
    XrmDatabase*	/* db */,
    XrmBindingList	/* bindings */,
    XrmQuarkList	/* quarks */,
    XrmRepresentation*	/* type */,
    XrmValue*		/* value */,
    XPointer		/* closure */
);

typedef struct _VEntry {
    struct _VEntry	*next;		/* next in chain */
    XrmQuark		name;		/* name of this entry */
    unsigned int	tight:1;	/* 1 if it is a tight binding */
    unsigned int	string:1;	/* 1 if type is String */
    unsigned int	size:30;	/* size of value */
} VEntryRec, *VEntry;


typedef struct _DEntry {
    VEntryRec		entry;		/* entry */
    XrmRepresentation	type;		/* representation type */
} DEntryRec, *DEntry;

/* the value is right after the structure */
#define StringValue(ve) (XPointer)((ve) + 1)
#define RepType(ve) ((DEntry)(ve))->type
/* the value is right after the structure */
#define DataValue(ve) (XPointer)(((DEntry)(ve)) + 1)
#define RawValue(ve) (char *)((ve)->string ? StringValue(ve) : DataValue(ve))

typedef struct _NTable {
    struct _NTable	*next;		/* next in chain */
    XrmQuark		name;		/* name of this entry */
    unsigned int	tight:1;	/* 1 if it is a tight binding */
    unsigned int	leaf:1;		/* 1 if children are values */
    unsigned int	hasloose:1;	/* 1 if has loose children */
    unsigned int	hasany:1;	/* 1 if has ANY entry */
    unsigned int	pad:4;		/* unused */
    unsigned int	mask:8;		/* hash size - 1 */
    unsigned int	entries:16;	/* number of children */
} NTableRec, *NTable;

/* the buckets are right after the structure */
#define NodeBuckets(ne) ((NTable *)((ne) + 1))
#define NodeHash(ne,q) NodeBuckets(ne)[(q) & (ne)->mask]

/* leaf tables have an extra level of indirection for the buckets,
 * so that resizing can be done without invalidating a search list.
 * This is completely ugly, and wastes some memory, but the Xlib
 * spec doesn't really specify whether invalidation is OK, and the
 * old implementation did not invalidate.
 */
typedef struct _LTable {
    NTableRec		table;
    VEntry		*buckets;
} LTableRec, *LTable;

#define LeafHash(le,q) (le)->buckets[(q) & (le)->table.mask]

/* An XrmDatabase just holds a pointer to the first top-level table.
 * The type name is no longer descriptive, but better to not change
 * the Xresource.h header file.  This type also gets used to define
 * XrmSearchList, which is a complete crock, but we'll just leave it
 * and caste types as required.
 */
typedef struct _XrmHashBucketRec {
    NTable table;
    XPointer mbstate;
    XrmMethods methods;
#ifdef XTHREADS
    LockInfoRec linfo;
#endif
} XrmHashBucketRec;

/* closure used in get/put resource */
typedef struct _VClosure {
    XrmRepresentation	*type;		/* type of value */
    XrmValuePtr		value;		/* value itself */
} VClosureRec, *VClosure;

/* closure used in get search list */
typedef struct _SClosure {
    LTable		*list;		/* search list */
    int			idx;		/* index of last filled element */
    int			limit;		/* maximum index */
} SClosureRec, *SClosure;

/* placed in XrmSearchList to indicate next table is loose only */
#define LOOSESEARCH ((LTable)1)

/* closure used in enumerate database */
typedef struct _EClosure {
    XrmDatabase db;			/* the database */
    DBEnumProc proc;			/* the user proc */
    XPointer closure;			/* the user closure */
    XrmBindingList bindings;		/* binding list */
    XrmQuarkList quarks;		/* quark list */
    int mode;				/* XrmEnum<kind> */
} EClosureRec, *EClosure;

/* types for typecasting ETable based functions to NTable based functions */
typedef Bool (*getNTableSProcp)(
    NTable              table,
    XrmNameList         names,
    XrmClassList        classes,
    SClosure            closure);
typedef Bool (*getNTableVProcp)(
    NTable              table,
    XrmNameList         names,
    XrmClassList        classes,
    VClosure            closure);
typedef Bool (*getNTableEProcp)(
    NTable              table,
    XrmNameList         names,
    XrmClassList        classes,
    register int        level,
    EClosure            closure);

/* predicate to determine when to resize a hash table */
#define GrowthPred(n,m) ((unsigned)(n) > (((m) + 1) << 2))

#define GROW(prev) \
    if (GrowthPred((*prev)->entries, (*prev)->mask)) \
	GrowTable(prev)

/* pick a reasonable value for maximum depth of resource database */
#define MAXDBDEPTH 100

/* macro used in get/search functions */

/* find an entry named ename, with leafness given by leaf */
#define NFIND(ename) \
    q = ename; \
    entry = NodeHash(table, q); \
    while (entry && entry->name != q) \
	entry = entry->next; \
    if (leaf && entry && !entry->leaf) { \
	entry = entry->next; \
	if (entry && !entry->leaf) \
	    entry = entry->next; \
	if (entry && entry->name != q) \
	    entry = (NTable)NULL; \
    }

/* resourceQuarks keeps track of what quarks have been associated with values
 * in all LTables.  If a quark has never been used in an LTable, we don't need
 * to bother looking for it.
 */

static unsigned char *resourceQuarks = (unsigned char *)NULL;
static XrmQuark maxResourceQuark = -1;

/* determines if a quark has been used for a value in any database */
#define IsResourceQuark(q)  ((q) > 0 && (q) <= maxResourceQuark && \
			     resourceQuarks[(q) >> 3] & (1 << ((q) & 7)))

typedef unsigned char XrmBits;

#define BSLASH  ((XrmBits) (1 << 5))
#define NORMAL	((XrmBits) (1 << 4))
#define EOQ	((XrmBits) (1 << 3))
#define SEP	((XrmBits) (1 << 2))
#define ENDOF	((XrmBits) (1 << 1))
#define SPACE	(NORMAL|EOQ|SEP|(XrmBits)0)
#define RSEP	(NORMAL|EOQ|SEP|(XrmBits)1)
#define EOS	(EOQ|SEP|ENDOF|(XrmBits)0)
#define EOL	(EOQ|SEP|ENDOF|(XrmBits)1)
#define BINDING	(NORMAL|EOQ)
#define ODIGIT	(NORMAL|(XrmBits)1)

#define next_char(ch,str) xrmtypes[(unsigned char)((ch) = *(++(str)))]
#define next_mbchar(ch,len,str) xrmtypes[(unsigned char)(ch = (*db->methods->mbchar)(db->mbstate, str, &len), str += len, ch)]

#define is_space(bits)		((bits) == SPACE)
#define is_EOQ(bits)		((bits) & EOQ)
#define is_EOF(bits)		((bits) == EOS)
#define is_EOL(bits)		((bits) & ENDOF)
#define is_binding(bits)	((bits) == BINDING)
#define is_odigit(bits)		((bits) == ODIGIT)
#define is_separator(bits)	((bits) & SEP)
#define is_nonpcs(bits)		(!(bits))
#define is_normal(bits)		((bits) & NORMAL)
#define is_simple(bits)		((bits) & (NORMAL|BSLASH))
#define is_special(bits)	((bits) & (ENDOF|BSLASH))

/* parsing types */
static XrmBits const xrmtypes[256] = {
    EOS,0,0,0,0,0,0,0,
    0,SPACE,EOL,0,0,
#if defined(WIN32) || defined(__UNIXOS2__)
                    EOL,	/* treat CR the same as LF, just in case */
#else
                    0,
#endif
                      0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    SPACE,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,BINDING,NORMAL,NORMAL,NORMAL,BINDING,NORMAL,
    ODIGIT,ODIGIT,ODIGIT,ODIGIT,ODIGIT,ODIGIT,ODIGIT,ODIGIT,
    NORMAL,NORMAL,RSEP,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,BSLASH,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,
    NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,NORMAL,0
    /* The rest will be automatically initialized to zero. */
};

void XrmInitialize(void)
{
    XrmQString = XrmPermStringToQuark("String");
    XrmQANY = XrmPermStringToQuark("?");
}

XrmDatabase XrmGetDatabase(
    Display *display)
{
    XrmDatabase retval;
    LockDisplay(display);
    retval = display->db;
    UnlockDisplay(display);
    return retval;
}

void XrmSetDatabase(
    Display *display,
    XrmDatabase database)
{
    LockDisplay(display);
    /* destroy database if set up imlicitely by XGetDefault() */
    if (display->db && (display->flags & XlibDisplayDfltRMDB)) {
	XrmDestroyDatabase(display->db);
	display->flags &= ~XlibDisplayDfltRMDB;
    }
    display->db = database;
    UnlockDisplay(display);
}

void
XrmStringToQuarkList(
    register _Xconst char  *name,
    register XrmQuarkList quarks)   /* RETURN */
{
    register XrmBits		bits;
    register Signature  	sig = 0;
    register char       	ch, *tname;
    register int 		i = 0;

    if ((tname = (char *)name)) {
	tname--;
	while (!is_EOF(bits = next_char(ch, tname))) {
	    if (is_binding (bits)) {
		if (i) {
		    /* Found a complete name */
		    *quarks++ = _XrmInternalStringToQuark(name,tname - name,
							  sig, False);
		    i = 0;
		    sig = 0;
		}
		name = tname+1;
	    }
	    else {
		sig = (sig << 1) + ch; /* Compute the signature. */
		i++;
	    }
	}
	*quarks++ = _XrmInternalStringToQuark(name, tname - name, sig, False);
    }
    *quarks = NULLQUARK;
}

void
XrmStringToBindingQuarkList(
    register _Xconst char   *name,
    register XrmBindingList bindings,   /* RETURN */
    register XrmQuarkList   quarks)     /* RETURN */
{
    register XrmBits		bits;
    register Signature  	sig = 0;
    register char       	ch, *tname;
    register XrmBinding 	binding;
    register int 		i = 0;

    if ((tname = (char *)name)) {
	tname--;
	binding = XrmBindTightly;
	while (!is_EOF(bits = next_char(ch, tname))) {
	    if (is_binding (bits)) {
		if (i) {
		    /* Found a complete name */
		    *bindings++ = binding;
		    *quarks++ = _XrmInternalStringToQuark(name, tname - name,
							  sig, False);

		    i = 0;
		    sig = 0;
		    binding = XrmBindTightly;
		}
		name = tname+1;

		if (ch == '*')
		    binding = XrmBindLoosely;
	    }
	    else {
		sig = (sig << 1) + ch; /* Compute the signature. */
		i++;
	    }
	}
	*bindings = binding;
	*quarks++ = _XrmInternalStringToQuark(name, tname - name, sig, False);
    }
    *quarks = NULLQUARK;
}

#ifdef DEBUG

static void PrintQuarkList(
    XrmQuarkList    quarks,
    FILE	    *stream)
{
    Bool	    firstNameSeen;

    for (firstNameSeen = False; *quarks; quarks++) {
	if (firstNameSeen) {
	    (void) fprintf(stream, ".");
	}
	firstNameSeen = True;
	(void) fputs(XrmQuarkToString(*quarks), stream);
    }
} /* PrintQuarkList */

#endif /* DEBUG */


/*
 * Fallback methods for Xrm parsing.
 * Simulate a C locale. No state needed here.
 */

static void
c_mbnoop(
    XPointer state)
{
}

static char
c_mbchar(
    XPointer state,
    const char *str,
    int *lenp)
{
    *lenp = 1;
    return *str;
}

static const char *
c_lcname(
    XPointer state)
{
    return "C";
}

static const XrmMethodsRec mb_methods = {
    c_mbnoop,	/* mbinit */
    c_mbchar,	/* mbchar */
    c_mbnoop,	/* mbfinish */
    c_lcname,	/* lcname */
    c_mbnoop	/* destroy */
};


static XrmDatabase NewDatabase(void)
{
    register XrmDatabase db;

    db = (XrmDatabase) Xmalloc(sizeof(XrmHashBucketRec));
    if (db) {
	_XCreateMutex(&db->linfo);
	db->table = (NTable)NULL;
	db->mbstate = (XPointer)NULL;
	db->methods = _XrmInitParseInfo(&db->mbstate);
	if (!db->methods)
	    db->methods = &mb_methods;
    }
    return db;
}

/* move all values from ftable to ttable, and free ftable's buckets.
 * ttable is quaranteed empty to start with.
 */
static void MoveValues(
    LTable ftable,
    register LTable ttable)
{
    register VEntry fentry, nfentry;
    register VEntry *prev;
    register VEntry *bucket;
    register VEntry tentry;
    register int i;

    for (i = ftable->table.mask, bucket = ftable->buckets; i >= 0; i--) {
	for (fentry = *bucket++; fentry; fentry = nfentry) {
	    prev = &LeafHash(ttable, fentry->name);
	    tentry = *prev;
	    *prev = fentry;
	    /* chain on all with same name, to preserve invariant order */
	    while ((nfentry = fentry->next) && nfentry->name == fentry->name)
		fentry = nfentry;
	    fentry->next = tentry;
	}
    }
    Xfree((char *)ftable->buckets);
}

/* move all tables from ftable to ttable, and free ftable.
 * ttable is quaranteed empty to start with.
 */
static void MoveTables(
    NTable ftable,
    register NTable ttable)
{
    register NTable fentry, nfentry;
    register NTable *prev;
    register NTable *bucket;
    register NTable tentry;
    register int i;

    for (i = ftable->mask, bucket = NodeBuckets(ftable); i >= 0; i--) {
	for (fentry = *bucket++; fentry; fentry = nfentry) {
	    prev = &NodeHash(ttable, fentry->name);
	    tentry = *prev;
	    *prev = fentry;
	    /* chain on all with same name, to preserve invariant order */
	    while ((nfentry = fentry->next) && nfentry->name == fentry->name)
		fentry = nfentry;
	    fentry->next = tentry;
	}
    }
    Xfree((char *)ftable);
}

/* grow the table, based on current number of entries */
static void GrowTable(
    NTable *prev)
{
    register NTable table;
    register int i;

    table = *prev;
    i = table->mask;
    if (i == 255) /* biggest it gets */
	return;
    while (i < 255 && GrowthPred(table->entries, i))
	i = (i << 1) + 1;
    i++; /* i is now the new size */
    if (table->leaf) {
	register LTable ltable;
	LTableRec otable;

	ltable = (LTable)table;
	/* cons up a copy to make MoveValues look symmetric */
	otable = *ltable;
	ltable->buckets = Xcalloc(i, sizeof(VEntry));
	if (!ltable->buckets) {
	    ltable->buckets = otable.buckets;
	    return;
	}
	ltable->table.mask = i - 1;
	MoveValues(&otable, ltable);
    } else {
	register NTable ntable;

	ntable = Xcalloc(1, sizeof(NTableRec) + (i * sizeof(NTable)));
	if (!ntable)
	    return;
	*ntable = *table;
	ntable->mask = i - 1;
	*prev = ntable;
	MoveTables(table, ntable);
    }
}

/* merge values from ftable into *pprev, destroy ftable in the process */
static void MergeValues(
    LTable ftable,
    NTable *pprev,
    Bool override)
{
    register VEntry fentry, tentry;
    register VEntry *prev;
    register LTable ttable;
    VEntry *bucket;
    int i;
    register XrmQuark q;

    ttable = (LTable)*pprev;
    if (ftable->table.hasloose)
	ttable->table.hasloose = 1;
    for (i = ftable->table.mask, bucket = ftable->buckets;
	 i >= 0;
	 i--, bucket++) {
	for (fentry = *bucket; fentry; ) {
	    q = fentry->name;
	    prev = &LeafHash(ttable, q);
	    tentry = *prev;
	    while (tentry && tentry->name != q)
		tentry = *(prev = &tentry->next);
	    /* note: test intentionally uses fentry->name instead of q */
	    /* permits serendipitous inserts */
	    while (tentry && tentry->name == fentry->name) {
		/* if tentry is earlier, skip it */
		if (!fentry->tight && tentry->tight) {
		    tentry = *(prev = &tentry->next);
		    continue;
		}
		if (fentry->tight != tentry->tight) {
		    /* no match, chain in fentry */
		    *prev = fentry;
		    prev = &fentry->next;
		    fentry = *prev;
		    *prev = tentry;
		    ttable->table.entries++;
		} else if (override) {
		    /* match, chain in fentry, splice out and free tentry */
		    *prev = fentry;
		    prev = &fentry->next;
		    fentry = *prev;
		    *prev = tentry->next;
		    /* free the overridden entry */
		    Xfree((char *)tentry);
		    /* get next tentry */
		    tentry = *prev;
		} else {
		    /* match, discard fentry */
		    prev = &tentry->next;
		    tentry = fentry; /* use as a temp var */
		    fentry = fentry->next;
		    /* free the overpowered entry */
		    Xfree((char *)tentry);
		    /* get next tentry */
		    tentry = *prev;
		}
		if (!fentry)
		    break;
	    }
	    /* at this point, tentry cannot match any fentry named q */
	    /* chain in all bindings together, preserve invariant order */
	    while (fentry && fentry->name == q) {
		*prev = fentry;
		prev = &fentry->next;
		fentry = *prev;
		*prev = tentry;
		ttable->table.entries++;
	    }
	}
    }
    Xfree((char *)ftable->buckets);
    Xfree((char *)ftable);
    /* resize if necessary, now that we're all done */
    GROW(pprev);
}

/* merge tables from ftable into *pprev, destroy ftable in the process */
static void MergeTables(
    NTable ftable,
    NTable *pprev,
    Bool override)
{
    register NTable fentry, tentry;
    NTable nfentry;
    register NTable *prev;
    register NTable ttable;
    NTable *bucket;
    int i;
    register XrmQuark q;

    ttable = *pprev;
    if (ftable->hasloose)
	ttable->hasloose = 1;
    if (ftable->hasany)
	ttable->hasany = 1;
    for (i = ftable->mask, bucket = NodeBuckets(ftable);
	 i >= 0;
	 i--, bucket++) {
	for (fentry = *bucket; fentry; ) {
	    q = fentry->name;
	    prev = &NodeHash(ttable, q);
	    tentry = *prev;
	    while (tentry && tentry->name != q)
		tentry = *(prev = &tentry->next);
	    /* note: test intentionally uses fentry->name instead of q */
	    /* permits serendipitous inserts */
	    while (tentry && tentry->name == fentry->name) {
		/* if tentry is earlier, skip it */
		if ((fentry->leaf && !tentry->leaf) ||
		    (!fentry->tight && tentry->tight &&
		     (fentry->leaf || !tentry->leaf))) {
		    tentry = *(prev = &tentry->next);
		    continue;
		}
		nfentry = fentry->next;
		if (fentry->leaf != tentry->leaf ||
		    fentry->tight != tentry->tight) {
		    /* no match, just chain in */
		    *prev = fentry;
		    *(prev = &fentry->next) = tentry;
		    ttable->entries++;
		} else {
		    if (fentry->leaf)
			MergeValues((LTable)fentry, prev, override);
		    else
			MergeTables(fentry, prev, override);
		    /* bump to next tentry */
		    tentry = *(prev = &(*prev)->next);
		}
		/* bump to next fentry */
		fentry = nfentry;
		if (!fentry)
		    break;
	    }
	    /* at this point, tentry cannot match any fentry named q */
	    /* chain in all bindings together, preserve invariant order */
	    while (fentry && fentry->name == q) {
		*prev = fentry;
		prev = &fentry->next;
		fentry = *prev;
		*prev = tentry;
		ttable->entries++;
	    }
	}
    }
    Xfree((char *)ftable);
    /* resize if necessary, now that we're all done */
    GROW(pprev);
}

void XrmCombineDatabase(
    XrmDatabase	from, XrmDatabase *into,
    Bool override)
{
    register NTable *prev;
    register NTable ftable, ttable, nftable;

    if (!*into) {
	*into = from;
    } else if (from) {
	_XLockMutex(&from->linfo);
	_XLockMutex(&(*into)->linfo);
	if ((ftable = from->table)) {
	    prev = &(*into)->table;
	    ttable = *prev;
	    if (!ftable->leaf) {
		nftable = ftable->next;
		if (ttable && !ttable->leaf) {
		    /* both have node tables, merge them */
		    MergeTables(ftable, prev, override);
		    /* bump to into's leaf table, if any */
		    ttable = *(prev = &(*prev)->next);
		} else {
		    /* into has no node table, link from's in */
		    *prev = ftable;
		    *(prev = &ftable->next) = ttable;
		}
		/* bump to from's leaf table, if any */
		ftable = nftable;
	    } else {
		/* bump to into's leaf table, if any */
		if (ttable && !ttable->leaf)
		    ttable = *(prev = &ttable->next);
	    }
	    if (ftable) {
		/* if into has a leaf, merge, else insert */
		if (ttable)
		    MergeValues((LTable)ftable, prev, override);
		else
		    *prev = ftable;
	    }
	}
	(from->methods->destroy)(from->mbstate);
	_XUnlockMutex(&from->linfo);
	_XFreeMutex(&from->linfo);
	Xfree((char *)from);
	_XUnlockMutex(&(*into)->linfo);
    }
}

void XrmMergeDatabases(
    XrmDatabase	from, XrmDatabase *into)
{
    XrmCombineDatabase(from, into, True);
}

/* store a value in the database, overriding any existing entry */
static void PutEntry(
    XrmDatabase		db,
    XrmBindingList	bindings,
    XrmQuarkList	quarks,
    XrmRepresentation	type,
    XrmValuePtr		value)
{
    register NTable *pprev, *prev;
    register NTable table;
    register XrmQuark q;
    register VEntry *vprev;
    register VEntry entry;
    NTable *nprev, *firstpprev;

#define NEWTABLE(q,i) \
    table = (NTable)Xmalloc(sizeof(LTableRec)); \
    if (!table) \
	return; \
    table->name = q; \
    table->hasloose = 0; \
    table->hasany = 0; \
    table->mask = 0; \
    table->entries = 0; \
    if (quarks[i]) { \
	table->leaf = 0; \
	nprev = NodeBuckets(table); \
    } else { \
	table->leaf = 1; \
	if (!(nprev = (NTable *)Xmalloc(sizeof(VEntry *)))) {\
	    Xfree(table); \
	    return; \
        } \
	((LTable)table)->buckets = (VEntry *)nprev; \
    } \
    *nprev = (NTable)NULL; \
    table->next = *prev; \
    *prev = table

    if (!db || !*quarks)
	return;
    table = *(prev = &db->table);
    /* if already at leaf, bump to the leaf table */
    if (!quarks[1] && table && !table->leaf)
	table = *(prev = &table->next);
    pprev = prev;
    if (!table || (quarks[1] && table->leaf)) {
	/* no top-level node table, create one and chain it in */
	NEWTABLE(NULLQUARK,1);
	table->tight = 1; /* arbitrary */
	prev = nprev;
    } else {
	/* search along until we need a value */
	while (quarks[1]) {
	    q = *quarks;
	    table = *(prev = &NodeHash(table, q));
	    while (table && table->name != q)
		table = *(prev = &table->next);
	    if (!table)
		break; /* not found */
	    if (quarks[2]) {
		if (table->leaf)
		    break; /* not found */
	    } else {
		if (!table->leaf) {
		    /* bump to leaf table, if any */
		    table = *(prev = &table->next);
		    if (!table || table->name != q)
			break; /* not found */
		    if (!table->leaf) {
			/* bump to leaf table, if any */
			table = *(prev = &table->next);
			if (!table || table->name != q)
			    break; /* not found */
		    }
		}
	    }
	    if (*bindings == XrmBindTightly) {
		if (!table->tight)
		    break; /* not found */
	    } else {
		if (table->tight) {
		    /* bump to loose table, if any */
		    table = *(prev = &table->next);
		    if (!table || table->name != q ||
			!quarks[2] != table->leaf)
			break; /* not found */
		}
	    }
	    /* found that one, bump to next quark */
	    pprev = prev;
	    quarks++;
	    bindings++;
	}
	if (!quarks[1]) {
	    /* found all the way to a leaf */
	    q = *quarks;
	    entry = *(vprev = &LeafHash((LTable)table, q));
	    while (entry && entry->name != q)
		entry = *(vprev = &entry->next);
	    /* if want loose and have tight, bump to next entry */
	    if (entry && *bindings == XrmBindLoosely && entry->tight)
		entry = *(vprev = &entry->next);
	    if (entry && entry->name == q &&
		(*bindings == XrmBindTightly) == entry->tight) {
		/* match, need to override */
		if ((type == XrmQString) == entry->string &&
		    entry->size == value->size) {
		    /* update type if not String, can be different */
		    if (!entry->string)
			RepType(entry) = type;
		    /* identical size, just overwrite value */
		    memcpy(RawValue(entry), (char *)value->addr, value->size);
		    return;
		}
		/* splice out and free old entry */
		*vprev = entry->next;
		Xfree((char *)entry);
		(*pprev)->entries--;
	    }
	    /* this is where to insert */
	    prev = (NTable *)vprev;
	}
    }
    /* keep the top table, because we may have to grow it */
    firstpprev = pprev;
    /* iterate until we get to the leaf */
    while (quarks[1]) {
	/* build a new table and chain it in */
	NEWTABLE(*quarks,2);
	if (*quarks++ == XrmQANY)
	    (*pprev)->hasany = 1;
	if (*bindings++ == XrmBindTightly) {
	    table->tight = 1;
	} else {
	    table->tight = 0;
	    (*pprev)->hasloose = 1;
	}
	(*pprev)->entries++;
	pprev = prev;
	prev = nprev;
    }
    /* now allocate the value entry */
    entry = (VEntry)Xmalloc(((type == XrmQString) ?
			     sizeof(VEntryRec) : sizeof(DEntryRec)) +
			    value->size);
    if (!entry)
	return;
    entry->name = q = *quarks;
    if (*bindings == XrmBindTightly) {
	entry->tight = 1;
    } else {
	entry->tight = 0;
	(*pprev)->hasloose = 1;
    }
    /* chain it in, with a bit of type cast ugliness */
    entry->next = *((VEntry *)prev);
    *((VEntry *)prev) = entry;
    entry->size = value->size;
    if (type == XrmQString) {
	entry->string = 1;
    } else {
	entry->string = 0;
	RepType(entry) = type;
    }
    /* save a copy of the value */
    memcpy(RawValue(entry), (char *)value->addr, value->size);
    (*pprev)->entries++;
    /* this is a new leaf, need to remember it for search lists */
    if (q > maxResourceQuark) {
	unsigned oldsize = (maxResourceQuark + 1) >> 3;
	unsigned size = ((q | 0x7f) + 1) >> 3; /* reallocate in chunks */
	if (resourceQuarks) {
	    unsigned char *prevQuarks = resourceQuarks;

	    resourceQuarks = (unsigned char *)Xrealloc((char *)resourceQuarks,
						       size);
	    if (!resourceQuarks) {
		Xfree(prevQuarks);
	    }
	} else
	    resourceQuarks = (unsigned char *)Xmalloc(size);
	if (resourceQuarks) {
	    bzero((char *)&resourceQuarks[oldsize], size - oldsize);
	    maxResourceQuark = (size << 3) - 1;
	} else {
	    maxResourceQuark = -1;
	}
    }
    if (q > 0 && resourceQuarks)
	resourceQuarks[q >> 3] |= 1 << (q & 0x7);
    GROW(firstpprev);

#undef NEWTABLE
}

void XrmQPutResource(
    XrmDatabase		*pdb,
    XrmBindingList      bindings,
    XrmQuarkList	quarks,
    XrmRepresentation	type,
    XrmValuePtr		value)
{
    if (!*pdb) *pdb = NewDatabase();
    _XLockMutex(&(*pdb)->linfo);
    PutEntry(*pdb, bindings, quarks, type, value);
    _XUnlockMutex(&(*pdb)->linfo);
}

void
XrmPutResource(
    XrmDatabase     *pdb,
    _Xconst char    *specifier,
    _Xconst char    *type,
    XrmValuePtr	    value)
{
    XrmBinding	    bindings[MAXDBDEPTH+1];
    XrmQuark	    quarks[MAXDBDEPTH+1];

    if (!*pdb) *pdb = NewDatabase();
    _XLockMutex(&(*pdb)->linfo);
    XrmStringToBindingQuarkList(specifier, bindings, quarks);
    PutEntry(*pdb, bindings, quarks, XrmStringToQuark(type), value);
    _XUnlockMutex(&(*pdb)->linfo);
}

void
XrmQPutStringResource(
    XrmDatabase     *pdb,
    XrmBindingList  bindings,
    XrmQuarkList    quarks,
    _Xconst char    *str)
{
    XrmValue	value;

    if (!*pdb) *pdb = NewDatabase();
    value.addr = (XPointer) str;
    value.size = strlen(str)+1;
    _XLockMutex(&(*pdb)->linfo);
    PutEntry(*pdb, bindings, quarks, XrmQString, &value);
    _XUnlockMutex(&(*pdb)->linfo);
}

/*	Function Name: GetDatabase
 *	Description: Parses a string and stores it as a database.
 *	Arguments: db - the database.
 *                 str - a pointer to the string containing the database.
 *                 filename - source filename, if any.
 *                 doall - whether to do all lines or just one
 */

/*
 * This function is highly optimized to inline as much as possible.
 * Be very careful with modifications, or simplifications, as they
 * may adversely affect the performance.
 *
 * Chris Peterson, MIT X Consortium		5/17/90.
 */

/*
 * Xlib spec says max 100 quarks in a lookup, will stop and return if
 * return if any single production's lhs has more than 100 components.
 */
#define QLIST_SIZE 100

/*
 * This should be big enough to handle things like the XKeysymDB or biggish
 * ~/.Xdefaults or app-defaults files. Anything bigger will be allocated on
 * the heap.
 */
#define DEF_BUFF_SIZE 8192

static void GetIncludeFile(
    XrmDatabase db,
    _Xconst char *base,
    _Xconst char *fname,
    int fnamelen);

static void GetDatabase(
    XrmDatabase db,
    _Xconst register char *str,
    _Xconst char *filename,
    Bool doall)
{
    char *rhs;
    char *lhs, lhs_s[DEF_BUFF_SIZE];
    XrmQuark quarks[QLIST_SIZE + 1];	/* allow for a terminal NullQuark */
    XrmBinding bindings[QLIST_SIZE + 1];

    register char *ptr;
    register XrmBits bits = 0;
    register char c;
    register Signature sig;
    register char *ptr_max;
    register int num_quarks;
    register XrmBindingList t_bindings;

    int len, alloc_chars;
    unsigned long str_len;
    XrmValue value;
    Bool only_pcs;
    Bool dolines;

    if (!db)
	return;

    /*
     * if strlen (str) < DEF_BUFF_SIZE allocate buffers on the stack for
     * speed otherwise malloc the buffer. From a buffer overflow standpoint
     * we can be sure that neither: a) a component on the lhs, or b) a
     * value on the rhs, will be longer than the overall length of str,
     * i.e. strlen(str).
     *
     * This should give good performance when parsing "*foo: bar" type
     * databases as might be passed with -xrm command line options; but
     * with larger databases, e.g. .Xdefaults, app-defaults, or KeysymDB
     * files, the size of the buffers will be overly large. One way
     * around this would be to double-parse each production with a resulting
     * performance hit. In any event we can be assured that a lhs component
     * name or a rhs value won't be longer than str itself.
     */

    str_len = strlen (str);
    if (DEF_BUFF_SIZE > str_len) lhs = lhs_s;
    else if ((lhs = (char*) Xmalloc (str_len)) == NULL)
	return;

    alloc_chars = DEF_BUFF_SIZE < str_len ? str_len : DEF_BUFF_SIZE;
    if ((rhs = (char*) Xmalloc (alloc_chars)) == NULL) {
	if (lhs != lhs_s) Xfree (lhs);
	return;
    }

    (*db->methods->mbinit)(db->mbstate);
    str--;
    dolines = True;
    while (!is_EOF(bits) && dolines) {
	dolines = doall;

	/*
	 * First: Remove extra whitespace.
	 */

	do {
	    bits = next_char(c, str);
	} while is_space(bits);

	/*
	 * Ignore empty lines.
	 */

	if (is_EOL(bits))
	    continue;		/* start a new line. */

	/*
	 * Second: check the first character in a line to see if it is
	 * "!" signifying a comment, or "#" signifying a directive.
	 */

	if (c == '!') { /* Comment, spin to next newline */
	    while (is_simple(bits = next_char(c, str))) {}
	    if (is_EOL(bits))
		continue;
	    while (!is_EOL(bits = next_mbchar(c, len, str))) {}
	    str--;
	    continue;		/* start a new line. */
	}

	if (c == '#') { /* Directive */
	    /* remove extra whitespace */
	    only_pcs = True;
	    while (is_space(bits = next_char(c, str))) {};
	    /* only "include" directive is currently defined */
	    if (!strncmp(str, "include", 7)) {
		str += (7-1);
		/* remove extra whitespace */
		while (is_space(bits = next_char(c, str))) {};
		/* must have a starting " */
		if (c == '"') {
		    _Xconst char *fname = str+1;
		    len = 0;
		    do {
			if (only_pcs) {
			    bits = next_char(c, str);
			    if (is_nonpcs(bits))
				only_pcs = False;
			}
			if (!only_pcs)
			    bits = next_mbchar(c, len, str);
		    } while (c != '"' && !is_EOL(bits));
		    /* must have an ending " */
		    if (c == '"')
			GetIncludeFile(db, filename, fname, str - len - fname);
		}
	    }
	    /* spin to next newline */
	    if (only_pcs) {
		while (is_simple(bits))
		    bits = next_char(c, str);
		if (is_EOL(bits))
		    continue;
	    }
	    while (!is_EOL(bits))
		bits = next_mbchar(c, len, str);
	    str--;
	    continue;		/* start a new line. */
	}

	/*
	 * Third: loop through the LHS of the resource specification
	 * storing characters and converting this to a Quark.
	 */

	num_quarks = 0;
	t_bindings = bindings;

	sig = 0;
	ptr = lhs;
	*t_bindings = XrmBindTightly;
	for(;;) {
	    if (!is_binding(bits)) {
		while (!is_EOQ(bits)) {
		    *ptr++ = c;
		    sig = (sig << 1) + c; /* Compute the signature. */
		    bits = next_char(c, str);
		}

		quarks[num_quarks++] =
			_XrmInternalStringToQuark(lhs, ptr - lhs, sig, False);

		if (num_quarks > QLIST_SIZE) {
		    Xfree(rhs);
		    if (lhs != lhs_s) Xfree (lhs);
		    (*db->methods->mbfinish)(db->mbstate);
		    return;
		}

		if (is_separator(bits))  {
		    if (!is_space(bits))
			break;

		    /* Remove white space */
		    do {
			*ptr++ = c;
			sig = (sig << 1) + c; /* Compute the signature. */
		    } while (is_space(bits = next_char(c, str)));

		    /*
		     * The spec doesn't permit it, but support spaces
		     * internal to resource name/class
		     */

		    if (is_separator(bits))
			break;
		    num_quarks--;
		    continue;
		}

		if (c == '.')
		    *(++t_bindings) = XrmBindTightly;
		else
		    *(++t_bindings) = XrmBindLoosely;

		sig = 0;
		ptr = lhs;
	    }
	    else {
		/*
		 * Magic unspecified feature #254.
		 *
		 * If two separators appear with no Text between them then
		 * ignore them.
		 *
		 * If anyone of those separators is a '*' then the binding
		 * will be loose, otherwise it will be tight.
		 */

		if (c == '*')
		    *t_bindings = XrmBindLoosely;
	    }

	    bits = next_char(c, str);
	}

	quarks[num_quarks] = NULLQUARK;

	/*
	 * Make sure that there is a ':' in this line.
	 */

	if (c != ':') {
	    char oldc;

	    /*
	     * A parsing error has occured, toss everything on the line
	     * a new_line can still be escaped with a '\'.
	     */

	    while (is_normal(bits))
		bits = next_char(c, str);
	    if (is_EOL(bits))
		continue;
	    bits = next_mbchar(c, len, str);
	    do {
		oldc = c;
		bits = next_mbchar(c, len, str);
	    } while (c && (c != '\n' || oldc == '\\'));
	    str--;
	    continue;
	}

	/*
	 * I now have a quark and binding list for the entire left hand
	 * side.  "c" currently points to the ":" separating the left hand
	 * side for the right hand side.  It is time to begin processing
	 * the right hand side.
	 */

	/*
	 * Fourth: Remove more whitespace
	 */

	for(;;) {
	    if (is_space(bits = next_char(c, str)))
		continue;
	    if (c != '\\')
		break;
	    bits = next_char(c, str);
	    if (c == '\n')
		continue;
	    str--;
	    bits = BSLASH;
	    c = '\\';
	    break;
	}

	/*
	 * Fifth: Process the right hand side.
	 */

	ptr = rhs;
	ptr_max = ptr + alloc_chars - 4;
	only_pcs = True;
	len = 1;

	for(;;) {

	    /*
	     * Tight loop for the normal case:  Non backslash, non-end of value
	     * character that will fit into the allocated buffer.
	     */

	    if (only_pcs) {
		while (is_normal(bits) && ptr < ptr_max) {
		    *ptr++ = c;
		    bits = next_char(c, str);
		}
		if (is_EOL(bits))
		    break;
		if (is_nonpcs(bits)) {
		    only_pcs = False;
		    bits = next_mbchar(c, len, str);
		}
	    }
	    while (!is_special(bits) && ptr + len <= ptr_max) {
		len = -len;
		while (len)
		    *ptr++ = str[len++];
		if (*str == '\0') {
		    bits = EOS;
		    break;
		}
		bits = next_mbchar(c, len, str);
	    }

	    if (is_EOL(bits)) {
		str--;
		break;
	    }

	    if (c == '\\') {
		/*
		 * We need to do some magic after a backslash.
		 */
		Bool read_next = True;

		if (only_pcs) {
		    bits = next_char(c, str);
		    if (is_nonpcs(bits))
			only_pcs = False;
		}
		if (!only_pcs)
		    bits = next_mbchar(c, len, str);

		if (is_EOL(bits)) {
		    if (is_EOF(bits))
			continue;
		} else if (c == 'n') {
		    /*
		     * "\n" means insert a newline.
		     */
		    *ptr++ = '\n';
		} else if (c == '\\') {
		    /*
		     * "\\" completes to just one backslash.
		     */
		    *ptr++ = '\\';
		} else {
		    /*
		     * pick up to three octal digits after the '\'.
		     */
		    char temp[3];
		    int count = 0;
		    while (is_odigit(bits) && count < 3) {
			temp[count++] = c;
			if (only_pcs) {
			    bits = next_char(c, str);
			    if (is_nonpcs(bits))
				only_pcs = False;
			}
			if (!only_pcs)
			    bits = next_mbchar(c, len, str);
		    }

		    /*
		     * If we found three digits then insert that octal code
		     * into the value string as a character.
		     */

		    if (count == 3) {
			*ptr++ = (unsigned char) ((temp[0] - '0') * 0100 +
						  (temp[1] - '0') * 010 +
						  (temp[2] - '0'));
		    }
		    else {
			int tcount;

			/*
			 * Otherwise just insert those characters into the
			 * string, since no special processing is needed on
			 * numerics we can skip the special processing.
			 */

			for (tcount = 0; tcount < count; tcount++) {
			    *ptr++ = temp[tcount]; /* print them in
						      the correct order */
			}
		    }
		    read_next = False;
		}
		if (read_next) {
		    if (only_pcs) {
			bits = next_char(c, str);
			if (is_nonpcs(bits))
			    only_pcs = False;
		    }
		    if (!only_pcs)
			bits = next_mbchar(c, len, str);
		}
	    }

	    /*
	     * It is important to make sure that there is room for at least
	     * four more characters in the buffer, since I can add that
	     * many characters into the buffer after a backslash has occured.
	     */

	    if (ptr + len > ptr_max) {
		char * temp_str;

		alloc_chars += BUFSIZ/10;
		temp_str = Xrealloc(rhs, sizeof(char) * alloc_chars);

		if (!temp_str) {
		    Xfree(rhs);
		    if (lhs != lhs_s) Xfree (lhs);
		    (*db->methods->mbfinish)(db->mbstate);
		    return;
		}

		ptr = temp_str + (ptr - rhs); /* reset pointer. */
		rhs = temp_str;
		ptr_max = rhs + alloc_chars - 4;
	    }
	}

	/*
	 * Lastly: Terminate the value string, and store this entry
	 * 	   into the database.
	 */

	*ptr++ = '\0';

	/* Store it in database */
	value.size = ptr - rhs;
	value.addr = (XPointer) rhs;

	PutEntry(db, bindings, quarks, XrmQString, &value);
    }

    if (lhs != lhs_s) Xfree (lhs);
    Xfree (rhs);

    (*db->methods->mbfinish)(db->mbstate);
}

void
XrmPutStringResource(
    XrmDatabase *pdb,
    _Xconst char*specifier,
    _Xconst char*str)
{
    XrmValue	value;
    XrmBinding	bindings[MAXDBDEPTH+1];
    XrmQuark	quarks[MAXDBDEPTH+1];

    if (!*pdb) *pdb = NewDatabase();
    XrmStringToBindingQuarkList(specifier, bindings, quarks);
    value.addr = (XPointer) str;
    value.size = strlen(str)+1;
    _XLockMutex(&(*pdb)->linfo);
    PutEntry(*pdb, bindings, quarks, XrmQString, &value);
    _XUnlockMutex(&(*pdb)->linfo);
}


void
XrmPutLineResource(
    XrmDatabase *pdb,
    _Xconst char*line)
{
    if (!*pdb) *pdb = NewDatabase();
    _XLockMutex(&(*pdb)->linfo);
    GetDatabase(*pdb, line, (char *)NULL, False);
    _XUnlockMutex(&(*pdb)->linfo);
}

XrmDatabase
XrmGetStringDatabase(
    _Xconst char    *data)
{
    XrmDatabase     db;

    db = NewDatabase();
    _XLockMutex(&db->linfo);
    GetDatabase(db, data, (char *)NULL, True);
    _XUnlockMutex(&db->linfo);
    return db;
}

/*	Function Name: ReadInFile
 *	Description: Reads the file into a buffer.
 *	Arguments: filename - the name of the file.
 *	Returns: An allocated string containing the contents of the file.
 */

static char *
ReadInFile(_Xconst char *filename)
{
    register int fd, size;
    char * filebuf;

#ifdef __UNIXOS2__
    filename = __XOS2RedirRoot(filename);
#endif

    /*
     * MS-Windows and OS/2 note: Default open mode includes O_TEXT
     */
    if ( (fd = _XOpenFile (filename, O_RDONLY)) == -1 )
	return (char *)NULL;

    /*
     * MS-Windows and OS/2 note: depending on how the sources are
     * untarred, the newlines in resource files may or may not have
     * been expanded to CRLF. Either way the size returned by fstat
     * is sufficient to read the file into because in text-mode any
     * CRLFs in a file will be converted to newlines (LF) with the
     * result that the number of bytes actually read with be <=
     * to the size returned by fstat.
     */
    {
	struct stat status_buffer;
	if ( (fstat(fd, &status_buffer)) == -1 ) {
	    close (fd);
	    return (char *)NULL;
	} else
	    size = status_buffer.st_size;
    }

    if (!(filebuf = Xmalloc(size + 1))) { /* leave room for '\0' */
	close(fd);
	return (char *)NULL;
    }
    size = read (fd, filebuf, size);

#ifdef __UNIXOS2__
    { /* kill CRLF */
      int i,k;
      for (i=k=0; i<size; i++)
	if (filebuf[i] != 0x0d) {
	   filebuf[k++] = filebuf[i];
	}
	filebuf[k] = 0;
    }
#endif

    if (size < 0) {
	close (fd);
	Xfree(filebuf);
	return (char *)NULL;
    }
    close (fd);

    filebuf[size] = '\0';	/* NULL terminate it. */
    return filebuf;
}

static void
GetIncludeFile(
    XrmDatabase db,
    _Xconst char *base,
    _Xconst char *fname,
    int fnamelen)
{
    int len;
    char *str;
    char realfname[BUFSIZ];

    if (fnamelen <= 0 || fnamelen >= BUFSIZ)
	return;
    if (*fname != '/' && base && (str = strrchr(base, '/'))) {
	len = str - base + 1;
	if (len + fnamelen >= BUFSIZ)
	    return;
	strncpy(realfname, base, len);
	strncpy(realfname + len, fname, fnamelen);
	realfname[len + fnamelen] = '\0';
    } else {
	strncpy(realfname, fname, fnamelen);
	realfname[fnamelen] = '\0';
    }
    if (!(str = ReadInFile(realfname)))
	return;
    GetDatabase(db, str, realfname, True);
    Xfree(str);
}

XrmDatabase
XrmGetFileDatabase(
    _Xconst char    *filename)
{
    XrmDatabase db;
    char *str;

    if (!(str = ReadInFile(filename)))
	return (XrmDatabase)NULL;

    db = NewDatabase();
    _XLockMutex(&db->linfo);
    GetDatabase(db, str, filename, True);
    _XUnlockMutex(&db->linfo);
    Xfree(str);
    return db;
}

Status
XrmCombineFileDatabase(
    _Xconst char    *filename,
    XrmDatabase     *target,
    Bool             override)
{
    XrmDatabase db;
    char *str;

    if (!(str = ReadInFile(filename)))
	return 0;
    if (override) {
	db = *target;
	if (!db)
	    *target = db = NewDatabase();
    } else
	db = NewDatabase();
    _XLockMutex(&db->linfo);
    GetDatabase(db, str, filename, True);
    _XUnlockMutex(&db->linfo);
    Xfree(str);
    if (!override)
	XrmCombineDatabase(db, target, False);
    return 1;
}

/* call the user proc for every value in the table, arbitrary order.
 * stop if user proc returns True.  level is current depth in database.
 */
/*ARGSUSED*/
static Bool EnumLTable(
    LTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    register int	level,
    register EClosure	closure)
{
    register VEntry *bucket;
    register int i;
    register VEntry entry;
    XrmValue value;
    XrmRepresentation type;
    Bool tightOk;

    closure->bindings[level] = (table->table.tight ?
				XrmBindTightly : XrmBindLoosely);
    closure->quarks[level] = table->table.name;
    level++;
    tightOk = !*names;
    closure->quarks[level + 1] = NULLQUARK;
    for (i = table->table.mask, bucket = table->buckets;
	 i >= 0;
	 i--, bucket++) {
	for (entry = *bucket; entry; entry = entry->next) {
	    if (entry->tight && !tightOk)
		continue;
	    closure->bindings[level] = (entry->tight ?
					XrmBindTightly : XrmBindLoosely);
	    closure->quarks[level] = entry->name;
	    value.size = entry->size;
	    if (entry->string) {
		type = XrmQString;
		value.addr = StringValue(entry);
	    } else {
		type = RepType(entry);
		value.addr = DataValue(entry);
	    }
	    if ((*closure->proc)(&closure->db, closure->bindings+1,
				 closure->quarks+1, &type, &value,
				 closure->closure))
		return True;
	}
    }
    return False;
}

static Bool EnumAllNTable(
    NTable		table,
    register int	level,
    register EClosure	closure)
{
    register NTable *bucket;
    register int i;
    register NTable entry;
    XrmQuark empty = NULLQUARK;

    if (level >= MAXDBDEPTH)
	return False;
    for (i = table->mask, bucket = NodeBuckets(table);
	 i >= 0;
	 i--, bucket++) {
	for (entry = *bucket; entry; entry = entry->next) {
	    if (entry->leaf) {
		if (EnumLTable((LTable)entry, &empty, &empty, level, closure))
		    return True;
	    } else {
		closure->bindings[level] = (entry->tight ?
					    XrmBindTightly : XrmBindLoosely);
		closure->quarks[level] = entry->name;
		if (EnumAllNTable(entry, level+1, closure))
		    return True;
	    }
	}
    }
    return False;
}

/* recurse on every table in the table, arbitrary order.
 * stop if user proc returns True.  level is current depth in database.
 */
static Bool EnumNTable(
    NTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    register int	level,
    register EClosure	closure)
{
    register NTable	entry;
    register XrmQuark	q;
    register unsigned int leaf;
    Bool (*get)(
            NTable		table,
            XrmNameList		names,
            XrmClassList 	classes,
            register int	level,
            EClosure		closure);
    Bool bilevel;

/* find entries named ename, leafness leaf, tight or loose, and call get */
#define ITIGHTLOOSE(ename) \
    NFIND(ename); \
    if (entry) { \
	if (leaf == entry->leaf) { \
	    if (!leaf && !entry->tight && entry->next && \
		entry->next->name == q && entry->next->tight && \
		(bilevel || entry->next->hasloose) && \
		EnumLTable((LTable)entry->next, names+1, classes+1, \
			   level, closure)) \
		return True; \
	    if ((*get)(entry, names+1, classes+1, level, closure)) \
		return True; \
	    if (entry->tight && (entry = entry->next) && \
		entry->name == q && leaf == entry->leaf && \
		(*get)(entry, names+1, classes+1, level, closure)) \
		return True; \
	} else if (entry->leaf) { \
	    if ((bilevel || entry->hasloose) && \
		EnumLTable((LTable)entry, names+1, classes+1, level, closure))\
		return True; \
	    if (entry->tight && (entry = entry->next) && \
		entry->name == q && (bilevel || entry->hasloose) && \
		EnumLTable((LTable)entry, names+1, classes+1, level, closure))\
		return True; \
	} \
    }

/* find entries named ename, leafness leaf, loose only, and call get */
#define ILOOSE(ename) \
    NFIND(ename); \
    if (entry && entry->tight && (entry = entry->next) && entry->name != q) \
	entry = (NTable)NULL; \
    if (entry) { \
	if (leaf == entry->leaf) { \
	    if ((*get)(entry, names+1, classes+1, level, closure)) \
		return True; \
	} else if (entry->leaf && (bilevel || entry->hasloose)) { \
	    if (EnumLTable((LTable)entry, names+1, classes+1, level, closure))\
		return True; \
	} \
    }

    if (level >= MAXDBDEPTH)
	return False;
    closure->bindings[level] = (table->tight ?
				XrmBindTightly : XrmBindLoosely);
    closure->quarks[level] = table->name;
    level++;
    if (!*names) {
	if (EnumAllNTable(table, level, closure))
	    return True;
    } else {
	if (names[1] || closure->mode == XrmEnumAllLevels) {
	    get = EnumNTable; /* recurse */
	    leaf = 0;
	    bilevel = !names[1];
	} else {
	    get = (getNTableEProcp)EnumLTable; /* bottom of recursion */
	    leaf = 1;
	    bilevel = False;
	}
	if (table->hasloose && closure->mode == XrmEnumAllLevels) {
	    NTable *bucket;
	    int i;
	    XrmQuark empty = NULLQUARK;

	    for (i = table->mask, bucket = NodeBuckets(table);
		 i >= 0;
		 i--, bucket++) {
		q = NULLQUARK;
		for (entry = *bucket; entry; entry = entry->next) {
		    if (!entry->tight && entry->name != q &&
			entry->name != *names && entry->name != *classes) {
			q = entry->name;
			if (entry->leaf) {
			    if (EnumLTable((LTable)entry, &empty, &empty,
					   level, closure))
				return True;
			} else {
			    if (EnumNTable(entry, &empty, &empty,
					   level, closure))
				return True;
			}
		    }
		}
	    }
	}

	ITIGHTLOOSE(*names);   /* do name, tight and loose */
	ITIGHTLOOSE(*classes); /* do class, tight and loose */
	if (table->hasany) {
	    ITIGHTLOOSE(XrmQANY); /* do ANY, tight and loose */
	}
	if (table->hasloose) {
	    while (1) {
		names++;
		classes++;
		if (!*names)
		    break;
		if (!names[1] && closure->mode != XrmEnumAllLevels) {
		    get = (getNTableEProcp)EnumLTable; /* bottom of recursion */
		    leaf = 1;
		}
		ILOOSE(*names);   /* loose names */
		ILOOSE(*classes); /* loose classes */
		if (table->hasany) {
		    ILOOSE(XrmQANY); /* loose ANY */
		}
	    }
	    names--;
	    classes--;
	}
    }
    /* now look for matching leaf nodes */
    entry = table->next;
    if (!entry)
	return False;
    if (entry->leaf) {
	if (entry->tight && !table->tight)
	    entry = entry->next;
    } else {
	entry = entry->next;
	if (!entry || !entry->tight)
	    return False;
    }
    if (!entry || entry->name != table->name)
	return False;
    /* found one */
    level--;
    if ((!*names || entry->hasloose) &&
	EnumLTable((LTable)entry, names, classes, level, closure))
	return True;
    if (entry->tight && entry == table->next && (entry = entry->next) &&
	entry->name == table->name && (!*names || entry->hasloose))
	return EnumLTable((LTable)entry, names, classes, level, closure);
    return False;

#undef ITIGHTLOOSE
#undef ILOOSE
}

/* call the proc for every value in the database, arbitrary order.
 * stop if the proc returns True.
 */
Bool XrmEnumerateDatabase(
    XrmDatabase		db,
    XrmNameList		names,
    XrmClassList	classes,
    int			mode,
    DBEnumProc		proc,
    XPointer		closure)
{
    XrmBinding  bindings[MAXDBDEPTH+2];
    XrmQuark	quarks[MAXDBDEPTH+2];
    register NTable table;
    EClosureRec	eclosure;
    Bool retval = False;

    if (!db)
	return False;
    _XLockMutex(&db->linfo);
    eclosure.db = db;
    eclosure.proc = proc;
    eclosure.closure = closure;
    eclosure.bindings = bindings;
    eclosure.quarks = quarks;
    eclosure.mode = mode;
    table = db->table;
    if (table && !table->leaf && !*names && mode == XrmEnumOneLevel)
	table = table->next;
    if (table) {
	if (!table->leaf)
	    retval = EnumNTable(table, names, classes, 0, &eclosure);
	else
	    retval = EnumLTable((LTable)table, names, classes, 0, &eclosure);
    }
    _XUnlockMutex(&db->linfo);
    return retval;
}

static void PrintBindingQuarkList(
    XrmBindingList      bindings,
    XrmQuarkList	quarks,
    FILE		*stream)
{
    Bool	firstNameSeen;

    for (firstNameSeen = False; *quarks; bindings++, quarks++) {
	if (*bindings == XrmBindLoosely) {
	    (void) fprintf(stream, "*");
	} else if (firstNameSeen) {
	    (void) fprintf(stream, ".");
	}
	firstNameSeen = True;
	(void) fputs(XrmQuarkToString(*quarks), stream);
    }
}

/* output out the entry in correct file syntax */
/*ARGSUSED*/
static Bool DumpEntry(
    XrmDatabase		*db,
    XrmBindingList      bindings,
    XrmQuarkList	quarks,
    XrmRepresentation   *type,
    XrmValuePtr		value,
    XPointer		data)
{
    FILE			*stream = (FILE *)data;
    register unsigned int	i;
    register char		*s;
    register char		c;

    if (*type != XrmQString)
	(void) putc('!', stream);
    PrintBindingQuarkList(bindings, quarks, stream);
    s = value->addr;
    i = value->size;
    if (*type == XrmQString) {
	(void) fputs(":\t", stream);
	if (i)
	    i--;
    }
    else
	(void) fprintf(stream, "=%s:\t", XrmRepresentationToString(*type));
    if (i && (*s == ' ' || *s == '\t'))
	(void) putc('\\', stream); /* preserve leading whitespace */
    while (i--) {
	c = *s++;
	if (c == '\n') {
	    if (i)
		(void) fputs("\\n\\\n", stream);
	    else
		(void) fputs("\\n", stream);
	} else if (c == '\\')
	    (void) fputs("\\\\", stream);
	else if ((c < ' ' && c != '\t') ||
		 ((unsigned char)c >= 0x7f && (unsigned char)c < 0xa0))
	    (void) fprintf(stream, "\\%03o", (unsigned char)c);
	else
	    (void) putc(c, stream);
    }
    (void) putc('\n', stream);
    return ferror(stream) != 0;
}

#ifdef DEBUG

void PrintTable(
    NTable table,
    FILE *file)
{
    XrmBinding  bindings[MAXDBDEPTH+1];
    XrmQuark	quarks[MAXDBDEPTH+1];
    EClosureRec closure;
    XrmQuark	empty = NULLQUARK;

    closure.db = (XrmDatabase)NULL;
    closure.proc = DumpEntry;
    closure.closure = (XPointer)file;
    closure.bindings = bindings;
    closure.quarks = quarks;
    closure.mode = XrmEnumAllLevels;
    if (table->leaf)
	EnumLTable((LTable)table, &empty, &empty, 0, &closure);
    else
	EnumNTable(table, &empty, &empty, 0, &closure);
}

#endif /* DEBUG */

void
XrmPutFileDatabase(
    XrmDatabase db,
    _Xconst char *fileName)
{
    FILE	*file;
    XrmQuark empty = NULLQUARK;

    if (!db) return;
    if (!(file = fopen(fileName, "w"))) return;
    if (XrmEnumerateDatabase(db, &empty, &empty, XrmEnumAllLevels,
			     DumpEntry, (XPointer) file))
	unlink((char *)fileName);
    fclose(file);
}

/* macros used in get/search functions */

/* find entries named ename, leafness leaf, tight or loose, and call get */
#define GTIGHTLOOSE(ename,looseleaf) \
    NFIND(ename); \
    if (entry) { \
	if (leaf == entry->leaf) { \
	    if (!leaf && !entry->tight && entry->next && \
		entry->next->name == q && entry->next->tight && \
		entry->next->hasloose && \
		looseleaf((LTable)entry->next, names+1, classes+1, closure)) \
		return True; \
	    if ((*get)(entry, names+1, classes+1, closure)) \
		return True; \
	    if (entry->tight && (entry = entry->next) && \
		entry->name == q && leaf == entry->leaf && \
		(*get)(entry, names+1, classes+1, closure)) \
		return True; \
	} else if (entry->leaf) { \
	    if (entry->hasloose && \
		looseleaf((LTable)entry, names+1, classes+1, closure)) \
		return True; \
	    if (entry->tight && (entry = entry->next) && \
		entry->name == q && entry->hasloose && \
		looseleaf((LTable)entry, names+1, classes+1, closure)) \
		return True; \
	} \
    }

/* find entries named ename, leafness leaf, loose only, and call get */
#define GLOOSE(ename,looseleaf) \
    NFIND(ename); \
    if (entry && entry->tight && (entry = entry->next) && entry->name != q) \
	entry = (NTable)NULL; \
    if (entry) { \
	if (leaf == entry->leaf) { \
	    if ((*get)(entry, names+1, classes+1, closure)) \
		return True; \
	} else if (entry->leaf && entry->hasloose) { \
	    if (looseleaf((LTable)entry, names+1, classes+1, closure)) \
		return True; \
	} \
    }

/* add tight/loose entry to the search list, return True if list is full */
/*ARGSUSED*/
static Bool AppendLEntry(
    LTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    register SClosure	closure)
{
    /* check for duplicate */
    if (closure->idx >= 0 && closure->list[closure->idx] == table)
	return False;
    if (closure->idx == closure->limit)
	return True;
    /* append it */
    closure->idx++;
    closure->list[closure->idx] = table;
    return False;
}

/* add loose entry to the search list, return True if list is full */
/*ARGSUSED*/
static Bool AppendLooseLEntry(
    LTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    register SClosure	closure)
{
    /* check for duplicate */
    if (closure->idx >= 0 && closure->list[closure->idx] == table)
	return False;
    if (closure->idx >= closure->limit - 1)
	return True;
    /* append it */
    closure->idx++;
    closure->list[closure->idx] = LOOSESEARCH;
    closure->idx++;
    closure->list[closure->idx] = table;
    return False;
}

/* search for a leaf table */
static Bool SearchNEntry(
    NTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    SClosure		closure)
{
    register NTable	entry;
    register XrmQuark	q;
    register unsigned int leaf;
    Bool		(*get)(
            NTable		table,
            XrmNameList		names,
            XrmClassList 	classes,
            SClosure		closure);

    if (names[1]) {
	get = SearchNEntry; /* recurse */
	leaf = 0;
    } else {
	get = (getNTableSProcp)AppendLEntry; /* bottom of recursion */
	leaf = 1;
    }
    GTIGHTLOOSE(*names, AppendLooseLEntry);   /* do name, tight and loose */
    GTIGHTLOOSE(*classes, AppendLooseLEntry); /* do class, tight and loose */
    if (table->hasany) {
	GTIGHTLOOSE(XrmQANY, AppendLooseLEntry); /* do ANY, tight and loose */
    }
    if (table->hasloose) {
	while (1) {
	    names++;
	    classes++;
	    if (!*names)
		break;
	    if (!names[1]) {
		get = (getNTableSProcp)AppendLEntry; /* bottom of recursion */
		leaf = 1;
	    }
	    GLOOSE(*names, AppendLooseLEntry);   /* loose names */
	    GLOOSE(*classes, AppendLooseLEntry); /* loose classes */
	    if (table->hasany) {
		GLOOSE(XrmQANY, AppendLooseLEntry); /* loose ANY */
	    }
	}
    }
    /* now look for matching leaf nodes */
    entry = table->next;
    if (!entry)
	return False;
    if (entry->leaf) {
	if (entry->tight && !table->tight)
	    entry = entry->next;
    } else {
	entry = entry->next;
	if (!entry || !entry->tight)
	    return False;
    }
    if (!entry || entry->name != table->name)
	return False;
    /* found one */
    if (entry->hasloose &&
	AppendLooseLEntry((LTable)entry, names, classes, closure))
	return True;
    if (entry->tight && entry == table->next && (entry = entry->next) &&
	entry->name == table->name && entry->hasloose)
	return AppendLooseLEntry((LTable)entry, names, classes, closure);
    return False;
}

Bool XrmQGetSearchList(
    XrmDatabase     db,
    XrmNameList	    names,
    XrmClassList    classes,
    XrmSearchList   searchList,	/* RETURN */
    int		    listLength)
{
    register NTable	table;
    SClosureRec		closure;

    if (listLength <= 0)
	return False;
    closure.list = (LTable *)searchList;
    closure.idx = -1;
    closure.limit = listLength - 2;
    if (db) {
	_XLockMutex(&db->linfo);
	table = db->table;
	if (*names) {
	    if (table && !table->leaf) {
		if (SearchNEntry(table, names, classes, &closure)) {
		    _XUnlockMutex(&db->linfo);
		    return False;
		}
	    } else if (table && table->hasloose &&
		       AppendLooseLEntry((LTable)table, names, classes,
					 &closure)) {
		_XUnlockMutex(&db->linfo);
		return False;
	    }
	} else {
	    if (table && !table->leaf)
		table = table->next;
	    if (table &&
		AppendLEntry((LTable)table, names, classes, &closure)) {
		_XUnlockMutex(&db->linfo);
		return False;
	    }
	}
	_XUnlockMutex(&db->linfo);
    }
    closure.list[closure.idx + 1] = (LTable)NULL;
    return True;
}

Bool XrmQGetSearchResource(
	     XrmSearchList	searchList,
    register XrmName		name,
    register XrmClass		class,
    	     XrmRepresentation	*pType,  /* RETURN */
    	     XrmValue		*pValue) /* RETURN */
{
    register LTable *list;
    register LTable table;
    register VEntry entry = NULL;
    int flags;

/* find tight or loose entry */
#define VTIGHTLOOSE(q) \
    entry = LeafHash(table, q); \
    while (entry && entry->name != q) \
	entry = entry->next; \
    if (entry) \
	break

/* find loose entry */
#define VLOOSE(q) \
    entry = LeafHash(table, q); \
    while (entry && entry->name != q) \
	entry = entry->next; \
    if (entry) { \
	if (!entry->tight) \
	    break; \
	if ((entry = entry->next) && entry->name == q) \
	    break; \
    }

    list = (LTable *)searchList;
    /* figure out which combination of name and class we need to search for */
    flags = 0;
    if (IsResourceQuark(name))
	flags = 2;
    if (IsResourceQuark(class))
	flags |= 1;
    if (!flags) {
	/* neither name nor class has ever been used to name a resource */
	table = (LTable)NULL;
    } else if (flags == 3) {
	/* both name and class */
	while ((table = *list++)) {
	    if (table != LOOSESEARCH) {
		VTIGHTLOOSE(name);  /* do name, tight and loose */
		VTIGHTLOOSE(class); /* do class, tight and loose */
	    } else {
		table = *list++;
		VLOOSE(name);  /* do name, loose only */
		VLOOSE(class); /* do class, loose only */
	    }
	}
    } else {
	/* just one of name or class */
	if (flags == 1)
	    name = class;
	while ((table = *list++)) {
	    if (table != LOOSESEARCH) {
		VTIGHTLOOSE(name); /* tight and loose */
	    } else {
		table = *list++;
		VLOOSE(name); /* loose only */
	    }
	}
    }
    if (table) {
	/* found a match */
	if (entry->string) {
	    *pType = XrmQString;
	    pValue->addr = StringValue(entry);
	} else {
	    *pType = RepType(entry);
	    pValue->addr = DataValue(entry);
	}
	pValue->size = entry->size;
	return True;
    }
    *pType = NULLQUARK;
    pValue->addr = (XPointer)NULL;
    pValue->size = 0;
    return False;

#undef VTIGHTLOOSE
#undef VLOOSE
}

/* look for a tight/loose value */
static Bool GetVEntry(
    LTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    VClosure		closure)
{
    register VEntry entry;
    register XrmQuark q;

    /* try name first */
    q = *names;
    entry = LeafHash(table, q);
    while (entry && entry->name != q)
	entry = entry->next;
    if (!entry) {
	/* not found, try class */
	q = *classes;
	entry = LeafHash(table, q);
	while (entry && entry->name != q)
	    entry = entry->next;
	if (!entry)
	    return False;
    }
    if (entry->string) {
	*closure->type = XrmQString;
	closure->value->addr = StringValue(entry);
    } else {
	*closure->type = RepType(entry);
	closure->value->addr = DataValue(entry);
    }
    closure->value->size = entry->size;
    return True;
}

/* look for a loose value */
static Bool GetLooseVEntry(
    LTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    VClosure		closure)
{
    register VEntry	entry;
    register XrmQuark	q;

#define VLOOSE(ename) \
    q = ename; \
    entry = LeafHash(table, q); \
    while (entry && entry->name != q) \
	entry = entry->next; \
    if (entry && entry->tight && (entry = entry->next) && entry->name != q) \
	entry = (VEntry)NULL;

    /* bump to last component */
    while (names[1]) {
	names++;
	classes++;
    }
    VLOOSE(*names);  /* do name, loose only */
    if (!entry) {
	VLOOSE(*classes); /* do class, loose only */
	if (!entry)
	    return False;
    }
    if (entry->string) {
	*closure->type = XrmQString;
	closure->value->addr = StringValue(entry);
    } else {
	*closure->type = RepType(entry);
	closure->value->addr = DataValue(entry);
    }
    closure->value->size = entry->size;
    return True;

#undef VLOOSE
}

/* recursive search for a value */
static Bool GetNEntry(
    NTable		table,
    XrmNameList		names,
    XrmClassList 	classes,
    VClosure		closure)
{
    register NTable	entry;
    register XrmQuark	q;
    register unsigned int leaf;
    Bool		(*get)(
            NTable              table,
            XrmNameList         names,
            XrmClassList        classes,
            VClosure            closure);
    NTable		otable;

    if (names[2]) {
	get = GetNEntry; /* recurse */
	leaf = 0;
    } else {
	get = (getNTableVProcp)GetVEntry; /* bottom of recursion */
	leaf = 1;
    }
    GTIGHTLOOSE(*names, GetLooseVEntry);   /* do name, tight and loose */
    GTIGHTLOOSE(*classes, GetLooseVEntry); /* do class, tight and loose */
    if (table->hasany) {
	GTIGHTLOOSE(XrmQANY, GetLooseVEntry); /* do ANY, tight and loose */
    }
    if (table->hasloose) {
	while (1) {
	    names++;
	    classes++;
	    if (!names[1])
		break;
	    if (!names[2]) {
		get = (getNTableVProcp)GetVEntry; /* bottom of recursion */
		leaf = 1;
	    }
	    GLOOSE(*names, GetLooseVEntry);   /* do name, loose only */
	    GLOOSE(*classes, GetLooseVEntry); /* do class, loose only */
	    if (table->hasany) {
		GLOOSE(XrmQANY, GetLooseVEntry); /* do ANY, loose only */
	    }
	}
    }
    /* look for matching leaf tables */
    otable = table;
    table = table->next;
    if (!table)
	return False;
    if (table->leaf) {
	if (table->tight && !otable->tight)
	    table = table->next;
    } else {
	table = table->next;
	if (!table || !table->tight)
	    return False;
    }
    if (!table || table->name != otable->name)
	return False;
    /* found one */
    if (table->hasloose &&
	GetLooseVEntry((LTable)table, names, classes, closure))
	return True;
    if (table->tight && table == otable->next) {
	table = table->next;
	if (table && table->name == otable->name && table->hasloose)
	    return GetLooseVEntry((LTable)table, names, classes, closure);
    }
    return False;
}

Bool XrmQGetResource(
    XrmDatabase         db,
    XrmNameList		names,
    XrmClassList 	classes,
    XrmRepresentation	*pType,  /* RETURN */
    XrmValuePtr		pValue)  /* RETURN */
{
    register NTable table;
    VClosureRec closure;

    if (db && *names) {
	_XLockMutex(&db->linfo);
	closure.type = pType;
	closure.value = pValue;
	table = db->table;
	if (names[1]) {
	    if (table && !table->leaf) {
		if (GetNEntry(table, names, classes, &closure)) {
		    _XUnlockMutex(&db->linfo);
		    return True;
		}
	    } else if (table && table->hasloose &&
		    GetLooseVEntry((LTable)table, names, classes, &closure)) {
		_XUnlockMutex (&db->linfo);
		return True;
	    }
	} else {
	    if (table && !table->leaf)
		table = table->next;
	    if (table && GetVEntry((LTable)table, names, classes, &closure)) {
		_XUnlockMutex(&db->linfo);
		return True;
	    }
	}
	_XUnlockMutex(&db->linfo);
    }
    *pType = NULLQUARK;
    pValue->addr = (XPointer)NULL;
    pValue->size = 0;
    return False;
}

Bool
XrmGetResource(XrmDatabase db, _Xconst char *name_str, _Xconst char *class_str,
	       XrmString *pType_str, XrmValuePtr pValue)
{
    XrmName		names[MAXDBDEPTH+1];
    XrmClass		classes[MAXDBDEPTH+1];
    XrmRepresentation   fromType;
    Bool		result;

    XrmStringToNameList(name_str, names);
    XrmStringToClassList(class_str, classes);
    result = XrmQGetResource(db, names, classes, &fromType, pValue);
    (*pType_str) = XrmQuarkToString(fromType);
    return result;
}

/* destroy all values, plus table itself */
static void DestroyLTable(
    LTable table)
{
    register int i;
    register VEntry *buckets;
    register VEntry entry, next;

    buckets = table->buckets;
    for (i = table->table.mask; i >= 0; i--, buckets++) {
	for (next = *buckets; (entry = next); ) {
	    next = entry->next;
	    Xfree((char *)entry);
	}
    }
    Xfree((char *)table->buckets);
    Xfree((char *)table);
}

/* destroy all contained tables, plus table itself */
static void DestroyNTable(
    NTable table)
{
    register int i;
    register NTable *buckets;
    register NTable entry, next;

    buckets = NodeBuckets(table);
    for (i = table->mask; i >= 0; i--, buckets++) {
	for (next = *buckets; (entry = next); ) {
	    next = entry->next;
	    if (entry->leaf)
		DestroyLTable((LTable)entry);
	    else
		DestroyNTable(entry);
	}
    }
    Xfree((char *)table);
}

const char *
XrmLocaleOfDatabase(
    XrmDatabase db)
{
    const char* retval;
    _XLockMutex(&db->linfo);
    retval = (*db->methods->lcname)(db->mbstate);
    _XUnlockMutex(&db->linfo);
    return retval;
}

void XrmDestroyDatabase(
    XrmDatabase   db)
{
    register NTable table, next;

    if (db) {
	_XLockMutex(&db->linfo);
	for (next = db->table; (table = next); ) {
	    next = table->next;
	    if (table->leaf)
		DestroyLTable((LTable)table);
	    else
		DestroyNTable(table);
	}
	_XUnlockMutex(&db->linfo);
	_XFreeMutex(&db->linfo);
	(*db->methods->destroy)(db->mbstate);
	Xfree((char *)db);
    }
}