summaryrefslogtreecommitdiff
path: root/mmdb2/mmdb_mmcif_.cpp
blob: f77d147118836a55f796f3dfe2381554c913b059 (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
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
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
//  $Id: mmdb_mmcif_.cpp $
//  =================================================================
//
//   CCP4 Coordinate Library: support of coordinate-related
//   functionality in protein crystallography applications.
//
//   Copyright (C) Eugene Krissinel 2000-2013.
//
//    This library is free software: you can redistribute it and/or
//    modify it under the terms of the GNU Lesser General Public
//    License version 3, modified in accordance with the provisions
//    of the license to address the requirements of UK law.
//
//    You should have received a copy of the modified GNU Lesser
//    General Public License along with this library. If not, copies
//    may be downloaded from http://www.ccp4.ac.uk/ccp4license.php
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU Lesser General Public License for more details.
//
//  =================================================================
//
//    10.05.15   <--  Date of Last Modification.
//                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  -----------------------------------------------------------------
//
//  **** Module  :  MMDB_MMCIF <implementation>
//       ~~~~~~~~~
//  **** Project :  MacroMolecular Data Base (MMDB)
//       ~~~~~~~~~
//  **** Classes :  mmdb::mmcif::Category ( mmCIF category    )
//       ~~~~~~~~~  mmdb::mmcif::Struct   ( mmCIF structure   )
//                  mmdb::mmcif::Loop     ( mmCIF loop        )
//                  mmdb::mmcif::Data     ( mmCIF data block  )
//                  mmdb::mmcif::File     ( mmCIF file        )
//
//  (C) E. Krissinel 2000-2015
//
//  =================================================================
//

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

#include "mmdb_mmcif_.h"

namespace mmdb  {

  namespace mmcif  {

    //  ======================  SortTags  ===============================

    void  SortTags ( psvector tag, int len, ivector index )  {
    int  i,k,l,l1,l2;
      if (len==1)  {
        index[0] = 0;
        return;
      }
      if (strcasecmp(tag[0],tag[1])<0)  {
        index[0] = 0;
        index[1] = 1;
      } else  {
        index[0] = 1;
        index[1] = 0;
      }
      for (k=2;k<len;k++)  {
        l2 = k-1;
        if (strcasecmp(tag[k],tag[index[0]])<0)       l2 = 0;
        else if (strcasecmp(tag[k],tag[index[l2]])>0) l2 = k;
        else  {
          l1 = 0;
          while (l1<l2-1)  {
            l = (l1+l2)/2;
            if (strcasecmp(tag[k],tag[index[l]])<0)  l2 = l;
                                               else  l1 = l;
          }
        }
        for (i=k;i>l2;i--)
          index[i] = index[i-1];
        index[l2] = k;
      }
    }


    //  ======================  Category  ==========================

    const int CIF_NODATA_DOT        = 0;
    const int CIF_NODATA_QUESTION   = 1;
    cpstr CIF_NODATA_DOT_FIELD      = pstr("\x02" ".");
    cpstr CIF_NODATA_QUESTION_FIELD = pstr("\x02" "?");

    Category::Category() : io::Stream()  {
      InitCategory();
    }

    Category::Category ( cpstr N ) : io::Stream()  {
      InitCategory();
      SetCategoryName ( N );
    }

    Category::Category ( io::RPStream Object ) : io::Stream(Object)  {
      InitCategory();
    }

    Category::~Category()  {
      FreeMemory();
    }

    void Category::InitCategory()  {
      name       = NULL;
      nTags      = 0;
      tag        = NULL;
      index      = NULL;
      nAllocTags = 0;
    }

    void Category::FreeMemory()  {
    int i;
      if (name)  delete[] name;
      name = NULL;
      for (i=0;i<nAllocTags;i++)
        if (tag[i])  delete[] tag[i];
      FreeVectorMemory ( tag  ,0 );
      FreeVectorMemory ( index,0 );
      nTags      = 0;
      nAllocTags = 0;
    }

    void Category::SetCategoryName ( cpstr N )  {
      if (N[0])  CreateCopy ( name,N );
      else  {
        CreateCopy ( name,pstr(" ") );
        name[0] = char(1);  // no category name
      }
    }

    void Category::ExpandTags ( int nTagsNew )  {
    int      i,nAT;
    psvector tag1;
    ivector  index1;
      if (nTagsNew>nAllocTags)  {
        nAT = nTagsNew + IMin(nAllocTags/2+1,20);
        GetVectorMemory ( tag1  ,nAT,0 );
        GetVectorMemory ( index1,nAT,0 );
        for (i=0;i<nAllocTags;i++)  {
          tag1  [i] = tag  [i];
          index1[i] = index[i];
        }
        for (i=nAllocTags;i<nAT;i++)  {
          tag1  [i] = NULL;
          index1[i] = i;
        }
        FreeVectorMemory ( tag  ,0 );
        FreeVectorMemory ( index,0 );
        tag        = tag1;
        index      = index1;
        nAllocTags = nAT;
      }
    }

    pstr Category::GetTag ( int tagNo )  {
      if ((tagNo>=0) && (tagNo<nTags))  return tag[tagNo];
      return NULL;
    }

    void Category::Sort()  {
    //  Sorts tags for easing the search
    int i,k;
      if (nAllocTags>0)  {
        k = 0;
        if (!index)
          GetVectorMemory ( index,nAllocTags,0 );
        for (i=0;i<nTags;i++)
          if (tag[i])  {
            if (k<i)  {
              tag[k] = tag[i];
              tag[i] = NULL;
            }
            k++;
          }
        nTags = k;
        SortTags ( tag,nTags,index );
      }
    }

    void Category::Optimize()  {
    int      i,k;
    psvector tag1;
      k = 0;
      for (i=0;i<nTags;i++)
        if (tag[i])  k++;
      if (k<=0)  FreeMemory();
      else if (k!=nAllocTags)  {
        GetVectorMemory  ( tag1,k,0 );
        FreeVectorMemory ( index,0 );
        k = 0;
        for (i=0;i<nTags;i++)
          if (tag[i])
            tag1[k++] = tag[i];
        FreeVectorMemory ( tag,0 );
        tag        = tag1;
        nTags      = k;
        nAllocTags = nTags;
        Sort();
      }
    }

    int  Category::GetTagNo ( cpstr ttag )  {
    //   Binary search for index of tag ttag in tag[].
    // Return:
    //    >=0 : position of the tag found
    //     <0 : the tag was not found, it could be inserted before
    //          (-RC-1)th element, where RC is the return value
    int l1,l2,l,k;

      if (!tag)    return -1;

      if (!index)  Sort();

      l = 0;
      l1 = 0;
      l2 = nTags-1;
      k  = 1;
      while (l1<l2-1)  {
        l = (l1+l2)/2;
        k = strcasecmp ( ttag,tag[index[l]] );
        if (k<0)      l2 = l;
        else if (k>0) l1 = l;
        else {
          l1 = l;
          break;
        }
      }

      if (k==0)  return index[l];    // is at RCth position
      k = strcasecmp ( ttag,tag[index[l1]] );
      if (k==0)  return index[l1];   // is at RCth position
      if (k<0)   return -1;          // would be at (-RC-1)th position
      if (l2!=l1)  {
        k = strcasecmp ( ttag,tag[index[l2]] );
        if (k==0)  return index[l2]; // is at RCth position
        if (k>0)   return -2-l2;     // would be at l2+1=(-RC-1)th position
      }

      return -2-l1;                  // would be at l1+1=(-RC-1)th position

    }

    int  Category::AddTag ( cpstr ttag )  {
    //  return -1: the tag has been added on the top of array;
    //             index is added and sorted automatically
    //        >=0: the tag is already in the array -- its position
    //             is returned
    int  i1,i;
      if (!tag)  {
        ExpandTags ( 3 );  // get space for first 3 tags
        CreateCopy ( tag[0],ttag );
        nTags  = 1;
        return -nTags;  // the tag has been added on the top of array
      }
      i1 = GetTagNo ( ttag );
      if (i1>=0)  return i1;  // non-negative returns mean that
                              // the tag is already in the array
      i1 = -i1-1;  // otherwise the tag has to be added and indexed at here
      // put new tag on the top of array and update index
      ExpandTags ( nTags+1 );
      CreateCopy ( tag[nTags],ttag );
      for (i=nTags;i>i1;i--)
        index[i] = index[i-1];
      index[i1] = nTags;
      nTags++;
      return -nTags; // the tag has been added on the top of array
    }

    void Category::PrintTags()  {
    int i;
      Sort();
      printf ( " Unsorted tags:\n" );
      for (i=0;i<nTags;i++)
        if (tag[i])
          printf ( "  %s.%s\n",name,tag[i] );
      if (index)  {
        printf ( " Sorted tags:\n" );
        for (i=0;i<nTags;i++)
          if (tag[index[i]])
            printf ( "  %s.%s\n",name,tag[index[i]] );
      }
    }

    bool Category::CheckTags ( cpstr * tagList )  {
    int i;
      i = 0;
      while (tagList[i][0])  {
        if (GetTagNo(tagList[i])<0)  return false;
        i++;
      }
      return true;
    }

    void  Category::PutCategoryName ( cpstr newName )  {
      CreateCopy ( name,newName );
    }

    void  Category::Copy ( PCategory Category )  {
    int i;
      FreeMemory();
      if (Category)  {
        CreateCopy ( name,Category->name );
        nTags      = Category->nTags;
        nAllocTags = nTags;
        if (nTags>0) {
          GetVectorMemory ( tag  ,nAllocTags,0 );
          GetVectorMemory ( index,nAllocTags,0 );
          for (i=0;i<nTags;i++)  {
            tag[i]   = NULL;
            CreateCopy ( tag[i],Category->tag[i] );
            index[i] = Category->index[i];
          }
        }
      }
    }


    void Category::write ( io::RFile f )  {
    int i;
      if (!index)  Sort();
      f.CreateWrite ( name   );
      f.WriteInt    ( &nTags );
      for (i=0;i<nTags;i++)
        f.CreateWrite ( tag[i] );
      f.WriteVector ( index,nTags,0 );
    }

    void Category::read ( io::RFile f )  {
    int i;
      FreeMemory   ();
      f.CreateRead ( name   );
      f.ReadInt    ( &nTags );
      nAllocTags = nTags;
      if (nTags>0) {
        GetVectorMemory ( tag,nTags,0 );
        for (i=0;i<nTags;i++)  {
          tag[i] = NULL;
          f.CreateRead ( tag[i] );
        }
      }
      f.CreateReadVector ( index,0 );
    }

    MakeStreamFunctions(Category)



    //  ======================  Struct  ===========================


    Struct::Struct() : Category() {
      InitStruct();
    }

    Struct::Struct ( cpstr N ) : Category(N) {
      InitStruct();
    }

    Struct::Struct ( io::RPStream Object ) : Category(Object)  {
      InitStruct();
    }

    Struct::~Struct()  {
      FreeMemory();
    }

    void Struct::FreeMemory()  {
    int i;
      for (i=0;i<nAllocTags;i++)
        if (field[i]) delete[] field[i];
      FreeVectorMemory ( field,0 );
      Category::FreeMemory();
    }

    void Struct::InitStruct()  {
      field = NULL;
    }

    void Struct::Optimize()  {
    int      i,k;
    psvector f1;
      k = 0;
      for (i=0;i<nTags;i++)
        if (!tag[i])  {
          if (field[i])  delete[] field[i];
          field[i] = NULL;
        } else if (!field[i])  {
          delete[] tag[i];
          tag[i] = NULL;
        } else
          k++;
      if (k<=0)  FreeMemory();
      else if (k!=nAllocTags)  {
        f1 = new pstr[k];
        k  = 0;
        for (i=0;i<nTags;i++)
          if (tag[i])
            f1[k++] = field[i];
        FreeVectorMemory ( field,0 );
        field = f1;
        Category::Optimize();
      }
    }

    void Struct::AddField ( cpstr F, cpstr T, bool Concatenate )  {
    psvector field1;
    int      i,nAT;
    pstr     nf;

      nAT = nAllocTags;
      i   = AddTag ( T );

      if (i<0) {
        // The tag was not in the list, but has been added on the top
        // of list. Now expand the field list and put new field on
        // the top of it.
        if (nAllocTags>nAT)  {
          GetVectorMemory ( field1,nAllocTags,0 );
          for (i=0;i<nTags-1;i++)
            field1[i] = field[i];
          for (i=nTags-1;i<nAllocTags;i++)
            field1[i] = NULL;
          FreeVectorMemory ( field,0 );
          field = field1;
        }
        i        = nTags-1;
        field[i] = NULL;
      }

      if (!F)  {
        if ((!Concatenate) || (!field[i]))  {
          CreateCopy ( field[i],pstr(" ?") );
          field[i][0] = char(2);
        }
      } else if ((!Concatenate) || (!field[i]))
        CreateCopy ( field[i],F );
      else  {
        nf = new char[strlen(field[i])+strlen(F)+1];
        strcpy ( nf,field[i] );
        strcat ( nf,F        );
        delete[] field[i];
        field[i] = nf;
      }

    }

    pstr Struct::GetField ( int tagNo )  {
      if ((tagNo>=0) && (tagNo<nTags))  return field[tagNo];
      return NULL;
    }

    int  Struct::GetString ( pstr & S, cpstr TName,
                                   bool Remove )  {
    int k = GetTagNo ( TName );
      if (S)  delete[] S;
      S = NULL;
      if (!field)     return CIFRC_NoField;
      if (k<0)        return CIFRC_NoTag;
      if (!field[k])  return CIFRC_NoField;
      if (field[k][0]==char(2))  {
        if (Remove)  {
          delete[] field[k];
          field[k] = NULL;
        }
      } else if (Remove)  {
        S = field[k];
        field[k] = NULL;
      } else
        CreateCopy ( S,field[k] );
      return 0;
    }

    pstr Struct::GetString ( cpstr TName, int & RC )  {
    int k = GetTagNo ( TName );
      if (k<0)  {
        RC = CIFRC_NoTag;
        return NULL;
      }
      if (!field)  {
        RC = CIFRC_NoField;
        return NULL;
      }
      if (!field[k])  {
        RC = CIFRC_NoField;
        return NULL;
      }
      RC = 0;
      if (field[k][0]==char(2))  return NULL;
      return field[k];
    }

    int  Struct::DeleteField ( cpstr TName )  {
    int k = GetTagNo ( TName );
      if ((k>=0) && (field)) {
        if (field[k])  delete[] field[k];
        field[k] = NULL;
      }
      return k;
    }

    int  Struct::GetReal ( realtype & R, cpstr TName,
                                 bool Remove )  {
    pstr endptr;
    int  RC;
    int  k = GetTagNo ( TName );
      R = 0.0;
      if (!field)                return CIFRC_NoField;
      if (k<0)                   return CIFRC_NoTag;
      if (!field[k])             return CIFRC_NoField;
      if (field[k][0]==char(2))  return CIFRC_NoData;
      R = strtod ( field[k],&endptr );
      if (endptr==field[k])  RC = CIFRC_WrongFormat;
      else  {
        RC = 0;
        if (Remove)  {
          delete[] field[k];
          field[k] = NULL;
        }
      }
      return RC;
    }

    int  Struct::GetInteger ( int & I, cpstr TName,
                                    bool Remove )  {
    pstr endptr;
    int  RC;
    int  k = GetTagNo ( TName );
      I = 0;
      if (!field)                return CIFRC_NoField;
      if (k<0)                   return CIFRC_NoTag;
      if (!field[k])             return CIFRC_NoField;
      if (field[k][0]==char(2))  {
        if (field[k][1]=='.')  I = MinInt4;
        return CIFRC_NoData;
      }
      I = mround ( strtod(field[k],&endptr) );
      if (endptr==field[k])  RC = CIFRC_WrongFormat;
      else  {
        RC = 0;
        if (Remove)  {
          delete[] field[k];
          field[k] = NULL;
        }
      }
      return RC;
    }


    void Struct::PutString ( cpstr S, cpstr T,
                                   bool NonBlankOnly )  {
    pstr p;
      if (!S)  PutNoData ( CIF_NODATA_QUESTION,T );
      else  {
        p = pstr(S);
        if (NonBlankOnly)
          while (*p==' ')  p++;
        if (!(*p))  PutNoData ( CIF_NODATA_DOT,T );
              else  AddField  ( S,T,false );
      }
    }

    void Struct::PutDate ( cpstr T )  {
    time_t t;
    tm *   tstruct;
     char   S[100];
      t       = time ( NULL );
      tstruct = localtime(&t);
      if (tstruct)
            sprintf ( S,"%4i-%02i-%02i",
                tstruct->tm_year+1900,tstruct->tm_mon+1,tstruct->tm_mday );
      else  strcpy  ( S,"YYYY-MM-DD" );
      AddField ( S,T,false );
    }


    void Struct::PutNoData ( int NoDataType, cpstr T )  {
    char S[10];
      S[0] = char(2);
      if (NoDataType==CIF_NODATA_DOT)  S[1] = '.';
                                 else  S[1] = '?';
      S[2] = char(0);
      AddField ( S,T,false );
    }


    void Struct::PutReal ( realtype R, cpstr T, int prec )  {
    char rS[100];
      sprintf  ( rS,"%.*g",prec,R );
      AddField ( rS,T,false );
    }

    void Struct::PutReal ( realtype R, cpstr T, cpstr format )  {
    char rS[100];
      sprintf  ( rS,format,R );
      AddField ( DelSpaces(rS,' '),T,false );
    }

    void Struct::PutInteger ( int I, cpstr T )  {
    char iS[100];
      if (I>MinInt4)  {
        sprintf  ( iS,"%i",I );
        AddField ( iS,T,false );
      } else
        PutNoData ( CIF_NODATA_DOT,T );
    }



    #define  NODATA_Q  pstr("?")
    #define  NODATA_P  pstr(".")

    bool Struct::WriteMMCIFStruct ( cpstr FName,
                                    io::GZ_MODE gzipMode )  {
    io::File f;
      f.assign ( FName,true,false,gzipMode );
      if (f.rewrite())  {
        WriteMMCIF ( f );
        f.shut();
        return true;
      } else
        return false;
    }

    #define _max_output_line_width 256

    void Struct::WriteMMCIF ( io::RFile f )  {
    int   i,j,k,l,m,n;
    pstr  F;

      // calculate maximal length of tags
      l = 0;
      for (i=0;i<nTags;i++)
        l = IMax(l,strlen(tag[i]));
      l += 1;  // add one space separator

      // calculate maximal space left for data
      m  = _max_output_line_width - l;
      // subtract category name width
      if (name[0]!=char(1))  m -= strlen(name);

      // start outout
      f.LF();
      for (i=0;i<nTags;i++)  {  // for each tag

        // print category name, if not hidden, and dot
        if (name[0]!=char(1))  {
          f.Write ( name      );
          f.Write ( pstr(".") );
        }

        // print tag, checking for duplicate tag flag
        F = strchr ( tag[i],'\1' );
        if (F)  {
          *F = char(0);
          f.Write ( tag[i] );
          *F = '\1';
        } else
          f.Write ( tag[i] );

        // print field
        if (field[i])  {  // field is defined
          F = field[i];
          if (strchr(F,'\n') || strstr(F,"\" "))  {
            f.Write ( pstr("\n;")   );
            f.Write ( F             );
            f.Write ( pstr("\n;\n") );
          } else {
            n = strlen(F);
            if (n>m)  // wrap around if field is too long
              f.Write ( pstr("\n ") );
            else {
              k = l-strlen(tag[i]);
              for (j=0;j<k;j++)
                f.Write ( pstr(" ") );
            }
            if ((((F[0]=='.') || (F[0]=='?')) && (!F[1])) ||
                strchr(F,' '))  {
              f.Write ( pstr("\"")   );
              f.Write ( field[i]     );
              f.Write ( pstr("\"\n") );
            } else if (field[i][0]==char(2))  {
              f.WriteLine ( &(field[i][1]) );
            } else if (!field[i][0])  {
              f.WriteLine ( NODATA_P );
            } else
              f.WriteLine ( field[i] );
          }

        } else  {  // field if not defined, put question mark

          k = l-strlen(tag[i]);
          for (j=0;j<k;j++)
            f.Write ( pstr(" ") );
          f.WriteLine ( NODATA_Q );

        }

      }

    }

    void Struct::Copy ( PCategory Struct )  {
    int i;
      Category::Copy ( Struct );
      if (nTags>0)  {
        GetVectorMemory ( field,nTags,0 );
        for (i=0;i<nTags;i++)  {
          field[i] = NULL;
          CreateCopy ( field[i],PStruct(Struct)->field[i] );
        }
      }
    }

    void Struct::write ( io::RFile f )  {
    int i;
      Category::write ( f );
      for (i=0;i<nTags;i++)
        f.CreateWrite ( field[i] );
    }

    void Struct::read ( io::RFile f )  {
    int i;
      Category::read ( f );
      if (nTags>0)  {
        GetVectorMemory ( field,nTags,0 );
        for (i=0;i<nTags;i++)  {
          field[i] = NULL;
          f.CreateRead ( field[i] );
        }
      }
    }


    MakeStreamFunctions(Struct)



    //  ======================  Loop  ==============================


    Loop::Loop() : Category()  {
      InitLoop();
    }

    Loop::Loop ( cpstr N ) : Category(N)  {
      InitLoop();
    }

    Loop::Loop ( io::RPStream Object ) : Category(Object)  {
      InitLoop();
    }

    Loop::~Loop()  {
      FreeMemory();
    }

    void Loop::InitLoop()  {
      nRows      = 0;
      field      = NULL;
      iColumn    = 0;
      nAllocRows = 0;
    }

    void Loop::FreeMemory()  {
      DeleteFields();
      Category::FreeMemory();
    }

    void Loop::Optimize()  {
    int      i,j,nT,nR,k,m;
    bool  empty;
    psmatrix f1;

      if (!field)  {
        Category::Optimize();  // optimize tags
        return;
      }

      // first check for empty columns
      nT = 0;
      for (i=0;i<nTags;i++)
        if (!tag[i])  {
          for (j=0;j<nRows;j++)  // delete ith column of field
            if (field[j])  {
              if (field[j][i])
                delete[] field[j][i];
              field[j][i] = NULL;
            }
        } else  {
          empty = true;
          j = 0;
          while ((j<nRows) && empty)  {  // check if ith column is empty
            if (field[j])
              empty = !field[j][i];
            j++;
          }
          if (empty)  {    // if ith column is empty, delete its tag
            delete[] tag[i];
            tag[i] = NULL;
          } else           // otherwise count ith tag
            nT++;
        }

      // now check for empty rows
      nR = 0;
      for (j=0;j<nRows;j++)
        if (field[j])  {
          i = 0;
          while ((i<nTags) && (!field[j][i])) i++;
          if (i>=nTags)  {
            delete[] field[j];  // delete empty row
            field[j] = NULL;
          } else
            nR++;             // count non-empty row
        }
      if ((nT<=0) || (nR<=0))
        FreeMemory();  // the loop is completely empty
      else if ((nT!=nTags) || (nR!=nAllocRows))  {
        f1 = new psvector[nR];
        m  = 0;
        for (j=0;j<nRows;j++)
          if (field[j])  {
            f1[m] = new pstr[nT];
            k = 0;
            for (i=0;i<nTags;i++)
              if (tag[i])
                f1[m][k++] = field[j][i];
            m++;
            delete[] field[j];
          }
        if (field)  delete[] field;
        field = f1;
        nRows = nR;
        nAllocRows = nRows;
        Category::Optimize();  // optimize tags
      }

    }

    void Loop::DeleteFields()  {
    int i,j;
      if (field)  {
        for (i=0;i<nAllocRows;i++)
          if (field[i])  {
            for (j=0;j<nTags;j++)
              if (field[i][j])  delete[] field[i][j];
            delete[] field[i];
          }
        delete[] field;
        field      = NULL;
        nRows      = 0;
        nAllocRows = 0;
      }
    }

    void Loop::AddLoopTag ( cpstr T, bool Remove )  {
    psmatrix  f1;
    int       i,j,nT1;
      if (Remove)  {
        DeleteFields();
        AddTag ( T );
      } else  {
        f1    = field;
        field = NULL;
        i     = AddTag ( T );
        if ((f1) && (i<0))  {
          // The tag was added on the top of tag array. Create
          // and fill new fields.
          field = new psvector[nAllocRows];
          nT1   = nTags-1;
          for (i=0;i<nAllocRows;i++)
            if (f1[i])  {
              field[i] = new pstr[nTags];
              for (j=0;j<nT1;j++)
                field[i][j] = f1[i][j];
              field[i][nT1] = NULL;
              f1[i] = NULL;
            } else
              field[i] = NULL;
          delete[] f1;
        } else
          // The tag was already in the category. Just restore fields.
          field = f1;
      }
    }


    void Loop::ExpandRows ( int nRowsNew )  {
    int      nAR,i;
    psmatrix field1;
      if (nRowsNew>nAllocRows)  {
        nAR    = nRowsNew + IMin(nAllocRows/2+10,2000);
        field1 = new psvector[nAR];
        for (i=0;i<nAllocRows;i++)
          field1[i] = field[i];
        for (i=nAllocRows;i<nAR;i++)
          field1[i] = NULL;
        if (field)  delete[] field;
        field      = field1;
        nAllocRows = nAR;
      }
    }

    void Loop::AddString ( cpstr S, bool NonBlankOnly )  {
    int  i;
    pstr p;
      if (!S)  AddNoData ( CIF_NODATA_QUESTION );
      else  {
        p = pstr(S);
        if (NonBlankOnly)
          while (*p==' ')  p++;
        if (!(*p))  AddNoData ( CIF_NODATA_DOT );
        else  {
          if (iColumn==0)  {  // start a new row
            ExpandRows ( nRows+1 );
            field[nRows] = new pstr[nTags];
            for (i=0;i<nTags;i++)
              field[nRows][i] = NULL;
            nRows++;
          }
          CreateCopy ( field[nRows-1][iColumn],S );
          iColumn++;
          if (iColumn>=nTags) iColumn = 0;
        }
      }
    }

    void Loop::AddNoData ( int NoDataType )  {
    char S[10];
      S[0] = char(2);
      if (NoDataType==CIF_NODATA_DOT)  S[1] = '.';
                                 else  S[1] = '?';
      S[2] = char(0);
      AddString ( S );
    }

    void Loop::AddReal ( realtype R, int prec )  {
    char rS[100];
      sprintf ( rS,"%.*g",prec,R );
      AddString ( rS );
    }

    void Loop::AddReal ( realtype R, cpstr format )  {
    char rS[100];
      sprintf ( rS,format,R );
      AddString ( DelSpaces(rS,' ') );
    }

    void Loop::AddInteger ( int I )  {
    char iS[100];
      if (I>MinInt4)  {
        sprintf ( iS,"%i",I );
        AddString ( iS );
      } else
        AddNoData ( CIF_NODATA_DOT );
    }


    pstr Loop::GetField ( int rowNo, int tagNo )  {
      if ((tagNo>=0) && (tagNo<nTags) &&
          (rowNo>=0) && (rowNo<nRows))  {
        if (field[rowNo])  return field[rowNo][tagNo];
      }
      return NULL;
    }

    int  Loop::GetString ( pstr & S, cpstr TName, int nrow,
                                 bool Remove)  {
    int k = GetTagNo ( TName );
      if (S)  delete[] S;
      S = NULL;
      if (k<0)                       return CIFRC_NoTag;
      if ((nrow<0) || (nrow>=nRows)) return CIFRC_WrongIndex;
      if (!field[nrow])              return CIFRC_NoField;
      if (!field[nrow][k])           return CIFRC_NoField;
      if (field[nrow][k][0]==char(2))  {
        if (Remove)  {
          delete[] field[nrow][k];
          field[nrow][k] = NULL;
        }
      } else if (Remove)  {
        S = field[nrow][k];
        field[nrow][k] = NULL;
      } else
        CreateCopy ( S,field[nrow][k] );
      return 0;
    }

    pstr Loop::GetString ( cpstr TName, int nrow, int & RC )  {
    int k = GetTagNo ( TName );
      if (k<0)  {
        RC = CIFRC_NoTag;
        return NULL;
      }
      if ((nrow<0) || (nrow>=nRows))  {
        RC = CIFRC_WrongIndex;
        return NULL;
      }
      if (!field[nrow])  {
        RC = CIFRC_NoField;
        return NULL;
      }
      if (!field[nrow][k])  {
        RC = CIFRC_NoField;
        return NULL;
      }
      RC = 0;
      // char(2) means the field was either '.' or '?'
      if (field[nrow][k][0]==char(2))  return NULL;
      return field[nrow][k];
    }

    //  CopyString() does nothing if RC is not 0
    void Loop::CopyString   ( pstr  buf,   int maxlength,
                                    cpstr TName, int nrow, int & RC )  {
    pstr p;
    int  k;

      if (RC)  return;

      k = GetTagNo ( TName );
      if (k<0)  {
        RC = CIFRC_NoTag;
        buf[0] = char(0);
        return;
      }
      if ((nrow<0) || (nrow>=nRows))  {
        RC = CIFRC_WrongIndex;
        buf[0] = char(0);
        return;
      }
      if (!field[nrow])  {
        RC = CIFRC_NoField;
        buf[0] = char(0);
        return;
      }
      p = field[nrow][k];
      if (!p)  {
        RC = CIFRC_NoField;
        buf[0] = char(0);
        return;
      }

      // char(2) means the field was either '.' or '?'
      if (p[0]==char(2))  {
        buf[0] = p[0];
        buf[1] = char(0);
      } else
        strncpy ( buf,p,IMin(maxlength,strlen(p)+1) );

    }



    int Loop::DeleteField ( cpstr TName, int nrow )  {
    int k = GetTagNo ( TName );
      if (k<0)  return CIFRC_NoTag;
      if ((nrow<0) || (nrow>=nRows))
                return CIFRC_WrongIndex;
      if (field[nrow])  {
        if (field[nrow][k])  delete[] field[nrow][k];
        field[nrow][k] = NULL;
      }
      return k;
    }

    int Loop::DeleteRow ( int nrow )  {
    int i;
      if ((nrow<0) || (nrow>=nRows))
                return CIFRC_WrongIndex;
      if (field[nrow])  {
        for (i=0;i<nTags;i++)
          if (field[nrow][i])  {
            delete[] field[nrow][i];
            field[nrow][i] = NULL;
          }
        delete[] field[nrow];
        field[nrow] = NULL;
      }
      return 0;
    }

    int  Loop::GetReal ( realtype & R, cpstr TName, int nrow,
                               bool Remove )  {
    pstr endptr;
    int  k = GetTagNo ( TName );
      if (k<0)  return CIFRC_NoTag;
      if ((nrow<0) || (nrow>=nRows))
                return CIFRC_WrongIndex;
      R = 0.0;
      if (!field[nrow])                return CIFRC_NoField;
      if (!field[nrow][k])             return CIFRC_NoField;
      if (field[nrow][k][0]==char(2))  return CIFRC_NoField;
      R = strtod ( field[nrow][k],&endptr );
      if (endptr==field[nrow][k])      return CIFRC_WrongFormat;
      if (Remove)  {
        delete[] field[nrow][k];
        field[nrow][k] = NULL;
      }
      return 0;
    }

    void Loop::CopyReal ( realtype & R, cpstr TName, int nrow,
                                int & RC )  {
    pstr endptr;
    int  k;

      if (RC)  return;

    //  R = 0.0;
      k = GetTagNo ( TName );

      if (k<0)                              RC = CIFRC_NoTag;
      else if ((nrow<0) || (nrow>=nRows))   RC = CIFRC_WrongIndex;
      else if (!field[nrow])                RC = CIFRC_NoField;
      else if (!field[nrow][k])             RC = CIFRC_NoField;
      else if (field[nrow][k][0]==char(2))  RC = CIFRC_NoField;
      else  {
        R = strtod ( field[nrow][k],&endptr );
        if (endptr==field[nrow][k])  RC = CIFRC_WrongFormat;
      }

    }

    void Loop::CopyInteger ( int & I, cpstr TName, int nrow,
                                   int & RC )  {
    pstr endptr;
    int  k;

      if (RC)  return;

      I = 0;
      k = GetTagNo ( TName );

      if (k<0)                              RC = CIFRC_NoTag;
      else if ((nrow<0) || (nrow>=nRows))   RC = CIFRC_WrongIndex;
      else if (!field[nrow])                RC = CIFRC_NoField;
      else if (!field[nrow][k])             RC = CIFRC_NoField;
      else if (field[nrow][k][0]==char(2))  RC = CIFRC_NoField;
      else  {
        I = mround ( strtod ( field[nrow][k],&endptr ) );
        if (endptr==field[nrow][k])  RC = CIFRC_WrongFormat;
      }

    }

    int  Loop::GetInteger ( int & I, cpstr TName, int nrow,
                                  bool Remove )  {
    pstr endptr;
    int  k = GetTagNo ( TName );
      if (k<0)  return CIFRC_NoTag;
      if ((nrow<0) || (nrow>=nRows))
                return CIFRC_WrongIndex;
      I = 0;
      if (!field[nrow])                return CIFRC_NoField;
      if (!field[nrow][k])             return CIFRC_NoField;
      if (field[nrow][k][0]==char(2))  {
        if (field[nrow][k][1]=='.')  I = MinInt4;
        return CIFRC_NoField;
      }
      I = mround ( strtod(field[nrow][k],&endptr) );
      if (endptr==field[nrow][k])      return CIFRC_WrongFormat;
      if (Remove)  {
        delete[] field[nrow][k];
        field[nrow][k] = NULL;
      }
      return 0;
    }


    int  Loop::GetSVector ( psvector & S, cpstr TName,
                                  int i1, int i2, bool Remove )  {
    int j,k,r1,r2;
      r1 = IMin(i1,i2);
      r2 = IMin(IMax(i1,i2),nRows-1);
      if ((r1<0) || (r1>=nRows) || (r2<0)) return CIFRC_WrongIndex;
      k = GetTagNo ( TName );
      if (k<0)  return CIFRC_NoTag;
      if (!S)
        GetVectorMemory ( S,r2-r1+1,r1 );
      if (Remove)  {
        for (j=r1;j<=r2;j++)
          if (field[j])  {
            S[j] = field[j][k];
            field[j][k] = NULL;
            if (S[j])  {
              if (S[j][0]==char(2))  {
                delete[] S[j];
                S[j] = NULL;
              }
            }
          } else
            S[j] = NULL;
      } else  {
        for (j=r1;j<=r2;j++)  {
          S[j] = NULL;
          if (field[j])  {
            if (field[j][k])  {
              if (field[j][k][0]!=char(2))
                CreateCopy ( S[j],field[j][k] );
            }
          }
        }
      }
      return 0;
    }

    int  Loop::GetRVector ( rvector & R, cpstr TName,
                                  int i1, int i2, bool Remove )  {
    int  j,k,r1,r2,RC;
    pstr endptr;
      r1 = IMin(i1,i2);
      r2 = IMin(IMax(i1,i2),nRows-1);
      if ((r1<0) || (r1>=nRows) || (r2<0)) return CIFRC_WrongIndex;
      k = GetTagNo ( TName );
      if (k<0)  return CIFRC_NoTag;
      if (!R)
        GetVectorMemory ( R,r2-r1+1,r1 );
      RC = 0;
      for (j=r1;j<=r2;j++)  {
        R[j] = 0.0;
        if (field[j])  {
          if (field[j][k])  {
            R[j] = strtod ( field[j][k],&endptr );
            if (endptr==field[j][k])  RC = CIFRC_WrongFormat;
            if (Remove)  {
              delete[] field[j][k];
              field[j][k] = NULL;
            }
          }
        }
      }
      return RC;
    }

    int  Loop::GetIVector ( ivector & I, cpstr TName,
                                  int i1, int i2, bool Remove )  {
    int  j,k,r1,r2,RC;
    pstr endptr;
      r1 = IMin(i1,i2);
      r2 = IMin(IMax(i1,i2),nRows-1);
      if ((r1<0) || (r1>=nRows) || (r2<0)) return CIFRC_WrongIndex;
      k = GetTagNo ( TName );
      if (k<0)    return CIFRC_NoTag;
      if (!I)
        GetVectorMemory ( I,r2-r1+1,r1 );
      RC = 0;
      for (j=r1;j<=r2;j++)  {
        I[j] = 0;
        if (field[j])  {
          if (field[j][k])  {
            I[j] = mround ( strtod(field[j][k],&endptr) );
            if (endptr==field[j][k]) RC = CIFRC_WrongFormat;
            if (Remove)  {
              delete[] field[j][k];
              field[j][k] = NULL;
            }
          }
        }
      }
      return RC;
    }


    void Loop::PutString ( cpstr S, cpstr T, int nrow )  {
    psmatrix field1;
    int      nT,nR,iT,i,j;
      nT = nTags;
      nR = nRows;
      iT = AddTag ( T );
      if (iT<0)  iT = nTags-1;
      if (nTags>nT)  {
        // a new tag has been added; all field must be reallocated.
        nRows      = IMax(nR,nrow+1);  // nrow is indexed like 0,1,...
        nAllocRows = IMax(nR,nrow+IMin(nR/2+1,2000));
        field1     = new psvector[nAllocRows];
        for (i=0;i<nR;i++)
          if (field[i])  {
            field1[i] = new pstr[nTags];
            for (j=0;j<nT;j++)
              field1[i][j] = field[i][j];
            for (j=nT;j<nTags;j++)
              field1[i][j] = NULL;
            delete[] field[i];
          } else
            field1[i] = NULL;
        for (i=nR;i<nRows;i++)
          field1[i] = NULL;
        if (field)  delete[] field;
        field = field1;
      } else if (nrow>=nR)  {
        // only new rows are to be added
        ExpandRows ( nrow+1 );
        nRows++;
      }
      if (!field[nrow])  {
        field[nrow] = new pstr[nTags];
        for (j=0;j<nTags;j++)
          field[nrow][j] = NULL;
      }
      CreateCopy ( field[nrow][iT],S );
      iColumn = iT+1;
      if (iColumn>=nTags) iColumn = 0;
    }


    void Loop::PutNoData ( int NoDataType, cpstr T, int nrow )  {
    char S[10];
      S[0] = char(2);
      if (NoDataType==CIF_NODATA_DOT)  S[1] = '.';
                                 else  S[1] = '?';
      S[2] = char(0);
      PutString ( S,T,nrow );
    }


    void Loop::PutReal ( realtype R, cpstr T, int nrow, int prec )  {
    char rS[100];
      sprintf ( rS,"%.*g",prec,R );
      PutString ( rS,T,nrow );
    }

    void Loop::PutReal ( realtype R, cpstr T, int nrow,
                               cpstr format )  {
    char rS[100];
      sprintf ( rS,format,R );
      PutString ( DelSpaces(rS,' '),T,nrow );
    }

    void Loop::PutInteger ( int I, cpstr T, int nrow )  {
    char iS[100];
      if (I>MinInt4)  {
        sprintf ( iS,"%i",I );
        PutString ( iS,T,nrow );
      } else
        PutNoData ( CIF_NODATA_DOT,T,nrow );
    }

    void Loop::PutSVector ( psvector S, cpstr T, int i1, int i2 )  {
    int i,j,k;
      PutString ( S[i2],T,i2 );
      if (iColumn==0)  k = nTags-1;
                 else  k = iColumn-1;
      for (i=i2-1;i>=i1;i--)  {
        if (!field[i])  {
          field[i] = new pstr[nTags];
          for (j=0;j<nTags;j++)
            field[i][j] = NULL;
        }
        CreateCopy ( field[i][k],S[i] );
      }
    }

    void Loop::PutRVector ( rvector R, cpstr T,
                                  int i1, int i2, int prec )  {
    int  i,j,k;
    char rS[100];
      PutReal ( R[i2],T,i2,prec );
      if (iColumn==0)  k = nTags-1;
                 else  k = iColumn-1;
      for (i=i2-1;i>=i1;i--)  {
        if (!field[i])  {
          field[i] = new pstr[nTags];
          for (j=0;j<nTags;j++)
            field[i][j] = NULL;
        }
        sprintf ( rS,"%.*g",prec,R[i] );
        CreateCopy ( field[i][k],rS );
      }
    }

    void Loop::PutIVector ( ivector I, cpstr T,
                                  int i1, int i2 )  {
    int  l,j,k;
    char iS[100];
      PutInteger ( I[i2],T,i2 );
      if (iColumn==0)  k = nTags-1;
                 else  k = iColumn-1;
      for (l=i2-1;l>=i1;l--)  {
        if (!field[l])  {
          field[l] = new pstr[nTags];
          for (j=0;j<nTags;j++)
            field[l][j] = NULL;
        }
        sprintf ( iS,"%i",I[l] );
        CreateCopy ( field[l][k],iS );
      }
    }

    bool Loop::WriteMMCIFLoop ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File f;
      f.assign ( FName,true,false,gzipMode );
      if (f.rewrite())  {
        WriteMMCIF ( f );
        f.shut();
        return true;
      } else
        return false;
    }

    void Loop::WriteMMCIF ( io::RFile f )  {
    int     i,j,k,m,n;
    ivector l;
    pstr    F;

      // write loop keyword
      f.Write ( pstr("\nloop_\n") );

      GetVectorMemory ( l,nTags,0 );
      k = 0;
      for (i=0;i<nTags;i++)  {
        if (name[0]!=char(1))  {
          f.Write ( name      );
          f.Write ( pstr(".") );
        }
        F = strchr ( tag[i],'\1' );
        if (F)  {
          *F = char(0);
          f.WriteLine ( tag[i] );
          *F = '\1';
        } else
          f.WriteLine ( tag[i] );
        l[i] = 0;
        for (j=0;j<nRows;j++)
          if (field[j])  {
            if (field[j][i])  {
              F = field[j][i];
              if (strchr(F,'\n') || strstr(F,"\" "))
                                       l[i] = 10001;
              else if (F[0]==char(2))  l[i] = IMax(l[i],1);
              else if (((F[0]=='.') || (F[0]=='?')) &&
                       (!F[1]))        l[i] = IMax(l[i],3);
              else  {
                if (strchr(F,' '))  m = 2;
                              else  m = 0;
                l[i] = IMax(l[i],strlen(F)+m);
              }
            }
          }
        l[i] = IMax(l[i],1);
        k += l[i]+1;
        if (k>_max_output_line_width)  {
          l[i] = -l[i];
          k = 0;
        }
      }
      for (i=0;i<nRows;i++)  {
        m = 0;  // counts symbols in the string
        k = 0;  // rest of left-aligned fields to fill with spaces
        for (j=0;j<nTags;j++)  {
          n = k;
          k = l[j];   // length of the field
          if (k<0)  k = -k;
          m += k+1;
          if (m>_max_output_line_width)  {
            f.LF();
            m = k+1;
          } else
            while (n>0) {
              f.Write ( pstr(" ") );
              n--;
            }
          if (field[i])  {
            if (field[i][j])  {
              F = field[i][j];
              if (k>10000)  {
                if (F[0]==char(2))  {
                  f.Write     ( pstr(" ") );
                  f.WriteLine ( &(F[1])   );
                } else if (!F[0])  {
                  f.Write     ( pstr(" ") );
                  f.WriteLine ( NODATA_P  );
                } else  {
                  f.Write     ( pstr(";") );
                  f.WriteLine ( F         );
                  f.WriteLine ( pstr(";") );
                }
                m = 0;
                k = 0;
              } else if ((((F[0]=='.') || (F[0]=='?')) && (!F[1])) ||
                         strchr(F,' '))  {
                f.Write ( pstr(" \"") );
                f.Write ( F           );
                f.Write ( pstr("\"")  );
                k -= strlen(F)+2;
              } else if (F[0]==char(2))  {
                f.Write ( pstr(" ") );
                f.Write ( &(F[1])   );
                k--;
              } else if (!F[0])  {
                f.Write ( pstr(" ") );
                f.Write ( NODATA_P  );
                k--;
              } else  {
                f.Write ( pstr(" ") );
                f.Write ( F         );
                k -= strlen(F);
              }
            } else  {
              f.Write ( pstr(" ") );
              f.Write ( NODATA_Q  );
              k--;
            }
          } else  {
            f.Write ( pstr(" ") );
            f.Write ( NODATA_Q  );
            k--;
          }
        }
        if (m) f.LF();
      }

    }


    void Loop::Copy ( PCategory Loop )  {
    int i,j;
      Category::Copy ( Loop );
      nRows      = PLoop(Loop)->nRows;
      nAllocRows = nRows;
      if ((nTags>0) && (nRows>0))  {
        field = new psvector[nRows];
        for (i=0;i<nRows;i++)  {
          if (PLoop(Loop)->field[i])  {
            field[i] = new pstr[nTags];
            for (j=0;j<nTags;j++)  {
              field[i][j] = NULL;
              CreateCopy ( field[i][j],PLoop(Loop)->field[i][j] );
            }
          } else
            field[i] = NULL;
        }
      }
      iColumn = PLoop(Loop)->iColumn;
    }


    void Loop::write ( io::RFile f )  {
    int i,j;
      Category::write ( f );
      f.WriteInt ( &nRows );
      if ((nTags>0) && (nRows>0))  {
        for (i=0;i<nRows;i++)  {
          if (field[i])  {
            j = 1;
            f.WriteInt ( &j );
            for (j=0;j<nTags;j++)
              f.CreateWrite ( field[i][j] );
          } else  {
            j = 0;
            f.WriteInt ( &j );
          }
        }
      }
      f.WriteInt ( &iColumn );
    }

    void Loop::read ( io::RFile f )  {
    int i,j;
      Category::read ( f );
      f.ReadInt ( &nRows );
      nAllocRows = nRows;
      if ((nTags>0) && (nRows>0))  {
        field = new psvector[nRows];
        for (i=0;i<nRows;i++)  {
          f.ReadInt ( &j );
          if (j)  {
            field[i] = new pstr[nTags];
            for (j=0;j<nTags;j++)  {
              field[i][j] = NULL;
              f.CreateRead ( field[i][j] );
            }
          } else
            field[i] = NULL;
        }
      }
      f.ReadInt ( &iColumn );
    }


    MakeStreamFunctions(Loop)



    //  ======================  Data  =============================


    Data::Data() : io::Stream()  {
      InitData();
    }

    Data::Data ( cpstr N ) : io::Stream()  {
      InitData();
      CreateCopy ( name,N );
    }

    Data::Data ( io::RPStream Object ) : io::Stream(Object)  {
      InitData();
    }

    Data::~Data() {
      FreeMemory(0);
    }

    void Data::InitData()  {
      name         = NULL;
      nCategories  = 0;
      Category     = NULL;
      index        = NULL;
      flags        = 0;
      Warning      = 0;
      loopNo       = 0;
      tagNo        = 0;
      WrongCat     = NULL;
      WrongTag     = NULL;
      nWrongFields = 0;
    }

    void Data::FreeMemory ( int key )  {
    int i;
      if (name)  delete[] name;
      name = NULL;
      if (Category)  {
        for (i=0;i<nCategories;i++)
          if (Category[i]) delete Category[i];
        delete[] Category;
        Category = NULL;
      }
      nCategories = 0;
      FreeVectorMemory ( index,0 );
      if (key==0)  FreeWrongFields();
    }

    void Data::FreeWrongFields()  {
    int i;
      if (WrongCat)  {
        for (i=0;i<nWrongFields;i++)
          if (WrongCat[i])  delete[] WrongCat[i];
        delete[] WrongCat;
      }
      if (WrongTag)  {
        for (i=0;i<nWrongFields;i++)
          if (WrongTag[i])  delete[] WrongTag[i];
        delete[] WrongTag;
      }
      WrongCat     = NULL;
      WrongTag     = NULL;
      nWrongFields = 0;
    }


    void  Data::SetPrintWarnings ( bool SPW )  {
      if (SPW)  SetFlag    ( CIFFL_PrintWarnings );
          else  RemoveFlag ( CIFFL_PrintWarnings );
    }

    void  Data::SetStopOnWarning ( bool SOW )  {
      if (SOW)  SetFlag    ( CIFFL_StopOnWarnings );
          else  RemoveFlag ( CIFFL_StopOnWarnings );
    }

    void  Data::SetFlag ( CIF_FLAG F )  {
      flags |= F;
    }

    void  Data::RemoveFlag ( CIF_FLAG F )  {
      flags &= ~F;
    }

    void  Data::SetWrongFields ( cpstr *cats, cpstr *tags )  {
    int i,lc,lt;
      FreeWrongFields();
      if ((!cats) || (!tags))  return;
      lc = 0;
      while (cats[lc]) lc++;
      lt = 0;
      while (tags[lt]) lt++;
      nWrongFields = IMax(lc,lt);
      if (nWrongFields>0)  {
        WrongCat = new pstr[nWrongFields];
        WrongTag = new pstr[nWrongFields];
        for (i=0;i<nWrongFields;i++)  {
          WrongCat[i] = NULL;
          WrongTag[i] = NULL;
          if (cats[i])  {
            if (cats[i][0])  CreateCopy ( WrongCat[i],cats[i] );
          }
          if (!WrongCat[i])  {
            CreateCopy ( WrongCat[i],pstr(" ") );
            WrongCat[i][0] = char(1);
          }
          if (tags[i])  CreateCopy ( WrongTag[i],tags[i]  );
                  else  CreateCopy ( WrongTag[i],pstr("") );
        }
      }
    }

    bool Data::CheckWrongField ( cpstr C, cpstr T )  {
    int i;
      for (i=0;i<nWrongFields;i++)
        if ((!strcasecmp(C,WrongCat[i])) &&
            (!strcasecmp(T,WrongTag[i])))  return true;
      return false;
    }

    #define _max_buf_len   500

    static char  _err_string[_max_buf_len+1];
    static int   _err_line;


    int  Data::ReadMMCIFData ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File f;
    char     S[_max_buf_len+1];
    int      RC,lcount;
      f.assign ( FName,true,false,gzipMode );
      if (f.reset(true))  {
        S[0]   = char(0);
        lcount = 0;
        RC     = ReadMMCIFData ( f,S,lcount );
        f.shut();
        return RC;
      } else  {
        _err_string[0] = char(0);
        _err_line      = 0;
        Warning = CIFRC_CantOpenFile;
        return CIFRC_CantOpenFile;
      }
    }


    // ---------------  General I/O functions

    int  Data::ReadMMCIFData ( io::RFile f, pstr S, int & lcount )  {
    pstr p;
    int  i,llen;
    pstr L;

      FreeMemory(1);
      Warning = 0;
      loopNo  = 0;
      tagNo   = 0;

      // 1. Look for 'data_' tag
      do {
        p = &(S[0]);
        while ((*p==' ') || (*p==char(9)))  p++;
        if (strncmp(p,"data_",5))  {
          f.ReadLine ( S,_max_buf_len );
          lcount++;
          p = NULL;
        }
      } while ((!p) && (!f.FileEnd()));

      if (!p)  {
        strcpy ( _err_string,S );
        _err_line = lcount;
        if (flags & CIFFL_PrintWarnings)
          printf ( "\n **** mmCIF READ ERROR "
                   "<<line %i: no 'data_XXXX' tag found>>\n",lcount );
        return CIFRC_NoDataLine;
      }

      llen = _max_buf_len;
      L    = new char[llen];
      i    = 0;
      p   += 5;
      while ((*p) && (*p!=' ') && (*p!=char(9)))  {
        L[i++] = *p;
        p++;
      }
      L[i] = char(0);
      CreateCopy ( name,L );


      // 2. Loop over tags until next 'data_' or end of file

      while (p)  {

        // skip spaces
        while ((*p==' ') || (*p==char(9)))  p++;

        if ((*p) && (*p!='#'))  {  // this is not a comment, continue
          if (*p=='_')
            GetDataItem ( f,S,L,p,lcount,llen );
          else if (!strncmp(p,"loop_",5))
            GetLoop ( f,S,L,p,lcount,llen );
          else if (!strncmp(p,"data_",5))  {
            p = NULL;
            break;
          } else  {
            // if got to here, the file is corrupted
            strcpy ( _err_string,S );
            _err_line = lcount;
            Warning |= CIFW_UnrecognizedItems;
            if (flags & CIFFL_PrintWarnings)
              printf ( "\n **** mmCIF READ WARNING "
                       "<<line %i: unrecognized string>>\n%s\n",
                       lcount,S );
            while ((*p) && (*p!=' ') && (*p!=char(9)))
              if (*p=='#')  *p = char(0);
                      else  p++;
          }
        } else
          *p = char(0);

        if (Warning && (flags & CIFFL_StopOnWarnings))  {
          if (L)  delete[] L;
          return Warning;
        }

        if (!(*p))  {
          if (!f.FileEnd())  {
            f.ReadLine ( S,_max_buf_len );
            lcount++;
            p = &(S[0]);
          } else
            p = NULL;
        }

      }

      if (L)  delete[] L;

      Optimize();  // get rid of over-allocated fields.

      return Warning;

    }


    void Data::GetDataItem ( io::RFile f, pstr S, pstr & L,
                             pstr & p, int & lcount, int & llen )  {
    PStruct cifStruct;
    char    T[100];
    int     RC,i;

      i = 0;
      while ((*p) && (*p!=' ') && (*p!=char(9)) && (*p!='.'))  {
        if (i<(int)sizeof(T)-1)  T[i++] = *p;
        p++;
      }
      T[i] = char(0);

      if (*p!='.')  {    // category name missing
        strcpy ( L,T );  // item name
        T[0] = char(1);  // special
        T[1] = char(0);  //   category name
      }

      //  look for category
      i = AddCategory ( T );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifStruct = new Struct ( T );
        Category[nCategories-1] = cifStruct;
      } else  {
        cifStruct = PStruct(Category[i]);
        if (cifStruct->GetCategoryID()!=MMCIF_Struct)  {
          strcpy ( _err_string,S );
          _err_line = lcount;
          Warning |= CIFW_NotAStructure;
          if (flags & CIFFL_PrintWarnings)
            printf ( "\n **** mmCIF READ WARNING "
                     "<<line %i: %s was a loop -- replaced>>\n%s\n",
                     lcount,T,S );
          delete Category[i];
          cifStruct = new Struct ( T );
          Category[i] = cifStruct;
        }
      }

      if (*p=='.')  {  // get item name
        i = 0;
        p++;  // skip period
        while ((*p) && (*p!=' ') && (*p!=char(9)))  {
          T[i++] = *p;
          p++;
        }
        T[i] = char(0);
      } else
        strcpy ( T,L );

      if (nWrongFields>0)  {
        if (CheckWrongField(cifStruct->name,T))  {
          GetField ( f,S,L,p,lcount,llen );
          cifStruct->DeleteField ( T );
          return;
        }
      }

      RC = GetField ( f,S,L,p,lcount,llen );

      if (RC)  {
        strcpy ( _err_string,S );
        _err_line = lcount;
        Warning |= CIFW_MissingField;
        if (flags & CIFFL_PrintWarnings)
          printf ( "\n **** mmCIF READ WARNING "
                   "<<line %i: expected data field missing>>\n%s\n",
                   lcount,S );
      }

      while ((*p==' ') || (*p==char(9)))  p++;
      if (*p=='#')  *p = char(0);

      i = cifStruct->GetTagNo ( T );
      if (i>=0)  {
        if (flags & CIFFL_SuggestTags)  {
          tagNo++;
          ParamStr ( T,pstr("\1"),tagNo );
        } else  {
          strcpy ( _err_string,S );
          _err_line = lcount;
          Warning |= CIFW_DuplicateTag;
          if (flags & CIFFL_PrintWarnings)
            printf ( "\n **** mmCIF READ WARNING "
                     "<<line %i: duplicated tag>>\n%s\n",lcount,S );
        }
      }
      cifStruct->AddField ( L,T );

    }

    void Data::GetLoop ( io::RFile f, pstr S, pstr & L,
                         pstr & p, int & lcount, int & llen )  {
    PLoop cifLoop;
    pstr  p1;
    char  T[100];
    bool  Repeat,WrongField;
    int   RC,i,nC;

      RC = 0;

      p += 5;  // skip 'loop_' tag

      loopNo++;
      cifLoop = NULL;
      nC      = -1; // undefined category number
      do {

        while ((*p==' ') || (*p==char(9)))  p++;
        p1 = p;

        if (*p=='_')  {

          // get category name
          i = 0;
          while ((*p) && (*p!=' ') && (*p!=char(9)) && (*p!='.'))  {
            if (i<(int)sizeof(T)-1)  T[i++] = *p;
            p++;
          }
          T[i] = char(0);

          if (*p!='.')  {    // category name missing
            strcpy ( L,T );  // item name
            if (flags & CIFFL_SuggestCategories)
                 sprintf ( T,"X%i",loopNo );
            else strcpy  ( T,"X" );
            T[0] = char(1);  // special category name
          }

          if (cifLoop)  {
            if (strcmp(cifLoop->GetCategoryName(),T))  {
              // loop ended, empty
              p    = p1;   // play back to last category
              cifLoop = NULL;
            }
          } else  {
            //  look for category
            i = AddCategory ( T );
            if ((i!=nC) && (nC>=0))  {  // empty loop; most probably
                                        // a corrupted file
              p = p1;   // play back to last category
              strcpy ( _err_string,S );
              _err_line = lcount;
              Warning |= CIFW_EmptyLoop;
              if (flags & CIFFL_PrintWarnings)
                printf ( "\n **** mmCIF READ WARNING "
                         "<<line %i: empty loop>>\n%s\n",lcount,S );
              // AddCategory(..) has added a NULL-Category on the top of
              // category list; remove it now
              DeleteCategory ( nCategories-1 );
              cifLoop = NULL;
    //          return;
            }
            if (i<0)  {
              // negative value means that the category was not in the list,
              // but a place for it has been provided and index updated
              cifLoop = new Loop ( T );
              Category[nCategories-1] = cifLoop;
              nC = nCategories-1;
            }
          }
    /*
     else if (Loop)  {
            if (!strcmp(Loop->GetCategoryName(),
                        Category[i]->GetCategoryName()))  {
              if (Loop->GetCategoryID()!=MMCIF_Loop)  {
                Warning |= CIFW_NotALoop;
                if (flags & CIFFL_PrintWarnings)
                  printf ( "\n **** mmCIF READ WARNING "
                           "<<line %i: %s was a structure --"
                           " replaced>>\n%s\n",lcount,T,S );
                delete Category[i];
                Loop = new Loop ( T );
                Category[i] = Loop;
              }
            } else
              Loop = NULL;
          }
    */
          if (cifLoop)  {

            if (*p=='.')  {  // get item name
              i = 0;
              p++;  // skip period
              while ((*p) && (*p!=' ') && (*p!=char(9)))  {
                T[i++] = *p;
                p++;
              }
              T[i] = char(0);
            } else
              strcpy ( T,L );

            if (nWrongFields>0)
                  WrongField = CheckWrongField ( cifLoop->name,T );
            else  WrongField = false;

            if (!WrongField)  {
              if (cifLoop->AddTag(T)>=0)  {
                if (flags & CIFFL_SuggestTags)  {
                  tagNo++;
                  ParamStr ( T,pstr("\1"),tagNo );
                  cifLoop->AddTag(T);
                } else  {
                  strcpy ( _err_string,S );
                  _err_line = lcount;
                  Warning |= CIFW_DuplicateTag;
                  if (flags & CIFFL_PrintWarnings)
                    printf ( "\n **** mmCIF READ WARNING "
                             "<<line %i: duplicate tag>>\n%s\n",lcount,S );
                }
              }
            }
            Repeat = true;

          } else  {

            p = p1;
            Repeat = false;

          }

        } else if (!(*p) || (*p=='#'))  {
          Repeat = !f.FileEnd();
          if (Repeat)  {
            f.ReadLine ( S,_max_buf_len );
            lcount++;
            p = &(S[0]);
          } else  {
            strcpy ( _err_string,S );
            _err_line = lcount;
            Warning |= CIFW_UnexpectedEOF;
            if (flags & CIFFL_PrintWarnings)
              printf ( "\n **** mmCIF READ WARNING "
                       "<<line %i: unexpected end of file>>\n%s\n",
                       lcount,S );
          }
        } else
          Repeat = false;

      } while (Repeat);

      if (cifLoop)  {
        do  {
          while ((*p==' ') || (*p==char(9)))  p++;
          if (!(*p) || (*p=='#'))  {
            Repeat = !f.FileEnd();
            if (Repeat)  {
              f.ReadLine ( S,_max_buf_len );
              lcount++;
              p = &(S[0]);
            }
          } else if (*p=='_')  Repeat = false;
          else if (!strncmp(p,"loop_",5))  Repeat = false;
          else if (!strncmp(p,"data_",5))  Repeat = false;
          else if (!strncmp(p,"stop_",5))  {
            p += 5;
            Repeat = false;
          } else  {
            RC = GetField ( f,S,L,p,lcount,llen );
            if (!RC)  {
              cifLoop->AddString ( L );
              Repeat = true;
            } else
              Repeat = false;
          }
        } while (Repeat);
        if ((cifLoop->iColumn!=0) || (RC))  {
          strcpy ( _err_string,S );
          _err_line = lcount;
          Warning |= CIFW_LoopFieldMissing;
          if (flags & CIFFL_PrintWarnings)
            printf ( "\n **** mmCIF READ WARNING "
                     "<<line %i: expected loop field missing>>\n%s\n",
                     lcount,S );
        }
      }

    }

    int  Data::GetField ( io::RFile f, pstr S, pstr & L,
                          pstr & p, int & lcount, int & llen )  {
    bool Repeat;
    pstr L1;
    int  i,flen;
    char c;

      flen    = 0;
      L[flen] = char(0);

      do {

        // skip all spaces before the field
        while ((*p==' ') || (*p==char(9)))  p++;

        if ((*p=='#') || (!(*p)))  {
          // comment or end of line met;  the field should be
          // found on the next line
          Repeat = !f.FileEnd();
          if (Repeat)  {
            // take the next line
            f.ReadLine ( S,_max_buf_len );
            lcount++;
            p = &(S[0]);
            Repeat = (*p!=';');
          } else  {
            // end of file and the field is not taken
            L[0] = char(0);
            return 1;
          }
        } else
          // first symbol of a field is found
          Repeat = false;

      } while (Repeat);


      if (*p==';')  {      // this is a multiline field
        p++;
        strcpy ( L,p );    // take first line of the field
        flen = strlen(L);
        while (!f.FileEnd())  {
          f.ReadLine ( S,_max_buf_len );
          lcount++;
          p = &(S[0]);
          if (*p==';')  {  // multiline field terminated
            p++;
            while ((*p==' ') || (*p==char(9)))  p++;
            return 0;
          } else  {        // multiline field continues -- take next line
            flen += strlen(S)+2;
            if (flen>=llen)  {
              llen = flen + IMin(2000,llen);
              L1   = new char[llen];
              strcpy ( L1,L );
              delete[] L;
              L = L1;
            }
            strcat ( L,"\n" );
            strcat ( L,S );
          }
        }

        // end of file -- take the last line of the multiline field
        p = &(S[strlen(S)]);

      } else  {

        i = 0;
        if (*p!='_')  {
          if ((*p=='\'') || (*p=='"'))  {
            c = *p;
            // field in quotation marks
            do  {
              p++;
              // stop taking characters either on end of line
              // or the quotation mark
              while ((*p) && (*p!=c))  {
                L[i++] = *p;
                p++;
              }
              while (*p==c)  {
                // it was a quotation mark -- check that it is followed
                // by end of line or space
                p++;
                if ((*p) && (*p!=' ') && (*p!=char(9)))  {
                  // the quotation mark is not a field terminator and
                  // belongs to the field.
                  L[i++] = c;    // take the quotation mark
                  if (*p!=c)     // take the non-space character
                    L[i++] = *p; // but check for field terminator
                }
              }
              // terminate the loop only on space or end of line
            } while ((*p) && (*p!=' ') && (*p!=char(9)));
            if (*p)  p++;
            L[i] = char(0);
          } else  {
            // a simplest field without spaces
            while ((*p) && (*p!=' ') && (*p!=char(9)))  {
              L[i++] = *p;
              p++;
            }
            L[i] = char(0);
            if (((L[0]=='.') || (L[0]=='?')) && (!L[1]))  {
              //  "no data" tokens
              L[1] = L[0];
              L[0] = char(2);
              L[2] = char(0);
            }
          }
        }

      }

      return 0;

    }

    void  Data::Sort()  {
    int      i,k;
    psvector cnames;

      k = 0;
      for (i=0;i<nCategories;i++)
        if (Category[i])  {
          if (k<i)  Category[k] = Category[i];
          k++;
        }
      for (i=k;i<nCategories;i++)
        Category[i] = NULL;
      nCategories = k;

      FreeVectorMemory ( index ,0 );
      GetVectorMemory  ( cnames,nCategories,0 );
      GetVectorMemory  ( index ,nCategories,0 );

      for (i=0;i<nCategories;i++)  {
        Category[i]->Sort();
        cnames[i] = NULL;
        CreateCopy ( cnames[i],Category[i]->name );
      }

      SortTags ( cnames,nCategories,index );

      for (i=0;i<nCategories;i++)
        if (cnames[i])  delete[] cnames[i];

      if (cnames) delete[] cnames;

    }

    int  Data::GetCategoryNo ( cpstr cname )  {
    //   Binary search for index of category cname in Category[].
    // Return:
    //    >=0 : position of the category found
    //     <0 : the category was not found, it could be inserted before
    //          (-RC-1)th element, where RC is the return value
    int l1,l2,l,k;

      if ((!Category) || (nCategories<1)) return -1;

      if (!index)    Sort();

      if (cname[0])  {
        l  = 0;
        l1 = 0;
        l2 = nCategories-1;
        k  = 1;
        while (l1<l2-1)  {
          l = (l1+l2)/2;
          k = strcasecmp ( cname,Category[index[l]]->name );
          if (k<0)      l2 = l;
          else if (k>0) l1 = l;
          else  {
            l1 = l;
            break;
          }
        }
        if (k==0)  return index[l];    // is at RCth position
        k = strcasecmp(cname,Category[index[l1]]->name);
        if (k==0)  return index[l1];   // is at RCth position
        if (k<0)   return -1;          // would be at (-RC-1)th position
        if (l2!=l1)  {
          k = strcasecmp(cname,Category[index[l2]]->name);
          if (k==0)  return index[l2]; // is at RCth position
          if (k>0)   return -2-l2;   // would be at l2+1=(-RC-1)th position
        }
        return -2-l1;                // would be at l1+1=(-RC-1)th position
      } else
        // 'root' category should be always on top
        if (Category[index[0]]->name[0]==char(1))  return index[0];

      return -1;

    }

    int  Data::AddCategory ( cpstr cname )  {
    //  return -1: a place for category has been added on the top of array;
    //             index is added and sorted automatically
    //        >=0: the category is already in the array -- its position
    //             is returned
    int              l1,l;
    PPCategory Category1;
    ivector          index1;


      if (!Category)  {
        Category     = new PCategory[1];
        Category[0]  = NULL;
        GetVectorMemory ( index,1,0 );
        index[0]     = 0;
        nCategories  = 1;
        return -nCategories;  // the category has been added on the top of array
      }
      l1 = GetCategoryNo ( cname );
      if (l1>=0)  return l1;  // non-negative returns mean that
                              // the category is already in the array
      l1 = -l1-1;  // otherwise the category has to be added and indexed at here
      // put new NULL-category on the top of array and update the index
      Category1 = new PCategory[nCategories+1];
      GetVectorMemory ( index1,nCategories+1,0 );
      for (l=0;l<nCategories;l++)
        Category1[l] = Category[l];
      Category1[nCategories] = NULL;
      for (l=0;l<l1;l++)
        index1[l] = index[l];
      index1[l1] = nCategories;
      for (l=l1+1;l<=nCategories;l++)
        index1[l] = index[l-1];
      delete[] Category;
      FreeVectorMemory ( index,0 );
      Category = Category1;
      index    = index1;
      nCategories++;
      return -nCategories; // the category has been added on
                           // the top of array
    }

    bool Data::WriteMMCIFData ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File f;
      f.assign ( FName,true,false,gzipMode );
      if (f.rewrite())  {
        WriteMMCIF ( f );
        f.shut();
        return true;
      } else
        return false;
    }

    void Data::WriteMMCIF ( io::RFile f )  {
    int  i;

      if (name)  {
        f.Write     ( pstr("\ndata_") );
        f.WriteLine ( name            );
      } else
        f.WriteLine ( pstr("\ndata_") );

      for (i=0;i<nCategories;i++)
        if (Category[i])
          Category[i]->WriteMMCIF ( f );

    }


    // ---------------  Retrieving data

    int  Data::DeleteCategory ( cpstr CName )  {
    int k;
      k = GetCategoryNo ( CName );
      if (k<0)  return CIFRC_NoCategory;
      return DeleteCategory ( k );
    }

    int  Data::DeleteCategory ( int CatNo ) {
    int i;
      if (Category[CatNo])  delete Category[CatNo];
      for (i=CatNo+1;i<nCategories;i++)
        Category[i-1] = Category[i];
      i = 0;
      while ((i<nCategories) && (index[i]!=CatNo))  {
        if (index[i]>CatNo) index[i]--;
        i++;
      }
      i++;
      while (i<nCategories)  {
        if (index[i]>CatNo) index[i]--;
        index[i-1] = index[i];
        i++;
      }
      nCategories--;
      index   [nCategories] = 0;
      Category[nCategories] = NULL;
      return 0;
    }

    int  Data::DeleteStructure ( cpstr CName )  {
    int k;
      k = GetCategoryNo ( CName );
      if (k<0)  return CIFRC_NoCategory;
      if (Category[k]->GetCategoryID()==MMCIF_Struct)
            return DeleteCategory ( k );
      else  return CIFRC_NotAStructure;
    }

    int  Data::DeleteLoop ( cpstr CName )  {
    int k;
      k = GetCategoryNo ( CName );
      if (k<0)  return CIFRC_NoCategory;
      if (Category[k]->GetCategoryID()==MMCIF_Loop)
            return DeleteCategory ( k );
      else  return CIFRC_NotALoop;
    }

    PCategory Data::GetCategory ( int categoryNo )  {
      if ((categoryNo>=0) && (categoryNo<nCategories))
        return Category[categoryNo];
      return NULL;
    }

    PStruct Data::GetStructure ( cpstr CName )  {
    int i;
      i = GetCategoryNo ( CName );
      if (i<0)  return NULL;
      if (Category[i]->GetCategoryID()==MMCIF_Struct)
            return PStruct(Category[i]);
      else  return NULL;
    }

    PLoop Data::GetLoop ( cpstr CName )  {
    int i;
      i = GetCategoryNo ( CName );
      if (i<0)  return NULL;
      if (Category[i]->GetCategoryID()==MMCIF_Loop)
            return PLoop(Category[i]);
      else  return NULL;
    }

    PLoop Data::FindLoop ( cpstr * tagList )  {
    int i;
      for (i=0;i<nCategories;i++)
        if (Category[i])  {
          if (Category[i]->GetCategoryID()==MMCIF_Loop)  {
            if (Category[i]->CheckTags(tagList))
              return PLoop(Category[i]);
          }
        }
      return NULL;
    }

    void Data::GetDataName ( pstr & dname, bool Remove )  {
      if (Remove)  {
        if (dname)  delete[] dname;
        dname = name;
        name  = NULL;
      } else
        CreateCopy ( dname,name );
    }

    int  Data::CheckData ( cpstr CName, cpstr TName )  {
    //   CheckData(..) returns positive value if the field is in the
    // file:
    //   CIFRC_Structure  category CName is a structure
    //   CIFRC_Loop       category CName is a loop
    // Negative returns mean:
    //   CIFRC_StructureNoTag  category CName is present,
    //                        it is a structure, but it does not
    //                        have tag TName
    //   CIFRC_LoopNoTag       category CName is present,
    //                        it is a loop, but it does not have
    //                        tag TName
    //   CIFRC_NoCategory      category CName is not present.
    // If TName is set to NULL then only the CName is checked and
    // possible returns are CIFRC_Structure, CIFRC_Loop and
    // CIFRC_NoCategory.
    int i,k;
      i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()==MMCIF_Struct)
            k = CIFRC_Structure;
      else  k = CIFRC_Loop;
      if (TName)  {
        if (Category[i]->GetTagNo(TName)<0)  {
          if (k==CIFRC_Structure)
                k = CIFRC_StructureNoTag;
          else  k = CIFRC_LoopNoTag;
        }
      }
      return k;
    }

    void Data::Optimize()  {
    int              i,k;
    PPCategory C1;
      k = 0;
      for (i=0;i<nCategories;i++)
        if (Category[i])  {
          Category[i]->Optimize();
          if (Category[i]->nTags<=0)  {
            delete Category[i];
            Category[i] = NULL;
          } else
            k++;
        }
      if (k>0)  {
        if (k!=nCategories)  {
          C1 = new PCategory[k];
          k  = 0;
          for (i=0;i<nCategories;i++)
            if (Category[i])
              C1[k++] = Category[i];
          if (Category) delete[] Category;
          Category    = C1;
          nCategories = k;
          FreeVectorMemory ( index,0 );
          Sort();
        }
      } else  {
        if (Category)  delete[] Category;
        Category    = NULL;
        nCategories = 0;
      }
    }

    int  Data::GetString  ( pstr & Dest, cpstr CName,
                                  cpstr TName, bool Remove )  {
    //   GetString(..), GetReal(..) and GetInteger(..) return 0 if the
    // requested field was found and successfully converted. Negative
    // returns mean:
    //    CIFRC_WrongFormat    the field was found but failed to convert
    //                        due to improper numeric format
    //    CIFRC_NoTag          category CName was found, but it does not
    //                        have tag TName
    //    CIFRC_NoCategory     category CName was not found
    //    CIFRC_NotAStructure  category CName was found, but it is a loop
    //                        rather than a structure.
    //   GetString(..) will try to dispose Dest unless it is assugned
    // NULL value before the call. The string will be then dynamically
    // allocated and copied.
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Struct)
                return CIFRC_NotAStructure;
      return PStruct(Category[i])->GetString ( Dest,TName,Remove );
    }

    pstr Data::GetString ( cpstr CName, cpstr TName, int & RC )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  {
        RC = CIFRC_NoCategory;
        return NULL;
      }
      if (Category[i]->GetCategoryID()!=MMCIF_Struct)  {
        RC = CIFRC_NotAStructure;
        return NULL;
      }
      return PStruct(Category[i])->GetString ( TName,RC );
    }

    int  Data::DeleteField ( cpstr CName, cpstr TName )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Struct)
                return CIFRC_NotAStructure;
      return PStruct(Category[i])->DeleteField ( TName );
    }

    int  Data::GetReal ( realtype & R, cpstr CName,
                         cpstr TName, bool Remove )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Struct)
                return CIFRC_NotAStructure;
      return PStruct(Category[i])->GetReal ( R,TName,Remove );
    }

    int  Data::GetInteger ( int & I, cpstr CName,
                                  cpstr TName, bool Remove )  {
    int j = GetCategoryNo ( CName );
      if (j<0)  return CIFRC_NoCategory;
      if (Category[j]->GetCategoryID()!=MMCIF_Struct)
                return CIFRC_NotAStructure;
      return PStruct(Category[j])->GetInteger ( I,TName,Remove );
    }

    int  Data::GetLoopLength ( cpstr CName )  {
    //   GetLoopLength(..) returns CIFRC_NotALoop if the category CName
    // is not a loop, CIFRC_NoCategory if the category CName is not
    // found. Non-negative returns give the length of the loop (may be
    // 0 if the loop is empty).
    int i;
      i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                return CIFRC_NotALoop;
      return PLoop(Category[i])->nRows;
    }

    int  Data::GetLoopString  ( pstr & Dest, cpstr CName,
                                      cpstr TName, int nrow,
                                      bool Remove )  {
    //   GetLoopString(..), GetLoopReal(..) and GetLoopInteger(..) act
    // like GetString(..), GetReal(..) and GetInteger(..) above for
    // nrow-th element of the 'loop_' (indexed like 0..N-1 where N
    // is obtained through GetLoopLength(..)). They will return
    // CIFRC_WrongIndex if nrow is out of range.
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                return CIFRC_NotALoop;
      return PLoop(Category[i])->GetString ( Dest,TName,nrow,Remove );
    }

    pstr Data::GetLoopString  ( cpstr CName, cpstr TName,
                                      int nrow, int & RC )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  {
        RC = CIFRC_NoCategory;
        return NULL;
      }
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)  {
        RC = CIFRC_NotALoop;
        return NULL;
      }
      return  PLoop(Category[i])->GetString ( TName,nrow,RC );
    }

    int Data::DeleteLoopField ( cpstr CName, cpstr TName,
                                      int nrow )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                return CIFRC_NotALoop;
      return PLoop(Category[i])->DeleteField ( TName,nrow );
    }

    int  Data::GetLoopReal ( realtype & R, cpstr CName,
                                   cpstr TName, int nrow,
                                   bool Remove )  {
    int i = GetCategoryNo ( CName );
      if (i<0)  return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                return CIFRC_NotALoop;
      return PLoop(Category[i])->GetReal ( R,TName,nrow,Remove );
    }

    int  Data::GetLoopInteger ( int & I, cpstr CName,
                                      cpstr TName, int nrow,
                                      bool Remove )  {
    int j = GetCategoryNo ( CName );
      if (j<0)  return CIFRC_NoCategory;
      if (Category[j]->GetCategoryID()!=MMCIF_Loop)
                return CIFRC_NotALoop;
      return PLoop(Category[j])->GetInteger ( I,TName,nrow,Remove );
    }


    int  Data::GetLoopSVector ( psvector & S, cpstr CName,
                                      cpstr TName, int i1, int i2,
                                      bool Remove )  {
    //   GetLoopSVector(..), GetLoopRVector(..) and GetLoopIVector(..)
    // read CIF 'loop_' data into allocated vectors of strings, reals and
    // integers, correspondingly. The vectors may be deallocated prior
    // to call and assigned NULL, in which case they will be allocated
    // with offsets of i1, which is also the lower index of the 'loop_'
    // data transferred into it. The upper vector index is given by i2 or
    // by the loop's length whichever is less. If vectors are not assigned
    // NULL prior the call, it is assumed that they are properly (i1-offset,
    // i2-i1+1 length) allocated.
    //   The return codes are same as those of GetLoopString(..),
    // GetLoopReal(..) and GetLoopInteger(..).
    int i;
      i = GetCategoryNo ( CName );
      if (i<0)    return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                  return CIFRC_NotALoop;
      return PLoop(Category[i])->GetSVector ( S,TName,i1,i2,Remove );
    }

    int  Data::GetLoopRVector ( rvector & R, cpstr CName,
                                      cpstr TName, int i1, int i2,
                                      bool Remove )  {
    int i;
      i = GetCategoryNo ( CName );
      if (i<0)    return CIFRC_NoCategory;
      if (Category[i]->GetCategoryID()!=MMCIF_Loop)
                  return CIFRC_NotALoop;
      return PLoop(Category[i])->GetRVector ( R,TName,i1,i2,Remove );
    }

    int  Data::GetLoopIVector ( ivector & I, cpstr CName,
                                      cpstr TName, int i1, int i2,
                                      bool Remove )  {
    int j;
      j = GetCategoryNo ( CName );
      if (j<0)    return CIFRC_NoCategory;
      if (Category[j]->GetCategoryID()!=MMCIF_Loop)
                  return CIFRC_NotALoop;
      return PLoop(Category[j])->GetIVector ( I,TName,i1,i2,Remove );
    }


    // ---------------  Storing data

    void  Data::PutDataName ( cpstr dname )  {
    // stores name for 'data_' record
      CreateCopy ( name,dname );
    }

    int  Data::PutNoData ( int NoDataType, cpstr CName, cpstr TName )  {
    PStruct cifStruct;
    int     i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifStruct = new Struct ( CName );
        Category[nCategories-1] = cifStruct;
      } else  {
        cifStruct = PStruct(Category[i]);
        if (cifStruct->GetCategoryID()!=MMCIF_Struct)  {
          RC = CIFRC_NotAStructure;
          delete Category[i];
          cifStruct = new Struct ( CName );
          Category[i] = cifStruct;
        }
      }

      cifStruct->PutNoData ( NoDataType,TName );

      return RC;

    }

    int  Data::PutString ( cpstr S, cpstr CName,
                           cpstr TName, bool Concatenate )  {
    //   PutString(..), PutReal(..) and PutInteger(..) will put the
    // values given into the specified category (CName) under the
    // specified tag (TName). The category, tag and field are created
    // automatically; the field will be replaced silently if identical
    // CName.TName is specified in two calls. Calls of these functions
    // may follow in random order; however CIF file will have all tags
    // grouped by categories and catgories will follow in the order
    // of first appearance in PutString(..), PutReal(..) or
    // PutInteger(..).
    //   Return code - one of CIFRC_Ok or CIFRC_NotAStruct
    PStruct cifStruct;
    int     i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifStruct = new Struct ( CName );
        Category[nCategories-1] = cifStruct;
      } else  {
        cifStruct = PStruct(Category[i]);
        if (cifStruct->GetCategoryID()!=MMCIF_Struct)  {
          RC = CIFRC_NotAStructure;
          delete Category[i];
          cifStruct = new Struct ( CName );
          Category[i] = cifStruct;
        }
      }

      cifStruct->AddField ( S,TName,Concatenate );

      return RC;

    }

    int   Data::PutDate ( cpstr CName, cpstr TName )  {
    PStruct cifStruct;
    int     i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifStruct = new Struct ( CName );
        Category[nCategories-1] = cifStruct;
      } else  {
        cifStruct = PStruct(Category[i]);
        if (cifStruct->GetCategoryID()!=MMCIF_Struct)  {
          RC = CIFRC_NotAStructure;
          delete Category[i];
          cifStruct = new Struct ( CName );
          Category[i] = cifStruct;
        }
      }

      cifStruct->PutDate ( TName );

      return RC;

    }

    int  Data::PutReal ( realtype R, cpstr CName,
                         cpstr TName, int prec )  {
    char rS[100];
      sprintf ( rS,"%.*g",prec,R );
      return PutString ( rS,CName,TName,false );
    }

    int  Data::PutInteger ( int I, cpstr CName,
                                         cpstr TName )  {
    char iS[100];
      if (I>MinInt4)  sprintf ( iS,"%i",I );
      else  {
        iS[0] = char(2);
        iS[1] = '.';
        iS[2] = char(0);
      }
      return PutString ( iS,CName,TName,false );
    }


    int  Data::AddLoop ( cpstr CName, PLoop & cifLoop )  {
    int  i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
        RC = CIFRC_Created;
      } else  {
        cifLoop = PLoop(Category[i]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[i];
          cifLoop = new Loop ( CName );
          Category[i] = cifLoop;
        }
      }

      return RC;

    }

    int  Data::AddStructure ( cpstr CName, PStruct & cifStruct )  {
    int  i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifStruct = new Struct ( CName );
        Category[nCategories-1] = cifStruct;
        RC = CIFRC_Created;
      } else  {
        cifStruct = PStruct(Category[i]);
        if (cifStruct->GetCategoryID()!=MMCIF_Struct)  {
          RC = CIFRC_NotAStructure;
          delete Category[i];
          cifStruct = new Struct ( CName );
          Category[i] = cifStruct;
        }
      }

      return RC;

    }


    int  Data::PutLoopNoData ( int NoDataType, cpstr CName,
                                     cpstr TName, int nrow )  {
    PLoop cifLoop;
    int   i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
      } else  {
        cifLoop = PLoop(Category[i]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[i];
          cifLoop = new Loop ( CName );
          Category[i] = cifLoop;
        }
      }

      cifLoop->PutNoData ( NoDataType,TName,nrow );

      return RC;

    }


    int  Data::PutLoopString ( cpstr S, cpstr CName,
                                     cpstr TName, int nrow )  {
    //   PutLoopString(..), PutLoopReal(..) and PutLoopInteger(..) act
    // like PutString(..), PutReal(..) and PutInteger(..) above for
    // nrow-th element of the 'loop_' CName (indexed begining from 0).
    // In consequitive calls, given values of nrow does not have to be
    // ordered; the most efficient way is to start with HIGHEST value
    // for nrow in the loop and move down to 0. The least efficient way
    // is to start with nrow=0 and move up.
    PLoop cifLoop;
    int   i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
      } else  {
        cifLoop = PLoop(Category[i]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[i];
          cifLoop = new Loop ( CName );
          Category[i] = cifLoop;
        }
      }

      cifLoop->PutString ( S,TName,nrow );

      return RC;

    }

    int  Data::PutLoopReal ( realtype R, cpstr CName,
                                   cpstr TName, int nrow, int prec )  {
    char rS[100];
      sprintf ( rS,"%.*g",prec,R );
      return PutLoopString ( rS,CName,TName,nrow );
    }

    int  Data::PutLoopInteger ( int I, cpstr CName,
                                      cpstr TName, int nrow )  {
    char iS[100];
      sprintf ( iS,"%i",I );
      return PutLoopString ( iS,CName,TName,nrow );
    }


    int  Data::PutLoopSVector ( psvector S, cpstr CName,
                                      cpstr TName, int i1, int i2 )  {
    //   PutLoopSVector(..), PutLoopRVector(..) and PutLoopIVector(..)
    // put vectors of values into specified loop fields. Parameters i1
    // and i2 give the range of indices of values which are to be
    // transfered. To transfer an entire vector allocated as [0..N-1]
    // i1 shoudl be set to 0 and i2 - to N-1. Note that the loop is
    // always indexed as starting form 0 on, therefore negative i1 and
    // i2 are not allowed, and specifying i1>0 will leave first i1
    // elements of the CIF loop for the corresponding tag undefined
    // (will be output like '?').
    PLoop cifLoop;
    int   i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
      } else  {
        cifLoop = PLoop(Category[i]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[i];
          cifLoop = new Loop ( CName );
          Category[i] = cifLoop;
        }
      }

      cifLoop->PutSVector ( S,TName,i1,i2 );

      return RC;

    }

    int  Data::PutLoopRVector ( rvector R, cpstr CName,
                                      cpstr TName,
                                      int i1, int i2, int prec )  {
    PLoop cifLoop;
    int   i,RC;

      RC = CIFRC_Ok;

      //  look for category
      i = AddCategory ( CName );
      if (i<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
      } else  {
        cifLoop = PLoop(Category[i]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[i];
          cifLoop = new Loop ( CName );
          Category[i] = cifLoop;
        }
      }

      cifLoop->PutRVector ( R,TName,i1,i2,prec );

      return RC;

    }

    int  Data::PutLoopIVector ( ivector I, cpstr CName,
                                      cpstr TName,
                                      int i1, int i2 )  {
    PLoop cifLoop;
    int   j,RC;

      RC = CIFRC_Ok;

      //  look for category
      j = AddCategory ( CName );
      if (j<0)  {
        // negative value means that the category was not in the list,
        // but a place for it has been provided and index updated
        cifLoop = new Loop ( CName );
        Category[nCategories-1] = cifLoop;
      } else  {
        cifLoop = PLoop(Category[j]);
        if (cifLoop->GetCategoryID()!=MMCIF_Loop)  {
          RC = CIFRC_NotALoop;
          delete Category[j];
          cifLoop = new Loop ( CName );
          Category[j] = cifLoop;
        }
      }

      cifLoop->PutIVector ( I,TName,i1,i2 );

      return RC;

    }


    int Data::RenameCategory ( cpstr CName,
                                     cpstr newCName )  {
    int i,RC;
      i = GetCategoryNo ( CName );
      if (i>=0)  {
        Category[i]->PutCategoryName ( newCName );
        Sort();
        RC = CIFRC_Ok;
      } else
        RC = CIFRC_NoCategory;
      return RC;
    }


    void Data::Copy ( PData Data )  {
    int i;
      FreeMemory(0);
      CreateCopy ( name,Data->name );
      nCategories = Data->nCategories;
      if (nCategories>0)  {
        Category = new PCategory[nCategories];
        GetVectorMemory ( index,nCategories,0 );
        for (i=0;i<nCategories;i++)  {
          if (Data->Category[i])  {
            if (Data->Category[i]->GetCategoryID()==MMCIF_Struct)
                  Category[i] = new Struct();
            else  Category[i] = new Loop();
            Category[i]->Copy ( Data->Category[i] );
          } else
            Category[i] = NULL;
          index[i] = Data->index[i];
        }
      }
      flags   = Data->flags;
      Warning = Data->Warning;
    }


    int  Data::CopyCategory ( PData Data, cpstr CName,
                                    cpstr newCName )  {
    PCategory Cat;
    int             i,di,dc,RC;

      di = Data->GetCategoryNo ( CName );

      if (di>=0)  {

        RC = CIFRC_Ok;
        dc = Data->Category[di]->GetCategoryID();

        //  look for category
        i = AddCategory ( CName );
        if (i<0)  {
          // negative value means that the category was not in the list,
          // but a place for it has been provided and index updated
          if (dc==MMCIF_Loop)  Cat = new Loop   ( CName );
                         else  Cat = new Struct ( CName );
          Category[nCategories-1] = Cat;
        } else  {
          Cat = Category[i];
          if (Cat->GetCategoryID()!=dc)  {
            RC = CIFRC_NotAStructure;
            delete Category[i];
            if (dc==MMCIF_Loop)  Cat = new Loop   ( CName );
                           else  Cat = new Struct ( CName );
            Category[i] = Cat;
          }
        }

        Cat->Copy ( Data->Category[di] );
        if (newCName)  {
          Cat->PutCategoryName ( newCName );
          Sort();
        }

      } else
        RC = CIFRC_NoCategory;

      return RC;

    }

    void Data::PrintCategories()  {
    // for debuging only
    int i;
      printf ( " Total %i categories:\n",nCategories );
      for (i=0;i<nCategories;i++)
        if (Category[i])  {
          printf ( " %5i. ",i+1 );
          if (Category[i]->GetCategoryID()==MMCIF_Loop)
                printf ( "Loop      %s\n",Category[i]->name );
          else  printf ( "Structure %s\n",Category[i]->name );
        }
    }


    void Data::write ( io::RFile f )  {
    int i,k;
      if (!index)  Sort();
      f.CreateWrite ( name );
      f.WriteInt    ( &nCategories );
      for (i=0;i<nCategories;i++)  {
        if (Category[i])  {
          k = Category[i]->GetCategoryID();
          f.WriteInt ( &k );
          Category[i]->write ( f );
        } else  {
          k = -1;
          f.WriteInt ( &k );
        }
        f.WriteInt ( &(index[i]) );
      }
      f.WriteInt ( &flags   );
      f.WriteInt ( &Warning );
    }


    void Data::read ( io::RFile f )  {
    int i,k;
      FreeMemory(0);
      f.CreateRead ( name );
      f.ReadInt    ( &nCategories );
      if (nCategories>0)  {
        Category = new PCategory[nCategories];
        GetVectorMemory ( index,nCategories,0 );
        for (i=0;i<nCategories;i++)  {
          f.ReadInt ( &k );
          if (k>=0)  {
            if (k==MMCIF_Struct)  Category[i] = new Struct();
                            else  Category[i] = new Loop();
            Category[i]->read ( f );
          } else
            Category[i] = NULL;
          f.ReadInt ( &(index[i]) );
        }
      }
      f.ReadInt ( &flags   );
      f.ReadInt ( &Warning );
    }


    MakeStreamFunctions(Data)



    //  ======================  File  =============================


    File::File() : io::Stream()  {
      InitFile();
    }

    File::File ( cpstr FName, io::GZ_MODE gzipMode ) : io::Stream()  {
      InitFile ();
      ReadMMCIFFile ( FName,gzipMode );
    }

    File::File ( io::RPStream Object ) : io::Stream(Object)  {
      InitFile();
    }

    File::~File()  {
      FreeMemory();
    }

    void File::InitFile()  {
      nData         = 0;
      nAllocData    = 0;
      data          = NULL;
      index         = NULL;
      PrintWarnings = false;
      StopOnWarning = false;
    }

    void File::FreeMemory()  {
    int i;
      for (i=0;i<nData;i++)
        if (data[i])  delete data[i];
      if (data)  delete[] data;
      data       = NULL;
      FreeVectorMemory ( index,0 );
      nData      = 0;
      nAllocData = 0;
    }


    pstr GetMMCIFInputBuffer ( int & LineNo )  {
      LineNo = _err_line;
      _err_string[sizeof(_err_string)-1] = char(0);
      return _err_string;
    }

    int  File::ReadMMCIFFile ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File  f;
    PData     CIF;
    char      S[500];
    int       RC,lcount;

      FreeMemory();

      CIF = NULL;
      f.assign ( FName,true,false,gzipMode );
      if (f.reset(true))  {
        S[0]   = char(0);
        lcount = 0;
        RC     = 0;
        while ((!RC) && (!f.FileEnd()))  {
          if (!CIF)  CIF = new Data();
          CIF->SetPrintWarnings ( PrintWarnings );
          CIF->SetStopOnWarning ( StopOnWarning );
          RC = CIF->ReadMMCIFData ( f,S,lcount );
          if (!RC)  {
            ExpandData ( nData+1 );
            data[nData] = CIF;
            nData++;
            CIF = NULL;
          }
        }
        if (CIF)  delete CIF;
        f.shut();
        if (RC==CIFRC_NoDataLine)  {
          if (nData>0)  RC = 0;
        }
        Sort();
        return RC;
      } else
        return CIFRC_CantOpenFile;

    }

    int File::WriteMMCIFFile ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File f;
      f.assign ( FName,true,false,gzipMode );
      if (f.rewrite())  {
        WriteMMCIF ( f );
        f.shut();
        return 0;
      } else
        return CIFRC_CantOpenFile;
    }

    void File::WriteMMCIF ( io::RFile f )  {
    int i;
      for (i=0;i<nData;i++)
        if (data[i])
          data[i]->WriteMMCIF ( f );
    }


    void File::Sort()  {
    psvector tag;
    int      i;
      if (nData>0)  {
        FreeVectorMemory ( index,0 );
        GetVectorMemory  ( index,nData,0 );
        GetVectorMemory  ( tag  ,nData,0 );
        for (i=0;i<nData;i++)  {
          tag[i] = NULL;
          CreateCopy ( tag[i],data[i]->name );
        }
        SortTags ( tag,nData,index );
        for (i=0;i<nData;i++)
          if (tag[i])  {
            delete[] tag[i];
            tag[i] = NULL;
          }
        FreeVectorMemory ( tag,0 );
      }
    }

    int  File::GetCIFDataNo ( cpstr DName )  {
    //   Binary search for index of DName ttag in data[].
    // Return:
    //    >=0 : position of the DName found
    //     <0 : the DName was not found, it could be inserted before
    //          (-RC-1)th element, where RC is the return value
    int l1,l2,l,k;

      if (!data)   return -1;
      if (!index)  Sort();

      l  = 0;
      l1 = 0;
      l2 = nData-1;
      k  = 1;
      while (l1<l2-1)  {
        l = (l1+l2)/2;
        k = strcasecmp ( DName,data[index[l]]->name );
        if (k<0)      l2 = l;
        else if (k>0) l1 = l;
        else  {
          l1 = l;
          break;
        }
      }

      if (k==0)  return index[l];    // is at RCth position
      k = strcasecmp ( DName,data[index[l1]]->name );
      if (k==0)  return index[l1];   // is at RCth position
      if (k<0)   return -1;          // would be at (-RC-1)th position
      if (l2!=l1)  {
        k = strcasecmp ( DName,data[index[l2]]->name );
        if (k==0)  return index[l2]; // is at RCth position
        if (k>0)   return -2-l2;     // would be at l2+1=(-RC-1)th position
      }

      return -2-l1;                  // would be at l1+1=(-RC-1)th position

    }

    PData  File::GetCIFData ( int dataNo )  {
      if ((dataNo>=0) && (dataNo<nData))  return data[dataNo];
                                    else  return NULL;
    }

    PData  File::GetCIFData ( cpstr DName )  {
    int l;
      l = GetCIFDataNo ( DName );
      if (l>=0)  return data[l];
           else  return NULL;
    }

    void File::ExpandData ( int nDataNew )  {
    int          i,nAD;
    PPData data1;
    ivector      index1;
      if (nDataNew>nAllocData)  {
        nAD   = nDataNew + IMin(nAllocData/2+1,100);
        data1 = new PData[nAD];
        GetVectorMemory ( index1,nAD,0 );
        for (i=0;i<nAllocData;i++)  {
          data1 [i] = data [i];
          index1[i] = index[i];
        }
        for (i=nAllocData;i<nAD;i++)  {
          data1 [i] = NULL;
          index1[i] = i;
        }
        if (data)  delete[] data;
        FreeVectorMemory ( index,0 );
        data       = data1;
        index      = index1;
        nAllocData = nAD;
      }
    }

    int  File::AddCIFData ( cpstr DName )  {
    //  return -1: the CIF data structure has been added on the
    //             top of data array; the index is added and sorted
    //             automatically
    //        >=0: the CIF data structure is already in the array
    //             -- its position is returned
    int  i1,i;
      if (!data)  {
        ExpandData ( 3 );  // get space for first 3 CIF data structures
        data[0] = new Data ( DName );
        nData   = 1;
        return -nData;     // the CIF data structure has been added
                           // "on the top" of array
      }
      i1 = GetCIFDataNo ( DName );
      if (i1>=0)  return i1;  // non-negative returns mean that the CIF
                              // data structure is already in the array
      i1 = -i1-1;  // otherwise the data has to be added and indexed at here
      // put new CIF data structure on the top of array and update index
      ExpandData ( nData+1 );
      data[nData] = new Data ( DName );
      for (i=nData;i>i1;i--)
        index[i] = index[i-1];
      index[i1] = nData;
      nData++;
      return -nData; // the tag has been added on the top of array
    }


    int File::DeleteCIFData ( cpstr DName )  {
    int dataNo = GetCIFDataNo ( DName );

      if (dataNo>=0)  return DeleteCIFData ( dataNo );
      return dataNo;

    }

    int File::DeleteCIFData ( int dataNo )  {
    int i;

      if ((0<=dataNo) && (dataNo<nData))  {

        if (data[dataNo])  delete data[dataNo];
        for (i=dataNo+1;i<nData;i++)
          data[i-1] = data[i];
        nData--;

        Sort();

        return 0;

      }

      return -nData;

    }

    void File::Copy  ( PFile File )  {
    int i;
      FreeMemory();
      nData      = File->nData;
      nAllocData = nData;
      if (nData>0)  {
        data = new PData[nData];
        for (i=0;i<nData;i++)  {
          if (File->data[i])  {
            data[i] = new Data();
            data[i]->Copy ( File->data[i] );
          } else
            data[i] = NULL;
        }
      }
    }


    void File::write ( io::RFile f )  {
    int i,k;
      f.WriteInt ( &nData );
      for (i=0;i<nData;i++)
        if (data[i])  {
          k = 1;
          f.WriteInt ( &k );
          data[i]->write ( f );
        } else  {
          k = 0;
          f.WriteInt ( &k );
        }
    }

    void File::read  ( io::RFile f )  {
    int i,k;
      FreeMemory();
      f.ReadInt ( &nData );
      nAllocData = nData;
      if (nData>0)  {
        data = new PData[nData];
        for (i=0;i<nData;i++)  {
          f.ReadInt ( &k );
          if (k)  {
            data[i] = new Data();
            data[i]->read ( f );
          } else
            data[i] = NULL;
        }
      }
    }


    MakeStreamFunctions(File)


    int  isCIF ( cpstr FName, io::GZ_MODE gzipMode )  {
    io::File f;
    int      rc;

      f.assign ( FName,true,false,gzipMode );
      if (f.reset(true))  {
        rc = isCIF ( f );
        f.shut();
      } else
        rc = -1;

      return rc;

    }

    int  isCIF ( io::RFile f )  {
    char    S[_max_buf_len+1];
    bool Done;
    pstr    p;

      f.ReadLine ( S,_max_buf_len );
      S[_max_buf_len] = char(0);
      Done = false;
      while (!Done)  {
        p = &(S[0]);
        while ((*p==' ') || (*p==char(9)))  p++;
        Done = !strncmp(p,"data_",5);
        if (!Done)  {
          if (f.FileEnd())  {
            Done = true;
            p    = NULL;
          } else  {
            f.ReadLine ( S,_max_buf_len );
            S[_max_buf_len] = char(0);
          }
        }
      }

      if (!p)  return 1;
      if (!strncmp(p,"data_",5))  return 0;
                            else  return 1;

    }


    pstr GetCIFMessage ( pstr M, int RC )  {
    int  LineNo;
    pstr InputLine;

      InputLine = GetMMCIFInputBuffer ( LineNo );

      if (RC>10)  {
        if (RC & CIFW_UnrecognizedItems)
          sprintf ( M,"unrecognized items found on %ith line\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_MissingField)
          sprintf ( M,"expected data field not found; line %i reads\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_EmptyLoop)
          sprintf ( M,"empty loop ('loop_') on %ith line\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_UnexpectedEOF)
          sprintf ( M,"unexpected end of file; line %i reads\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_LoopFieldMissing)
          sprintf ( M,"expected data field in a loop not found; "
                      "line %i reads\n%s", LineNo,InputLine );
        else if (RC & CIFW_LoopFieldMissing)
          sprintf ( M,"expected data field in a loop not found; "
                      "line %i reads\n%s", LineNo,InputLine );
        else if (RC & CIFW_NotAStructure)
          sprintf ( M,"a loop is used as a structure on line %i\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_NotALoop)
          sprintf ( M,"a structure is used as a loop on line %i\n%s",
                    LineNo,InputLine );
        else if (RC & CIFW_DuplicateTag)
          sprintf ( M,"duplicate tag was found on line %i\n%s",
                    LineNo,InputLine );
        else
          sprintf ( M,"undocumented warning issued for line %i\n%s",
                    LineNo,InputLine );
      } else if (RC<0)
        switch (RC)  {
          case CIFRC_StructureNoTag : strcpy(M,"tag of a structure not "
                                               "found");
                                 break;
          case CIFRC_LoopNoTag      : strcpy(M,"tag of a loop not found");
                                 break;
          case CIFRC_NoCategory     : strcpy(M,"category not found");
                                 break;
          case CIFRC_WrongFormat    : strcpy(M,"wrong format of a number");
                                 break;
          case CIFRC_NoTag          : strcpy(M,"tag not found");
                                 break;
          case CIFRC_NotAStructure  : strcpy(M,"category is not a "
                                               "structure");
                                 break;
          case CIFRC_NotALoop       : strcpy(M,"category is not a loop");
                                 break;
          case CIFRC_WrongIndex     : strcpy(M,"index outside the loop's "
                                               "limits");
                                 break;
          case CIFRC_NoField        : strcpy(M,"data is absent");
                                 break;
          case CIFRC_Created        : strcpy(M,"category created");
                                 break;
          case CIFRC_CantOpenFile   : strcpy(M,"can't open CIF file");
                                 break;
          case CIFRC_NoDataLine     : strcpy(M,"'data_' tag not found." );
                                 break;
          default                   : strcpy(M,"undocumented return code");
        }

      return M;

    }

  }  // namespace mmcif

}  // namespace mmdb