File: cdentrez.c

package info (click to toggle)
ncbi-tools6 6.1.20170106%2Bdfsg1-9
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 468,492 kB
  • sloc: ansic: 1,474,204; pascal: 6,740; cpp: 6,248; xml: 3,390; sh: 2,139; perl: 1,084; csh: 508; makefile: 437; javascript: 198; ruby: 93; lisp: 81
file content (3868 lines) | stat: -rw-r--r-- 103,530 bytes parent folder | download | duplicates (13)
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
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
/*   cdentrez.c                                                          
 * ===========================================================================
 *
 *                            PUBLIC DOMAIN NOTICE                          
 *               National Center for Biotechnology Information
 *                                                                          
 *  This software/database is a "United States Government Work" under the   
 *  terms of the United States Copyright Act.  It was written as part of    
 *  the author's official duties as a United States Government employee and 
 *  thus cannot be copyrighted.  This software/database is freely available 
 *  to the public for use. The National Library of Medicine and the U.S.    
 *  Government have not placed any restriction on its use or reproduction.  
 *                                                                          
 *  Although all reasonable efforts have been taken to ensure the accuracy  
 *  and reliability of the software and data, the NLM and the U.S.          
 *  Government do not and cannot warrant the performance or results that    
 *  may be obtained by using this software or data. The NLM and the U.S.    
 *  Government disclaim all warranties, express or implied, including       
 *  warranties of performance, merchantability or fitness for any particular
 *  purpose.                                                                
 *                                                                          
 *  Please cite the author in any work or product based on this material.   
 *
 * ===========================================================================
 *
 * RCS $Id: cdentrez.c,v 6.2 1999/03/11 23:20:07 kans Exp $
 *
 * Author:  Ostell, Kans
 *
 * Version Creation Date:   10/15/91
 *
 * File Description: 
 *   	entrez index access library for Entrez CDROM
 *
 * Modifications:  
 * --------------------------------------------------------------------------
 * Date     Name        Description of modification
 * -------  ----------  -----------------------------------------------------
 * 07-07-94 Schuler     Added CdEntrezGetInfo function
 * 07-12-94 Schuler     Added #ifdef _NEW_CdEntrez_/_OLD_CdEntrez
 * 07-13-94 Schuler     Moved CdTermFree here from cdromlib.c
 * 09-22-94 Schuler     CdEntrezFini: set _nouveau to FALSE
 * 11-22-94 Schuler     Cleaned up some integer size problems
 *
 * 05-19-95 Schuler     Added rcs Log directive for automatic insertion of
 *                      modification comments.
 *
 * Revision $Log: cdentrez.c,v $
 * Revision Revision 6.2  1999/03/11 23:20:07  kans
 * Revision sprintf cast
 * Revision
 * Revision Revision 6.1  1998/08/24 18:42:15  kans
 * Revision fixed -v -fd warnings
 * Revision
 * Revision Revision 6.0  1997/08/25 18:12:52  madden
 * Revision Revision changed to 6.0
 * Revision
 * Revision Revision 5.5  1997/06/26 21:55:31  vakatov
 * Revision [PC] DLL'd "ncbicdr.lib", "ncbiacc.lib", "ncbinacc.lib" and "ncbicacc.lib"
 * Revision
 * Revision Revision 5.4  1997/03/07 17:16:10  epstein
 * Revision always choose the highest GI in EntrezFindSeqId
 * Revision
 * Revision 5.3  1997/01/14  21:26:07  epstein
 * plug memory leak when performing Entrez set-difference operations
 *
 * Revision 5.2  1996/11/22  18:02:19  epstein
 * change algorithm for looking up PDB accessions
 *
 * Revision 5.1  1996/08/14  19:56:41  epstein
 * add APIs for fetching pieces of biostruc annots (mostly written by Chris Hogue)
 *
 * Revision 5.0  1996/05/28  13:55:34  ostell
 * Set to revision 5.0
 *
 * Revision 4.18  1996/05/14  21:01:12  epstein
 * use SQID index to and docsum to convert back-and-forth between GIs and SeqIds, per Jim Ostell
 *
 * Revision 4.17  1996/04/01  21:02:31  epstein
 * remove dead CdEntrezBiostrucAnnotSetGet() code
 *
 * Revision 4.16  1996/04/01  20:59:38  epstein
 * Schuler/Epstein changes for cleaner CdEntrezBiostrucAnnotSetGet retrieval
 *
 * Revision 4.15  1996/03/29  18:52:12  epstein
 * add support for structure alignments (includes kludge for now)
 *
 * Revision 4.14  1995/10/23  21:39:56  epstein
 * another tweak for PC 16-bit addressing
 *
 * Revision 4.13  1995/10/23  14:17:52  epstein
 * fix 16/32-bit portability problems
 *
 * Revision 4.12  1995/10/03  14:12:40  epstein
 * repair term-checking logic to avoid erroneous caching
 *
 * Revision 4.11  1995/10/02  15:25:56  epstein
 * correct range-checking logic due to semantics of StringXCmp()
 *
 * Revision 4.10  1995/10/02  12:51:23  epstein
 * fix endpoints for range scanning
 *
 * Revision 4.9  1995/10/02  12:49:44  epstein
 * add memory-based performance enhancements
 *
 * Revision 4.8  1995/10/02  02:35:33  epstein
 * add range-checking
 *
 * Revision 4.7  1995/09/19  13:27:51  epstein
 * add truncation limit
 *
 * Revision 4.6  1995/08/30  20:54:53  epstein
 * search TYP_CH database if retcode is -1
 *
 * Revision 4.5  1995/08/28  23:20:47  kans
 * includes new mmdbapi headers
 *
 * Revision 4.4  1995/08/28  17:44:01  epstein
 * add code so that when retcode is -1, we perform less validation on the retrieve Seq-entry
 *
 * Revision 4.3  1995/08/24  20:44:10  epstein
 * add more stuff for genomes
 *
 * Revision 4.2  1995/08/18  17:41:17  epstein
 * fix (?) parsing of PDB accession per Brandon's observation
 *
 * Revision 4.1  1995/08/11  20:26:18  epstein
 * add max-models support for biostrucs
 *
 * Revision 4.0  1995/07/26  13:50:32  ostell
 * force revision to 4.0
 *
 * Revision 2.62  1995/07/19  22:07:00  kans
 * added (probably superfluous) casts to some sprintf calls
 *
 * Revision 2.61  1995/06/29  15:57:03  epstein
 * added Complexity argument when fetching structures
 *
 * Revision 2.60  95/06/27  11:54:35  kans
 * replaced _OLD_CDEntrez_ with _OLD_CdEntrez_
 * 
 * Revision 2.59  1995/06/23  16:02:43  kans
 * support for accmmdbs.c stub to resolve symbols without MMDB link
 *
 * Revision 2.58  1995/06/23  13:22:25  kans
 * Biostruc_CD_supported symbol needed for local MMDB access
 *
 * Revision 2.57  1995/05/16  14:36:20  schuler
 * Automatic comment insertion enabled
 *
 *
 * ==========================================================================
 */

#define REVISION_STR  "$Revision: 6.2 $"

static char * _this_module = "CdEntrez";
#define THIS_MODULE _this_module
static char * _this_file = __FILE__;
#define THIS_FILE _this_file

#include <accentr.h>
#include <cdentrez.h>
#include <sequtil.h>
#include <objall.h>

typedef struct posting {
  ByteStorePtr  uids;
  DocUidPtr     buffer;
  Int4          bufsize;
  Int4          index;
  Int4          count;
} Posting, PNTR PostingPtr;

#define SCAN_MAX 200

/* the 1023 below is not a typo; it's needed to avoid overflowing 16-bit
   addressing on PCs */
#define DEF_CDENTREZ_MEMUSAGE (64 * 1023L)
#define MAX_CDENTREZ_UID_LIST_SIZE (cdMemUsage)
#define CDENTREZ_TERM_MAX (cdMemUsage / 4)
#define MAX_CDENTREZ_BYTESTORE (cdMemUsage / 4)
#define MAX_CDENTREZ_SMALL_LIST (cdMemUsage / 2)

typedef struct scanData {
  Int4          specialCount;
  Int4          totalCount;
  Int4          offset;
  ByteStorePtr  specialPtr;
  ByteStorePtr  remainderPtr;
} ScanData, PNTR ScanPtr;

static Int2          db;
static Int2          fld;

static DocUidPtr     uidPtr;

static Int2          searchTermLen;
static Int4          cdMemUsage = 32768;

static ByteStorePtr  specialPost;
static ByteStorePtr  remainPost;

static Char          selection [256];
static Char          wildcard [256];
static Char          topOfRange [256];
static Boolean       rangeScanning = FALSE;

static ScanPtr       scanPtr;
static Int4          scanCount;
static Boolean       scanOk;
static CdTermProc    userScanProc;

static CdTermPtr     eset;

static ValNodePtr    cachedExpr = NULL;
static ByteStorePtr  cachedBsp = NULL;

static void NEAR NextNode PROTO((void));
static ByteStorePtr NEAR Factor PROTO((void));
static ByteStorePtr NEAR Term PROTO((void));        
static ByteStorePtr NEAR Diff PROTO((void));
static ByteStorePtr NEAR Expression PROTO((void));
static CdTermPtr NEAR FindTermNode PROTO((CharPtr term, DocType type, DocField field, CharPtr highRange));
static ValNodePtr CdTLExprFree PROTO((ValNodePtr elst));

static PostingPtr NEAR NewPost PROTO((ByteStorePtr lst, Int4 defsize));
static PostingPtr NEAR FreePost PROTO((PostingPtr pst));
static Int4 NEAR PostLength PROTO((PostingPtr pst));
static void NEAR RewindPost PROTO((PostingPtr pst));
static DocUid NEAR ReadItem PROTO((PostingPtr pst));
static void NEAR WriteItem PROTO((PostingPtr pst, DocUid value));
static void NEAR FlushItems PROTO((PostingPtr pst));
static void NEAR SavePostingList PROTO((FILE *f, ByteStorePtr bsp));

static Boolean NEAR CdEntrezMergeTerm PROTO((DocType type, DocField field, CharPtr term, Int4Ptr spcl, Int4Ptr totl, CdTermProc userProc));
static void NEAR SingleSpaces PROTO((CharPtr str));
static void NEAR TermTruncate PROTO((CharPtr str));
static void NEAR QuickSortSmall PROTO((DocUidPtr uids, Int4 l, Int4 r));
static Int4 NEAR CompressSmall PROTO((DocUidPtr uids, Int4 count));
static Int4 NEAR UniqueSmall PROTO((DocUidPtr uids, Int4 count));
static ByteStorePtr NEAR MergeSmallLists PROTO((ByteStorePtr bsp, ByteStorePtr small));
static Boolean NEAR MergeSeveralLists PROTO((Int4 i, Int4 count));
static Boolean NEAR MergeSeveralOrderedLists PROTO((Int4 i, Int4 count));
static Boolean NEAR MergeUnorderedLists PROTO((Int4 i, Int4 count));
static Boolean NEAR ProcessScanResults PROTO((void));
static Boolean  WildCardProc PROTO((CdTermPtr trmp));
static Boolean  ScanOnlyProc PROTO((CdTermPtr trmp));
static Boolean  ScanAndFreeProc PROTO((CdTermPtr trmp));

/**** Moved from cdentrez.h ********************/

static CdTermPtr NEAR CdEntrezCreateTerm PROTO((CharPtr term, DocType type, DocField field, ByteStorePtr special, ByteStorePtr remainder, CharPtr highRange));
static ByteStorePtr NEAR LoadPostingList PROTO((FILE *f, Int4 special, Int4 total));
static ByteStorePtr NEAR FreePostingList PROTO((ByteStorePtr lst));
static ByteStorePtr NEAR MergePostingLists PROTO((ByteStorePtr lst1, ByteStorePtr lst2));
static ByteStorePtr NEAR IntersectPostingLists PROTO((ByteStorePtr lst1, ByteStorePtr lst2));
static ByteStorePtr NEAR DifferencePostingLists PROTO((ByteStorePtr lst1, ByteStorePtr lst2));

static ValNodePtr currNode;
static Uint1 currChoice;

/************************* moved from old cdml.c ****************************/
static AsnTypePtr  MEDLINE_ENTRY = NULL;
static AsnTypePtr  MEDLINE_ENTRY_cit = NULL;
static AsnTypePtr  MEDLINE_ENTRY_abstract = NULL;
static AsnTypePtr  TITLE_E_trans = NULL;
static AsnTypePtr  AUTH_LIST_names_ml_E = NULL;
static AsnTypePtr  AUTH_LIST_names_str_E = NULL;
static AsnTypePtr  DATE_STD_year = NULL;
static AsnTypePtr  DATE_str = NULL;
static AsnTypePtr  TITLE_E_name = NULL;
static AsnTypePtr  MEDLINE_ENTRY_mesh = NULL;
static AsnTypePtr  MEDLINE_ENTRY_substance = NULL;
static AsnTypePtr  MEDLINE_ENTRY_xref = NULL;
static AsnTypePtr  MEDLINE_ENTRY_idnum = NULL;
static AsnTypePtr  MEDLINE_ENTRY_gene = NULL;

static DocSumPtr NEAR MedSumAsnRead PROTO((AsnIoPtr aip, DocUid uid));
static void NEAR StripAuthor PROTO((CharPtr author));
static void NEAR FindAsnType PROTO((AsnTypePtr PNTR atp, AsnModulePtr amp, CharPtr str));

static DocSumPtr NEAR CdEntMlSumGet PROTO((Int4 uid));

/************************* moved from old cdseq.c ****************************/
static AsnTypePtr  SEQ_ENTRY = NULL;
static AsnTypePtr  SEQ_ENTRY_seq = NULL;
static AsnTypePtr  SEQ_ENTRY_set = NULL;
static AsnTypePtr  TEXTSEQ_ID_name = NULL;
static AsnTypePtr  TEXTSEQ_ID_accession = NULL;
static AsnTypePtr  SEQ_DESCR_E_title = NULL;
static AsnTypePtr  GIIMPORT_ID_id = NULL;
static AsnTypePtr  BIOSEQ_inst = NULL;
static AsnTypePtr  SEQ_INST_mol = NULL;
static AsnTypePtr  SEQ_INST_repr = NULL;
static AsnTypePtr  SEQ_ID_gibbsq = NULL;
static AsnTypePtr  SEQ_ID_gibbmt = NULL;
static AsnTypePtr  SEQ_ID_genbank = NULL;
static AsnTypePtr  SEQ_ID_gi = NULL;
static AsnTypePtr  SEQ_ID_embl = NULL;
static AsnTypePtr  SEQ_ID_ddbj = NULL;
static AsnTypePtr  SEQ_ID_pir = NULL;
static AsnTypePtr  SEQ_ID_swissprot = NULL;
static AsnTypePtr  PDB_BLOCK_compound_E = NULL;
static AsnTypePtr  PDB_SEQ_ID_MOL = NULL;
static AsnTypePtr  BIOSEQ_id = NULL;
static AsnTypePtr  BIOSEQ_id_E = NULL;
static AsnTypePtr  CIT_PAT_title = NULL;

static DocSumPtr NEAR CdEntSeqSumGet PROTO((Int4 uid, DocType type));

extern int _nouveau;

/*****************************************************************************
*
*   CdEntrezInit ()
*       Creates linked list of CdTerm nodes, creates temporary file for
*       postings lists, saves file name in first node.  When creating new
*       nodes, posting file is appended to temporary file, node offset then
*       points to temporary file location of posting information.
*
*****************************************************************************/

NLM_EXTERN Boolean  CdEntrezInit (Boolean no_warnings)

{
  FILE      *fp;
  Char      str [PATH_MAX];
  Boolean inited = FALSE;
  CharPtr   prop;
  
#ifdef Biostruc_supported
	objmmdb1AsnLoad ();
	objmmdb2AsnLoad ();
	objmmdb3AsnLoad ();
#endif
#ifdef _NEW_CdEntrez_
	_nouveau = GetAppParamBoolean("ncbi","CdEntrez","NewStyle",TRUE);
	if (_nouveau)
	{	
		if (cd3_CdInit())
			inited = TRUE;
		else
			ErrLogPrintf("cd3_CdInit() failed\n");
	}
#endif
	/* In the dual OLD/NEW case, go on to try CdInit if cd3_CdInit failed */
#ifdef _OLD_CdEntrez_
	if (!inited)
	{
		if (CdInit())
		{
			inited = TRUE;
			_nouveau = FALSE;
		}
	}
#endif
	if (!inited)
		return FALSE;
		
	eset = MemNew (sizeof (CdTerm));
	if (eset == NULL)
		return FALSE;
	eset->type = 255;   /* set to not used */
    TmpNam (str);
    eset->term = StringSave (str);
#ifdef WIN_MAC
    FileCreate (str, "????", "NCBI");
#endif
    fp = FileOpen (str, "wb");
	if (fp == NULL) {
		ErrPostEx (SEV_ERROR, ERR_CD_FILEOPEN, 0, "Unable to open temporary file %s", str);
		return FALSE;
	}
    FileClose (fp);
  if ((prop = (CharPtr) GetAppProperty("CdEntrezMemUsage")) != NULL)
  {
      long tmplong;

      sscanf(prop, "%ld", &tmplong);

      cdMemUsage = tmplong;
  } else {
      cdMemUsage = DEF_CDENTREZ_MEMUSAGE;
  }
      cdMemUsage = MIN(cdMemUsage, MAXALLOC);
	return TRUE;
}

/*****************************************************************************
*
*   CdEntrezFini ()
*       Frees linked list of CdTerm nodes and removes temporary posting file.
*
*****************************************************************************/

NLM_EXTERN void  CdEntrezFini (void)

{
  CdTermPtr nxt;
  Char      temp [PATH_MAX];

  if (eset != NULL) {
    if (eset->term != NULL) {
      StringCpy (temp, eset->term);
      FileRemove (temp);
    }
    while (eset != NULL) {
      nxt = eset->next;
      CdTermFree (eset);
      eset = nxt;
    }
  }
  eset = NULL;

  cachedExpr = CdTLExprFree(cachedExpr);
  cachedBsp = BSFree(cachedBsp);
  
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		cd3_CdFini();
#endif
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		CdFini();
#endif
	_nouveau = FALSE;
}


/*****************************************************************************
*
*   CdEntrezGetInfo ()
*
*****************************************************************************/

NLM_EXTERN EntrezInfo* CdEntrezGetInfo (void)
{
	EntrezInfo *info = NULL;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		info = cd3_CdGetInfo();
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		info = CdGetInfo();
#endif
	
	return info;
}

/*****************************************************************************
*
*   CdEntrezDetailedInfo ()
*
*****************************************************************************/

NLM_EXTERN char* CdEntrezDetailedInfo (void)
{
	char *info = NULL;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		info = cd3_CdDetailedInfo();
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		info = CdDetailedInfo();
#endif
	
	return info;
}


/*****************************************************************************
*
*   CdEntGetMaxLinks()
*   	returns max links in link set allowed by system
*
*****************************************************************************/
NLM_EXTERN Int4 CdEntGetMaxLinks (void)

{
	return (Int4)(INT_MAX / sizeof(DocUid));
}

/*****************************************************************************
*
*   CdEntrezCreateNamedUidList(term, type, field, num, uids)
*       Creates a term node in the entrez set structure if one does not
*       yet exist, and loads the posting file from the uid parameter.
*
*****************************************************************************/
NLM_EXTERN void  CdEntrezCreateNamedUidList (CharPtr term, DocType type, DocField field, Int4 num, DocUidPtr uids)

{
  Int4          count;
  ByteStorePtr  post;
  Char          str [256];

  if (term != NULL && uids != NULL && num > 0 && num <= 16383) {
    StringNCpy (str, term, sizeof (str) - 1);
    post = BSNew (0);
    if (post != NULL) {
      count = (Int4) num;
      QuickSortSmall (uids, 0, (Int4) (count - 1));
      count = CompressSmall (uids, count);
      count = UniqueSmall (uids, count);
      BSWrite (post, uids, (Int4) (count * sizeof (DocUid)));
      CdEntrezCreateTerm (str, type, field, NULL, post, NULL);
      BSFree (post);
    }
  }
}

/*****************************************************************************
*
*   CdEntrezCreateNamedUidListX(term, type, field, post)
*       Creates a term node in the entrez set structure if one does not
*       yet exist, and loads the posting file from the uid parameter.
*
*****************************************************************************/
NLM_EXTERN void  CdEntrezCreateNamedUidListX (CharPtr term, DocType type, DocField field, ByteStorePtr bsp)

{
  Int4          actual;
  Int4          count;
  ByteStorePtr  post;
  ByteStorePtr  small;
  Char          str [256];
  DocUidPtr     uids;

  if (term != NULL && bsp != NULL) {
    StringNCpy (str, term, sizeof (str) - 1);
    post = BSNew (0);
    if (post != NULL) {
      uids = MemNew (4096 * sizeof (DocUid));
      BSSeek (bsp, 0L, 0);
      actual = BSRead (bsp, uids, (Int4) (4096 * sizeof (DocUid)));
      while (actual > 0) {
        count = (Int4) actual;
        QuickSortSmall (uids, 0, (Int4) (count - 1));
        count = CompressSmall (uids, count);
        count = UniqueSmall (uids, count);
        if (count > 0) {
          small = BSNew (0L);
          if (small != NULL) {
            BSWrite (small, uids, count * sizeof (DocUid));
            post = MergePostingLists (post, small);
          }
        }
        actual = BSRead (bsp, uids, (Int4) (4096 * sizeof (DocUid)));
      }
      CdEntrezCreateTerm (str, type, field, NULL, post, NULL);
      MemFree (uids);
      BSFree (post);
    }
  }
}

/*****************************************************************************
*
*   CdEntTLNew (type)
*       Creates linked list of asn nodes for constructing boolean query on
*       terms.  First node points to the EntrezSetNew-created structure that
*       maps terms to posting lists.  Remaining nodes contain symbols for AND,
*       OR, LEFT PARENTHESIS, RIGHT PARENTHESIS, or a SPECIAL or TOTAL term
*       specification.  The term specification nodes point to a CdTerm node
*       within the entrez set structure.
*
*****************************************************************************/

NLM_EXTERN ValNodePtr  CdEntTLNew (DocType type)

{
  ValNodePtr anp;

  anp = NULL;
  if (eset != NULL) {
    anp = ValNodeNew (NULL);
    if (anp != NULL) {
      anp->choice = NULLSYM;
      anp->data.ptrvalue = (Pointer) eset;
	  eset->type = type;
    }
  }
  return anp;
}

/*****************************************************************************
*
*   CdEntTLAddTerm (elst, term, type, field, special, highRange)
*       Adds a term node to a boolean algebraic term query.
*
*****************************************************************************/

NLM_EXTERN ValNodePtr  CdEntTLAddTerm (ValNodePtr elst, CharPtr term, DocType type, DocField field, Boolean special, CharPtr highRange)

{
  ValNodePtr anp;
  CdTermPtr  trmp;

  anp = NULL;
  if (eset != NULL && elst != NULL) {
	if (type != eset->type)   /* mixed databases */
		return NULL;
    anp = ValNodeNew (elst);
    if (anp != NULL) {
      if (special) {
        anp->choice = SPECIALTERM;
      } else {
        anp->choice = TOTALTERM;
      }
      trmp = FindTermNode (term, type, field, highRange);
      anp->data.ptrvalue = (Pointer) trmp;
    }
  }
  return anp;
}

/*****************************************************************************
*
*   CdEntTLFree (elst)
*       Frees a boolean algebraic term query list.
*
*****************************************************************************/

NLM_EXTERN ValNodePtr  CdEntTLFree (ValNodePtr elst)

{
  if (elst != NULL) {
    ValNodeFree (elst);
	eset->type = 255;   /* set to nothing */
  }
  return NULL;
}

/*****************************************************************************
*
*   CdTLExprFree(elst)
*
*   Free the CdEntrez-style expression, including all of its subordinate terms
****************************************************************************/
static ValNodePtr CdTLExprFree(ValNodePtr elst)
{
  ValNodePtr np;
  CdTermPtr tp;

  for (np = elst; np != NULL; np = np->next) {
    switch (np->choice) {
    case SPECIALTERM:
    case TOTALTERM:
      if ((tp = np->data.ptrvalue) != NULL) {
        MemFree (tp->term);
        MemFree (tp->highRange);
        MemFree (tp);
      }
      break;
    default:
      break;
    }
  }

  ValNodeFree(elst);

  return NULL;
}


/*****************************************************************************
*
*   CdDupExpr(elst)
*
*   Duplicate the input CdEntrez-style expression
****************************************************************************/
static ValNodePtr CdDupExpr(ValNodePtr elst)
{
  ValNodePtr dup = NULL;
  ValNodePtr trailing = NULL;
  ValNodePtr np;
  CdTermPtr tp1, tp2;

  for (; elst != NULL; elst = elst->next) {
    np = ValNodeNew(NULL);
    if (dup == NULL)
      dup = np;
    if (trailing != NULL)
      trailing->next = np;
    trailing = np;
    np->choice = elst->choice;
    switch (elst->choice) {
    case SPECIALTERM:
    case TOTALTERM:
      tp2 = elst->data.ptrvalue;
      if (tp2 != NULL)
      {
        tp1 = MemNew(sizeof(*tp1));
        np->data.ptrvalue = tp1;
        tp1->type = tp2->type;
        tp1->field = tp2->field;
        tp1->term = StringSave(tp2->term);
        tp1->highRange = StringSave(tp2->highRange);
      }
      break;
    default:
      break;
    }
  }

  return dup;
}

static Boolean
EqualTerms (CharPtr x, CharPtr y)
{
  if (x == NULL && y == NULL)
    return TRUE;
  if (x == NULL || y == NULL)
    return FALSE;
  return (StringICmp(x,y) == 0);
}
  

/*****************************************************************************
*
*   CdEntTLExprEqual (elst1, elst2)
*
*   Determine whether two CdEntrez-style boolean expressions are equal
****************************************************************************/

static Boolean
CdTLExprEqual (ValNodePtr elst1, ValNodePtr elst2)
{
  Boolean equal = TRUE;
  CdTermPtr c1, c2;

  for (; elst1 != NULL && elst2 != NULL && equal; elst1 = elst1->next,
       elst2 = elst2->next) {
    if (elst1->choice == elst2->choice) {
      switch (elst1->choice) {
        case SPECIALTERM:
        case TOTALTERM:
          c1 = elst1->data.ptrvalue;
          c2 = elst2->data.ptrvalue;
          equal = c1 != NULL && c2 != NULL && c1->type == c2->type &&
                  c1->field == c2->field && EqualTerms(c1->term, c2->term) &&
                  EqualTerms(c1->highRange, c2->highRange);
          break;
        default:
          break;
      }
    } else {
      equal = FALSE;
    }
  }

  return elst1 == NULL && elst2 == NULL && equal;
}


/*****************************************************************************
*
*   CdEntTLEvalCount (elst)
*       Evaluates a boolean algebraic term query list, returning the
*       count of resulting UIDs.
*
*****************************************************************************/

NLM_EXTERN Int4 CdEntTLEvalCount (ValNodePtr elst)
{
  ByteStorePtr bsp;
  Int4         len;

  len = 0;
  bsp = CdEntTLEvalX(elst);
  if (bsp != NULL) {
    len = BSLen(bsp) / sizeof(DocUid);
    BSFree (bsp);
  }
  return len;
}


/*****************************************************************************
*
*   CdEntTLEvalX (elst)
*       Evaluates a boolean algebraic term query list, returning a pointer to
*       a ByteStore containing the resultant unique identifiers.  The number
*       of UIDs is calculated as BSLen (bsp) / sizeof (DocUid).
*
*****************************************************************************/

NLM_EXTERN ByteStorePtr  CdEntTLEvalX (ValNodePtr elst)

{
  ByteStorePtr bsp;

  bsp = NULL;
  if (eset != NULL && elst != NULL) {
    if (cachedExpr != NULL && CdTLExprEqual(elst, cachedExpr)) {
      BSSeek(cachedBsp, 0L, SEEK_SET);
      bsp = BSDup (cachedBsp);
    } else {
      cachedExpr = CdTLExprFree(cachedExpr);
      cachedExpr = CdDupExpr(elst);
      cachedBsp = BSFree(cachedBsp);

      currNode = elst;
      currChoice = NULLSYM;
      NextNode ();
      if (eset->term != NULL && currNode != NULL) {
        bsp = Expression ();
        BSSeek(bsp, 0L, SEEK_SET);
        cachedBsp = BSDup(bsp);
      }

    }
  }
  return bsp;
}

/*****************************************************************************
*
*   CdEntTLEval (elst)
*       Evaluates a boolean algebraic term query list, returning a pointer to
*       a LinkSet containing the resultant unique identifiers.
*
*****************************************************************************/

NLM_EXTERN LinkSetPtr  CdEntTLEval (ValNodePtr elst)

{
  ByteStorePtr bsp;
  LinkSetPtr lsp = NULL;
  Int4 numlinks;

  bsp = CdEntTLEvalX (elst);
  if (bsp != NULL)
	{
		numlinks = BSLen(bsp) / sizeof(DocUid);
		lsp = LinkSetNew();
		lsp->num = numlinks;
		if (numlinks <= CdEntGetMaxLinks())
		{
			lsp->uids = MemNew((size_t)(numlinks * sizeof(DocUid)));
			BSSeek (bsp, 0L, 0);
			BSRead(bsp, lsp->uids, (numlinks * sizeof(DocUid)));
		}
		BSFree(bsp);
	}
  return lsp;
}

/*****************************************************************************
*
*   DocSumPtr CdDocSum(type, uid)
*
*****************************************************************************/
NLM_EXTERN DocSumPtr  CdDocSum (DocType type, DocUid uid)

{
	DocSum *sum = NULL;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
	{
		sum = CdGetDocSum(type,uid);
	}
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
	{
		if (type == TYP_ML)
			sum = CdEntMlSumGet(uid);
		else
			sum = CdEntSeqSumGet(uid, type);
	}
#endif

	return sum;
}


#ifdef _NEW_CdEntrez_
NLM_EXTERN int  CdDocSumListGet PROTO((DocSum **result, int numuid, DocType type, const DocUid *uids))
{
	int i, n;
	const DocUid *p = uids;
	DocSum **s = result;
		
	ASSERT(result != NULL);
	ASSERT(uids != NULL);
	
	for (i=n=0; i<numuid; ++i)
	{
		if ((*s = CdGetDocSum(type,*p++)) != NULL)
		{
			s++;
			n++;
		}
	}
	return n;	
}
#endif



/*****************************************************************************
*
*   CdLinkUidList(type, link_to_type, numuid, uids)
*   	returns count of input uids processed
*       returns -1 on error
*       if neighbors (type == link_to_type)
*   		sums weights for same uids
*   	if (more than EntrezUserMaxLinks() uids, frees uids and weights,
*           but leaves num set)
*
*****************************************************************************/
NLM_EXTERN Int2  CdLinkUidList (LinkSetPtr PNTR result, DocType type, DocType link_to_type, Int2 numuid, Int4Ptr uids, Boolean mark_missing)      
{
	Int4 max_links = CdEntGetMaxLinks();
	Int4 count;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		count = cd3_CdLinkUidGet(result,type,link_to_type,numuid,uids,mark_missing,max_links);
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		count = CdLinkUidGet(result,type,link_to_type,numuid,uids,mark_missing,max_links);
#endif

	return count;
}

/*****************************************************************************
*
*   CdUidLinks()
*   	retrieves links to other uids
*
*****************************************************************************/
NLM_EXTERN LinkSetPtr  CdUidLinks (DocType type, DocUid uid, DocType link_to_type)
{
	LinkSetPtr lsp = NULL;
	DocUid u = uid;

#ifdef _NEW_CdEntrez_
	if (_nouveau)
	  cd3_CdLinkUidGet(&lsp,type,link_to_type,1,&u,FALSE,CdEntGetMaxLinks());
#endif
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
	  CdLinkUidGet(&lsp,type,link_to_type,1,&u,FALSE,CdEntGetMaxLinks());
#endif

	return lsp;
}

static Boolean  TermListPageScanProc PROTO((CdTermPtr trmptr));
static Boolean  TermListTermScanProc PROTO((CdTermPtr trmptr));
static TermListProc trmproc;
static Int4 trmcount;
static Int4 trmmax;
static Boolean trmfound;
static Char trmfirst [80];
static Int4 the_first_page;

/*****************************************************************************
*
*   CdTermListByPage (type, field, page, numpage, proc)
*   	Gets terms starting at page, for numpage, by calling proc
*   	returns number of complete pages read
*
*****************************************************************************/
NLM_EXTERN Int2  CdTermListByPage (DocType type, DocField field, Int2 page, Int2 numpage, TermListProc proc)

{
	trmproc = proc;
	if (trmproc != NULL) {
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		return cd3_CdTermScan(type, field, page, numpage, TermListPageScanProc);
#endif
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		return CdTermScan(type, field, page, numpage, TermListPageScanProc);
#endif
	} else {
		return 0;
	}

	return 0;
}

/*****************************************************************************
*
*   CdTermListByTerm (type, field, term, numterms, proc, first_page)
*   	Gets Terms starting with at term
*   	returns number of complete pages read
*   	sets first_page to first page read
*
*****************************************************************************/
NLM_EXTERN Int2  CdTermListByTerm (DocType type, DocField field, CharPtr term, Int2 numterms, TermListProc proc, Int2Ptr first_page)

{
	Int4  first;
	Int4  rsult;

	rsult = 0;
#ifdef _NEW_CdEntrez_
	if (_nouveau)
		first = cd3_CdTrmLookup(type, field, term);
#endif
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		first = CdTrmLookup(type, field, term);
#endif
	the_first_page = first;
	trmproc = proc;
	trmcount = 0;
	if (numterms > 0) {
		trmmax = numterms;
	} else {
		trmmax = INT2_MAX;
	}
	trmfound = FALSE;
	StringNCpy (trmfirst, term, sizeof (trmfirst) - 1);
	if (trmproc != NULL) {
#ifdef _NEW_CdEntrez_
		if (_nouveau)
			rsult = cd3_CdTermScan(type,field,first,0,TermListTermScanProc);
#endif
#ifdef _OLD_CdEntrez_
		if (!_nouveau)
			rsult = CdTermScan(type,field,first,0,TermListTermScanProc);
#endif
	}
	if (first_page != NULL) {
	  *first_page = the_first_page;
	}
	return rsult;
}

/*****************************************************************************
*
*   TermListPageScanProc(trmptr)
*   	Callback for CdTermListByPage
*
*****************************************************************************/
static Boolean  TermListPageScanProc(CdTermPtr trmptr)
{
  Boolean ret = trmproc(trmptr->term,
                        trmptr->special_count, trmptr->total_count);
  MemFree(trmptr);
  return ret;
}

/*****************************************************************************
*
*   TermListTermScanProc(trmptr)
*   	Callback for CdTermListByTerm
*
*****************************************************************************/
static Boolean  TermListTermScanProc(CdTermPtr trmptr)
{
  Boolean ret = TRUE;
  if (! trmfound) {
    if (MeshStringICmp (trmptr->term, trmfirst) >= 0) {
      trmfound = TRUE;
      the_first_page = trmptr->page;
    }
  }
  if (trmfound) {
    ret = trmproc(trmptr->term, trmptr->special_count, trmptr->total_count);
    trmcount++;
  } else {
    MemFree (trmptr->term);
  }
  MemFree(trmptr);
  return (ret && trmcount < trmmax);
}

/*****************************************************************************
*
*   CdEntrezFindTerm(type, field, term, spec, total)
*   	returns count of special and total for a term
*   	if term ends with  "...", does a truncated merge of the term
*   	if term contains '*' or '?', does a wild card merge
*
*****************************************************************************/
NLM_EXTERN Boolean  CdEntrezFindTerm (DocType type, DocField field, CharPtr term, Int4Ptr spcl, Int4Ptr totl)

{
	CharPtr tmp;
	CdTermPtr ctp;

	tmp = term;
	while (*tmp != '\0')
		tmp++;
	tmp -= 3;
	if ((*tmp == '.') && (*(tmp+1) == '.') && (*(tmp+2) == '.')) {
		return CdEntrezMergeTerm (type, field, term, spcl, totl, NULL);
	} else if (StringChr (term, '*') != NULL || StringChr (term, '?') != NULL) {
		return CdEntrezMergeTerm (type, field, term, spcl, totl, WildCardProc);
	} else {
#ifdef _NEW_CdEntrez_
		if (_nouveau)
			ctp = cd3_CdTrmFind(type,field,term);
#endif
#ifdef _OLD_CdEntrez_
		if (!_nouveau)
			ctp = CdTrmFind(type,field,term);
#endif
		if (ctp == NULL)
			return FALSE;
		*spcl = ctp->special_count;
		*totl = ctp->total_count;
		CdTermFree(ctp);
		return TRUE;
	}
}


/*****************************************************************************
*
*   CdTermFree(trmp)
*      frees a CdTerm structure
*
*****************************************************************************/

NLM_EXTERN CdTermPtr  CdTermFree (CdTermPtr trmp)

{
	if (trmp == NULL)
		return NULL;
	if (trmp->term != NULL)
		MemFree (trmp->term);
	if (trmp->highRange != NULL)
		MemFree (trmp->highRange);
	return (CdTermPtr) MemFree(trmp);
}




/*****************************************************************************
*
*   Below are static functions local to this module
*   ===============================================
*
*****************************************************************************/

/*****************************************************************************
*
*   Functions to manipulate Boolean lists
*
*****************************************************************************/

/*****************************************************************************
*
*   NextNode ()
*       Advances to the next node in a term query list.
*
*****************************************************************************/

static void NEAR NextNode (void)

{
  if (currNode != NULL) {
    currNode = currNode->next;
    if (currNode != NULL) {
      currChoice = currNode->choice;
    } else {
      currChoice = NULLSYM;
    }
  } else {
    currChoice = NULLSYM;
  }
}

/*****************************************************************************
*
*   Factor ()
*       Processes individual term nodes or parenthetical expressions in a
*       term query list.
*
*****************************************************************************/

static ByteStorePtr NEAR Factor (void)

{
  ByteStorePtr bsp;
  FILE         *fp;
  CdTermPtr    trmp;

  bsp = NULL;
  if (currChoice == LPAREN) {
    NextNode ();
    bsp = Expression ();
    if (currChoice != RPAREN) {
      ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "Expected right parenthesis");
    } else {
      NextNode ();
    }
  } else if (currChoice == SPECIALTERM || currChoice == TOTALTERM) {
    if (currNode != NULL) {
      trmp = currNode->data.ptrvalue;
      if (trmp != NULL) {
        fp = FileOpen (eset->term, "rb");
        if (fp != NULL) {
          fseek (fp, trmp->offset, SEEK_SET);
          if (currChoice == SPECIALTERM) {
            bsp = LoadPostingList (fp, trmp->special_count, trmp->special_count);
          } else if (currChoice == TOTALTERM) {
            bsp = LoadPostingList (fp, trmp->special_count, trmp->total_count);
          }
          FileClose (fp);
        }
      }
    }
    NextNode ();
  } else {
    NextNode ();
  }
  return bsp;
}

/*****************************************************************************
*
*   Term ()
*       Processes strings of ANDed term nodes in a term query list.
*
*****************************************************************************/

static ByteStorePtr NEAR Term (void)

{
  ByteStorePtr bsp;
  ByteStorePtr fct;

  bsp = Factor ();
  while (currChoice == ANDSYMBL) {
    NextNode ();
    fct = Factor ();
    bsp = IntersectPostingLists (bsp, fct);
  }
  return bsp;
}

/*****************************************************************************
*
*   Diff ()
*       Processes strings of ORed term nodes in a term query list.
*
*****************************************************************************/

static ByteStorePtr NEAR Diff (void)

{
  ByteStorePtr bsp;
  ByteStorePtr trm;

  bsp = Term ();
  while (currChoice == ORSYMBL) {
    NextNode ();
    trm = Term ();
    bsp = MergePostingLists (bsp, trm);
  }
  return bsp;
}


/*****************************************************************************
*
*   Expression ()
*       Processes strings of BUTNOTed term nodes in a term query list.
*
*****************************************************************************/

static ByteStorePtr NEAR Expression (void)

{
  ByteStorePtr bsp;
  ByteStorePtr trm;

  bsp = Diff ();
  while (currChoice == BUTNOTSYMBL) {
    NextNode ();
    trm = Diff ();
    bsp = DifferencePostingLists (bsp, trm);
  }
  return bsp;
}


/*****************************************************************************
*
*   Low level functions to manipulate postings lists.
*
*****************************************************************************/

static PostingPtr NEAR NewPost (ByteStorePtr lst, Int4 defsize)

{
  PostingPtr  pst;

  pst = NULL;
  if (lst != NULL) {
    pst = MemNew (sizeof (Posting));
    if (pst != NULL) {
      pst->uids = lst;
      pst->buffer = NULL;
      if (defsize == 0) {
        pst->bufsize = (Int4) MIN (16384L, BSLen (lst));
      } else {
        pst->bufsize = (Int4) MIN (16384L, defsize);
      }
      pst->count = 0;
      pst->index = 0;
    }
  }
  return pst;
}

static PostingPtr NEAR FreePost (PostingPtr pst)

{
  if (pst != NULL) {
    if (pst->uids != NULL) {
      BSFree (pst->uids);
    }
    if (pst->buffer != NULL) {
      MemFree (pst->buffer);
    }
    MemFree (pst);
  }
  return NULL;
}

static Int4 NEAR PostLength (PostingPtr pst)

{
  Int4  k;

  k = 0;
  if (pst != NULL) {
    k = (Int4) (BSLen (pst->uids) / (Int4) sizeof (DocUid));
  }
  return k;
}

static void NEAR RewindPost (PostingPtr pst)

{
  if (pst != NULL) {
    if (pst->uids != NULL) {
      BSSeek (pst->uids, 0L, 0);
    }
    pst->count = 0;
    pst->index = 0;
  }
}

static DocUid NEAR ReadItem (PostingPtr pst)

{
  DocUid  rsult;

  rsult = INT4_MAX;
  if (pst != NULL && pst->uids != NULL) {
    if (pst->buffer == NULL) {
      pst->buffer = MemNew ((size_t) pst->bufsize);
      pst->count = 0;
      pst->index = 0;
    }
    if (pst->count <= 0) {
      pst->count = (Int4) BSRead (pst->uids, pst->buffer, pst->bufsize);
      pst->index = 0;
    }
    if (pst->count > 0) {
      rsult = pst->buffer [pst->index];
      (pst->index)++;
      (pst->count) -= sizeof (DocUid);
    }
  }
  return rsult;
}

static void NEAR WriteItem (PostingPtr pst, DocUid value)

{
  if (pst != NULL && pst->uids != NULL) {
    if (pst->buffer == NULL) {
      pst->buffer = MemNew ((size_t) pst->bufsize);
      pst->count = 0;
      pst->index = 0;
    }
    pst->buffer [pst->index] = value;
    (pst->index)++;
    (pst->count) += sizeof (DocUid);
    if (pst->count >= pst->bufsize) {
      BSWrite (pst->uids, pst->buffer, pst->count);
      pst->count = 0;
      pst->index = 0;
    }
  }
}

static void NEAR FlushItems (PostingPtr pst)

{
  if (pst != NULL && pst->uids != NULL && pst->buffer != NULL) {
    BSWrite (pst->uids, pst->buffer, pst->count);
    if (pst->buffer != NULL) {
      pst->buffer = MemFree (pst->buffer);
    }
    pst->count = 0;
    pst->index = 0;
  }
}

static ByteStorePtr NEAR MergePostingLists (ByteStorePtr lst1, ByteStorePtr lst2)

{
  PostingPtr    buf1;
  PostingPtr    buf2;
  PostingPtr    buf3;
  Int4          k;
  Int4          k1;
  Int4          k2;
  DocUid        pstar;
  DocUid        qstar;
  ByteStorePtr  rsult;

  ProgMon ("MergePostingLists");
  rsult = NULL;
  if (lst1 != NULL && lst2 != NULL) {
    buf1 = NewPost (lst1, 0);
    buf2 = NewPost (lst2, 0);
    k1 = PostLength (buf1);
    k2 = PostLength (buf2);
    k = k1 + k2;
    rsult = BSNew (k * sizeof (DocUid));
    buf3 = NewPost (rsult, k * (Int4) sizeof (DocUid));
    if (rsult != NULL && buf1 != NULL && buf2 != NULL && buf3 != NULL) {
      RewindPost (buf1);
      RewindPost (buf2);
      pstar = ReadItem (buf1);
      qstar = ReadItem (buf2);
      while (k > 0) {
        if (pstar < qstar) {
          WriteItem (buf3, pstar);
          k--;
          pstar = ReadItem (buf1);
        } else if (qstar < pstar) {
          WriteItem (buf3, qstar);
          k--;
          qstar = ReadItem (buf2);
        } else {
          WriteItem (buf3, pstar);
          k -= 2;
          pstar = ReadItem (buf1);
          qstar = ReadItem (buf2);
        }
      }
      FlushItems (buf3);
    } else {
      ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "List is too large to merge");
    }
    if (buf1 != NULL) {
      FreePost (buf1);
    }
    if (buf2 != NULL) {
      FreePost (buf2);
    }
    if (buf3 != NULL) {
      buf3->uids = NULL;
      FreePost (buf3);
    }
  } else if (lst1 != NULL) {
    rsult = lst1;
  } else if (lst2 != NULL) {
    rsult = lst2;
  }
  return rsult;
}

static ByteStorePtr NEAR IntersectPostingLists (ByteStorePtr lst1, ByteStorePtr lst2)

{
  PostingPtr    buf1;
  PostingPtr    buf2;
  PostingPtr    buf3;
  Int4          k;
  Int4          k1;
  Int4          k2;
  DocUid        pstar;
  DocUid        qstar;
  ByteStorePtr  rsult;

  ProgMon ("UnionPostingLists");
  rsult = NULL;
  if (lst1 != NULL && lst2 != NULL) {
    buf1 = NewPost (lst1, 0);
    buf2 = NewPost (lst2, 0);
    k1 = PostLength (buf1);
    k2 = PostLength (buf2);
    k = MIN (k1, k2);
    rsult = BSNew (k * sizeof (DocUid));
    buf3 = NewPost (rsult, k * (Int4) sizeof (DocUid));
    if (rsult != NULL && buf1 != NULL && buf2 != NULL && buf3 != NULL) {
      RewindPost (buf1);
      RewindPost (buf2);
      pstar = ReadItem (buf1);
      qstar = ReadItem (buf2);
      while (k1 > 0 && k2 > 0) {
        if (pstar < qstar) {
          k1--;
          pstar = ReadItem (buf1);
        } else if (qstar < pstar) {
          k2--;
          qstar = ReadItem (buf2);
        } else {
          WriteItem (buf3, pstar);
          k1--;
          k2--;
          pstar = ReadItem (buf1);
          qstar = ReadItem (buf2);
        }
      }
      FlushItems (buf3);
    } else {
      ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "List is too large to intersect");
    }
    if (buf1 != NULL) {
      FreePost (buf1);
    }
    if (buf2 != NULL) {
      FreePost (buf2);
    }
    if (buf3 != NULL) {
      buf3->uids = NULL;
      FreePost (buf3);
    }
  }
  return rsult;
}

static ByteStorePtr NEAR DifferencePostingLists (ByteStorePtr lst1, ByteStorePtr lst2)

{
  PostingPtr    buf1;
  PostingPtr    buf2;
  PostingPtr    buf3;
  Int4          k;
  Int4          k1;
  Int4          k2;
  DocUid        pstar;
  DocUid        qstar;
  ByteStorePtr  rsult;

  ProgMon ("DiffPostingLists");
  rsult = NULL;
  if (lst1 != NULL && lst2 != NULL) {
    buf1 = NewPost (lst1, 0);
    buf2 = NewPost (lst2, 0);
    k1 = PostLength (buf1);
    k2 = PostLength (buf2);
    k = k1 + k2;
    rsult = BSNew (k * sizeof (DocUid));
    buf3 = NewPost (rsult, k * (Int4) sizeof (DocUid));
    if (rsult != NULL && buf1 != NULL && buf2 != NULL && buf3 != NULL) {
      RewindPost (buf1);
      RewindPost (buf2);
      pstar = ReadItem (buf1);
      qstar = ReadItem (buf2);
      while (k > 0) {
        if (pstar < qstar) {
          WriteItem (buf3, pstar);
          k--;
          pstar = ReadItem (buf1);
        } else if (qstar < pstar) {
          k--;
          qstar = ReadItem (buf2);
        } else {
          k -= 2;
          pstar = ReadItem (buf1);
          qstar = ReadItem (buf2);
        }
      }
      FlushItems (buf3);
    } else {
      ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "List is too large to difference");
    }
    if (buf1 != NULL) {
      FreePost (buf1);
    }
    if (buf2 != NULL) {
      FreePost (buf2);
    }
    if (buf3 != NULL) {
      buf3->uids = NULL;
      FreePost (buf3);
    }
  } else if (lst1 != NULL) {
    rsult = lst1;
  }
  return rsult;
}

static ByteStorePtr NEAR FreePostingList (ByteStorePtr lst)

{
  if (lst != NULL) {
    BSFree (lst);
  }
  return NULL;
}

static ByteStorePtr NEAR LoadPostingList (FILE *f, Int4 special, Int4 total)

{
  VoidPtr       bufr;
  Int4          cnt;
  Int4          cntr;
  Int4          k1;
  Int4          k2;
  ByteStorePtr  lst1;
  ByteStorePtr  lst2;
  ByteStorePtr  rsult;

  rsult = NULL;
  if (f != NULL && special >= 0 && total >= 0) {
    bufr = MemNew (MAX_CDENTREZ_BYTESTORE * sizeof (DocUid));
    if (bufr != NULL) {
      k1 = special;
      k2 = total - special;
      lst1 = BSNew (k1 * sizeof (DocUid));
      if (lst1 != NULL) {
        cntr = k1;
        cnt = MIN (k1, (long) MAX_CDENTREZ_BYTESTORE);
        while (cnt > 0) {
          FileRead (bufr, sizeof (DocUid), (size_t) cnt, f);
          BSWrite (lst1, bufr, cnt * sizeof (DocUid));
          cntr -= cnt;
          cnt = MIN (cntr, (long) MAX_CDENTREZ_BYTESTORE);
        }
      } else {
        ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "List is too large to load");
      }
      lst2 = BSNew (k2 * sizeof (DocUid));
      if (lst2 != NULL) {
        cntr = k2;
        cnt = MIN (k2, (long) MAX_CDENTREZ_BYTESTORE);
        while (cnt > 0) {
          FileRead (bufr, sizeof (DocUid), (size_t) cnt, f);
          BSWrite (lst2, bufr, cnt * sizeof (DocUid));
          cntr -= cnt;
          cnt = MIN (cntr, (long) MAX_CDENTREZ_BYTESTORE);
        }
      } else {
        ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "List is too large to load");
      }
      rsult = MergePostingLists (lst1, lst2);
    }
    MemFree (bufr);
  }
  return rsult;
}

/*****************************************************************************
*
*   CdEntrezCreateTerm (term, type, field, special, remainder)
*       Creates a CdTerm node in the entrez set structure if one does not yet
*       exist, and loads the posting file from two ByteStorePtr posting lists.
*
*****************************************************************************/

static void NEAR SavePostingList (FILE *f, ByteStorePtr bsp)

{
  VoidPtr  bufr;
  Int4     cnt;
  Int4     cntr;

  if (f != NULL && bsp != NULL) {
    bufr = MemNew (MAX_CDENTREZ_BYTESTORE * sizeof (DocUid));
    if (bufr != NULL) {
      cntr = (BSLen (bsp) / (Int4) sizeof (DocUid));
      cnt = MIN (cntr, (long) MAX_CDENTREZ_BYTESTORE);
      BSSeek (bsp, 0L, 0);
      while (cnt > 0) {
        BSRead (bsp, bufr, cnt * sizeof (DocUid));
        FileWrite (bufr, sizeof (DocUid), (size_t) cnt, f);
        cntr -= cnt;
        cnt = MIN (cntr, (long) MAX_CDENTREZ_BYTESTORE);
      }
    }
    MemFree (bufr);
  }
}

static CdTermPtr NEAR CdEntrezCreateTerm (CharPtr term, DocType type, DocField field, ByteStorePtr special, ByteStorePtr remainder, CharPtr highRange)

{
  FILE      *fp;
  Boolean   goOn;
  CdTermPtr last;
  Int4      remainderCount;
  Int4      specialCount;
  CdTermPtr trmp;

  trmp = NULL;
  if (eset != NULL && term != NULL) {
    trmp = eset->next;
    last = eset;
    goOn = TRUE;
    while (trmp != NULL && goOn) {
      if (trmp->type == type && trmp->field == field &&
          EqualTerms (trmp->term, term) &&
          EqualTerms (trmp->highRange, highRange)) {
        goOn = FALSE;
      } else {
        last = trmp;
        trmp = trmp->next;
      }
    }
    if (goOn) {
      trmp = MemNew (sizeof (CdTerm));
      if (trmp != NULL) {
        specialCount = 0;
        remainderCount = 0;
        if (special != NULL) {
          specialCount = (BSLen (special) / (Int4) sizeof (DocUid));
        }
        if (remainder != NULL) {
          remainderCount = (BSLen (remainder) / (Int4) sizeof (DocUid));
        }
        trmp->type = type;
        trmp->field = field;
        trmp->term = StringSave (term);
        trmp->special_count = specialCount;
        trmp->total_count = specialCount + remainderCount;
        trmp->highRange = StringSave(highRange);
        trmp->next = NULL;
        last->next = trmp;
        fp = FileOpen (eset->term, "ab");
        if (fp != NULL) {
          fseek (fp, 0, SEEK_END);
          trmp->offset = ftell (fp);
          SavePostingList (fp, special);
          SavePostingList (fp, remainder);
          FileClose (fp);
        } else {
          trmp->offset = 0;
        }
      }
    }
  }
  return trmp;
}

/*****************************************************************************
*
*   FindTermNode (term, type, field, highRange)
*       Returns a pointer to a CdTerm node in the entrez set structure,
*       creating the node and loading the posting file, if necessary.  The
*       value of the offset field becomes the offset into the temporary file.
*
*****************************************************************************/

static CdTermPtr NEAR FindTermNode (CharPtr term, DocType type, DocField field, CharPtr highRange)

{
  FILE      *fp;
  Boolean   goOn;
  CdTermPtr last;
  Int4      offset;
  Int4      remain;
  Int4      special;
  CharPtr   tmp;
  Int4      total;
  CdTermPtr trmp;

  trmp = NULL;
  if (eset != NULL && term != NULL) {
    trmp = eset->next;
    last = eset;
    goOn = TRUE;
    while (trmp != NULL && goOn) {
      if (trmp->type == type && trmp->field == field &&
          EqualTerms (trmp->term, term) &&
          EqualTerms (trmp->highRange, highRange)) {
        goOn = FALSE;
      } else {
        last = trmp;
        trmp = trmp->next;
      }
    }
    if (goOn) {
      tmp = term;
      while (*tmp != '\0')
        tmp++;
      tmp -= 3;
      rangeScanning = FALSE;
      if (highRange != NULL) {
          rangeScanning = TRUE;
          StrNCpy(topOfRange, highRange, sizeof(topOfRange));
          CdEntrezMergeTerm (type, field, term, NULL, NULL, NULL);
      } else {
        if ((*tmp == '.') && (*(tmp+1) == '.') && (*(tmp+2) == '.')) {
          CdEntrezMergeTerm (type, field, term, NULL, NULL, NULL);
        } else if (StringChr (term, '*') != NULL || StringChr (term, '?') != NULL) {
          CdEntrezMergeTerm (type, field, term, NULL, NULL, WildCardProc);
        }
      }
      trmp = eset->next;
      last = eset;
      goOn = TRUE;
      while (trmp != NULL && goOn) {
        if (trmp->type == type && trmp->field == field &&
            EqualTerms (trmp->term, term) &&
            EqualTerms (trmp->highRange, highRange)) {
          goOn = FALSE;
        } else {
          last = trmp;
          trmp = trmp->next;
        }
      }
    }
    if (goOn) {
#ifdef _NEW_CdEntrez_
		if (_nouveau)
			trmp = cd3_CdTrmFind(type,field,term);
#endif
#ifdef _OLD_CdEntrez_
		if (!_nouveau)
			trmp = CdTrmFind(type,field,term);
#endif
      if (trmp != NULL) {
        if (field != FLD_ORGN) {
          last->next = trmp;
          fp = FileOpen (eset->term, "rb");
          if (fp != NULL) {
            fseek (fp, 0, SEEK_END);
            offset = ftell (fp);
            FileClose (fp);
          } else {
            offset = 0;
          }
#ifdef _NEW_CdEntrez_
          if (_nouveau)
            cd3_CdTrmUidsFil (type, field, trmp->offset, trmp->total_count, eset->term, TRUE);
#endif
#ifdef _OLD_CdEntrez_
          if (!_nouveau)
            CdTrmUidsFil (type, field, trmp->offset, trmp->total_count, eset->term, TRUE);
#endif
          trmp->offset = offset;
        } else {
          db = type;
          fld = field;
          uidPtr = MemNew ((size_t) MAX_CDENTREZ_UID_LIST_SIZE);
          if (uidPtr != NULL) {
            scanPtr = MemNew (SCAN_MAX * sizeof (ScanData));
            if (scanPtr != NULL) {
              scanOk = TRUE;
              scanCount = 0;
              specialPost = NULL;
              remainPost = NULL;
              ScanOnlyProc (trmp);
              if (scanCount > 0) {
                ProcessScanResults ();
              }
              if (specialPost != NULL && remainPost != NULL) {
                remainPost = DifferencePostingLists (remainPost, specialPost);
              }
              if (specialPost == NULL) {
                specialPost = BSNew (0);
              }
              if (remainPost == NULL) {
                remainPost = BSNew (0);
              }
              special = BSLen (specialPost) / sizeof (DocUid);
              remain = BSLen (remainPost) / sizeof (DocUid);
              total = special + remain;
              scanPtr = MemFree (scanPtr);
            }
            uidPtr = MemFree (uidPtr);
            if (scanOk && total > 0) {
              trmp = CdTermFree (trmp);
              trmp = CdEntrezCreateTerm (term, db, fld, specialPost, remainPost, highRange);
            }
            specialPost = BSFree (specialPost);
            remainPost = BSFree (remainPost);
          }
        }
      }
    }
  }
  return trmp;
}

/*****************************************************************************
*
*   CdEntrezPreloadMerge (term, type, field, spcl, totl)
*       Creates a CdTerm node in the entrez set structure if one does not yet
*       exist, and loads the posting file by merging multiple postings files.
*
*****************************************************************************/

static void NEAR SingleSpaces (CharPtr str)

{
  Char  ch;
  Int2  i;
  Int2  j;
  Int2  k;

  i = 0;
  j = 0;
  k = 0;
  ch = str [i];
  while (ch != '\0') {
    if (ch == ' ') {
      if (k == 0) {
        str [j] = ch;
        j++;
      }
      k++;
      i++;
    } else {
      k = 0;
      str [j] = ch;
      i++;
      j++;
    }
    ch = str [i];
  }
  str [j] = '\0';
}

static void NEAR TermTruncate (CharPtr str)

{
  if (str != NULL && str [0] != '\0') {
    SingleSpaces (str);
    if (searchTermLen < (Int2) StringLen (str)) {
      str [searchTermLen] = '\0';
    }
  }
}

static int LIBCALLBACK HeapCompare (VoidPtr ptr1, VoidPtr ptr2)

{
  DocUidPtr  uid1;
  DocUidPtr  uid2;

  if (ptr1 != NULL && ptr2 != NULL) {
    uid1 = (DocUidPtr) ptr1;
    uid2 = (DocUidPtr) ptr2;
    if (*uid1 > *uid2) {
      return 1;
    } else if (*uid1 < *uid2) {
      return -1;
    } else {
      return 0;
    }
  } else {
    return 0;
  }
}

static void NEAR QuickSortSmall (DocUidPtr uids, Int4 l, Int4 r)

{
  HeapSort (uids + l, (size_t) (r - l + 1), sizeof (DocUid), HeapCompare);
}

/*
static Boolean NEAR AlreadyInOrder (DocUidPtr uids, Int4 l, Int4 r)

{
  DocUid   last;
  Boolean  rsult;

  rsult = TRUE;
  if (l < r) {
    last = 0;
    while (l <= r) {
      if (uids [l] < last) {
        rsult = FALSE;
      }
      last = uids [l];
      l++;
    }
  }
  return rsult;
}

static void NEAR QuickSortSmall (DocUidPtr uids, Int4 l, Int4 r)

{
  DocUid  a;
  DocUid  b;
  DocUid  c;
  Int4    i;
  Int4    j;
  DocUid  temp;
  DocUid  x;

  if (AlreadyInOrder (uids, l, r)) {
    return;
  }
  i = l;
  j = r;
  a = uids [l];
  b = uids [(l + r) / 2];
  c = uids [r];
  if (a > b) {
    if (c > a) {
      x = a;
    } else if (c < b) {
      x = b;
    } else {
      x = c;
    }
  } else {
    if (c < a) {
      x = a;
    } else if (c > b) {
      x = b;
    } else {
      x = c;
    }
  }
  do {
    while (uids [i] < x) {
      i++;
    }
    while (x < uids [j]) {
      j--;
    }
    if (i <= j) {
      temp = uids [i];
      uids [i] = uids [j];
      uids [j] = temp;
      i++;
      j--;
    }
  } while (i <= j);
  if (i - l < r - j) {
    if (l < j) {
      QuickSortSmall (uids, l, j);
    }
    if (i < r) {
      QuickSortSmall (uids, i, r);
    }
  } else {
    if (i < r) {
      QuickSortSmall (uids, i, r);
    }
    if (l < j) {
      QuickSortSmall (uids, l, j);
    }
  }
}
*/

static Int4 NEAR CompressSmall (DocUidPtr uids, Int4 count)

{
  Int4  i;
  Int4  j;

  i = 0;
  j = 0;
  while (i < count) {
    if (uids [i] > 0) {
      uids [j] = uids [i];
      i++;
      j++;
    } else {
      i++;
    }
  }
  i = j;
  while (j < count) {
    uids [j] = 0;
    j++;
  }
  return i;
}

static Int4 NEAR UniqueSmall (DocUidPtr uids, Int4 count)

{
  Int4    i;
  Int4    j;
  DocUid  last;

  i = 0;
  if (count <= 1) {
    i = count;
  } else {
    i = 0;
    j = 0;
    last = 0;
    while (i < count) {
      if (uids [i] != last) {
        uids [j] = uids [i];
        last = uids [i];
        i++;
        j++;
      } else {
        i++;
      }
    }
    i = j;
    while (j < count) {
      uids [j] = 0;
      j++;
    }
  }
  return i;
}

static ByteStorePtr NEAR MergeSmallLists (ByteStorePtr bsp, ByteStorePtr small)

{
  Int4       count;
  Int4       len;
  DocUidPtr  uids;

  if (small != NULL) {
    len = BSLen (small) / (Int4) sizeof (DocUid);
    if (len <= (long) MAX_CDENTREZ_SMALL_LIST && len > 0) {
      count = (Int4) len;
      uids = MemNew ((size_t) count * sizeof (DocUid));
      if (uids != NULL) {
        BSMerge (small, (VoidPtr) uids);
        small = BSFree (small);
        QuickSortSmall (uids, 0, (Int4) (count - 1));
        count = CompressSmall (uids, count);
        count = UniqueSmall (uids, count);
        if (count > 0) {
          small = BSNew (0L);
          BSWrite (small, uids, count * sizeof (DocUid));
        }
        uids = MemFree (uids);
        if (small != NULL) {
          bsp = MergePostingLists (bsp, small);
        }
      } else {
        ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "MergeSmallLists memory failure");
      }
    } else if (len > (long) MAX_CDENTREZ_SMALL_LIST) {
      ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "MergeSmallLists > %d", MAX_CDENTREZ_SMALL_LIST);
    }
  }
  return bsp;
}

static Boolean NEAR MergeUnorderedLists (Int4 i, Int4 count)

{
  BytePtr       bptr;
  Int4          finish;
  Boolean       goOn;
  Int4          j;
  Int4          len;
  Int4          max;
  DocUidPtr     mptr;
  Int4          number;
  Int4          offset;
  ByteStorePtr  remainLarge;
  ByteStorePtr  remainSmall;
  Int4          smallCount;
  Int4          start;
  Int4          total;

  goOn = TRUE;
  j = i + count - 1;
  max = scanPtr [j].offset + scanPtr [j].totalCount *
        (Int4) sizeof (DocUid) - scanPtr [i].offset;
  if (max <= MAX_CDENTREZ_UID_LIST_SIZE) {
    offset = scanPtr [i].offset;
    len = (Int4) (max / (Int4) sizeof (DocUid));
#ifdef _NEW_CdEntrez_
    if (_nouveau)
      cd3_CdTrmUidsMem (db, fld, offset, (Int4) len, uidPtr);
#endif
#ifdef _OLD_CdEntrez_
    if (!_nouveau)
      CdTrmUidsMem (db, fld, offset, (Int4) len, uidPtr);
#endif
    remainSmall = NULL;
    smallCount = 0;
    for (j = i; j < i + count; j++) {
      scanPtr [j].offset -= offset;
      total = scanPtr [j].totalCount;
      bptr = ((BytePtr) uidPtr) + scanPtr [j].offset;
      mptr = (DocUidPtr) bptr;
      if (smallCount + total > MAX_CDENTREZ_SMALL_LIST) {
        if (remainSmall != NULL) {
          remainPost = MergeSmallLists (remainPost, remainSmall);
          remainSmall = NULL;
        }
        smallCount = 0;
      }
      if (total > 100) {
        start = 0;
        number = 0;
        while (start < total) {
          finish = start + 1;
          while (finish < total && mptr [finish - 1] < mptr [finish]) {
            finish++;
          }
          number = finish - start;
          if (number > 100) {
            remainLarge = BSNew (number * sizeof (DocUid));
            BSWrite (remainLarge, (mptr + start), number * sizeof (DocUid));
            remainPost = MergePostingLists (remainPost, remainLarge);
          } else {
            smallCount += number;
            if (number > 0) {
              if (remainSmall == NULL) {
                remainSmall = BSNew (0L);
              }
              BSWrite (remainSmall, (mptr + start), number * sizeof (DocUid));
            }
            if (smallCount > MAX_CDENTREZ_SMALL_LIST) {
              if (remainSmall != NULL) {
                remainPost = MergeSmallLists (remainPost, remainSmall);
                remainSmall = NULL;
              }
              smallCount = 0;
            }
          }
          start = finish;
        }
      } else {
        smallCount += total;
        if (total > 0) {
          if (remainSmall == NULL) {
            remainSmall = BSNew (0L);
          }
          BSWrite (remainSmall, mptr, total * sizeof (DocUid));
        }
      }
    }
    if (remainSmall != NULL) {
      remainPost = MergeSmallLists (remainPost, remainSmall);
      remainSmall = NULL;
    }
  } else {
    ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "Cannot merge > 32 K element");
    scanOk = FALSE;
    goOn = FALSE;
  }
  return goOn;
}

static Boolean NEAR MergeSeveralOrderedLists (Int4 i, Int4 count)

{
  BytePtr       bptr;
  Boolean       goOn;
  Int4          j;
  Int4          len;
  Int4          max;
  DocUidPtr     mptr;
  Int4          offset;
  Int4          remainder;
  ByteStorePtr  remainLarge;
  ByteStorePtr  remainSmall;
  Int4          smallCount;
  Int4          special;
  ByteStorePtr  specialLarge;
  ByteStorePtr  specialSmall;
  Int4          total;

  goOn = TRUE;
  j = i + count - 1;
  max = scanPtr [j].offset + scanPtr [j].totalCount *
        (Int4) sizeof (DocUid) - scanPtr [i].offset;
  if (max <= MAX_CDENTREZ_UID_LIST_SIZE) {
    offset = scanPtr [i].offset;
    len = (Int4) (max / (Int4) sizeof (DocUid));
#ifdef _NEW_CdEntrez_
    if (_nouveau)
      cd3_CdTrmUidsMem (db, fld, offset, (Int4) len, uidPtr);
#endif
#ifdef _OLD_CdEntrez_
    if (!_nouveau)
      CdTrmUidsMem (db, fld, offset, (Int4) len, uidPtr);
#endif
    specialSmall = NULL;
    remainSmall = NULL;
    smallCount = 0;
    for (j = i; j < i + count; j++) {
      scanPtr [j].offset -= offset;
      special = scanPtr [j].specialCount;
      total = scanPtr [j].totalCount;
      remainder = total - special;
      bptr = ((BytePtr) uidPtr) + scanPtr [j].offset;
      mptr = (DocUidPtr) bptr;
      if (smallCount + total > MAX_CDENTREZ_SMALL_LIST) {
        if (specialSmall != NULL) {
          specialPost = MergeSmallLists (specialPost, specialSmall);
          specialSmall = NULL;
        }
        if (remainSmall != NULL) {
          remainPost = MergeSmallLists (remainPost, remainSmall);
          remainSmall = NULL;
        }
        smallCount = 0;
      }
      if (total > 100) {
        specialLarge = BSNew (special * sizeof (DocUid));
        BSWrite (specialLarge, mptr, special * sizeof (DocUid));
        specialPost = MergePostingLists (specialPost, specialLarge);
        remainLarge = BSNew (remainder * sizeof (DocUid));
        BSWrite (remainLarge, (mptr + special),
                 remainder * sizeof (DocUid));
        remainPost = MergePostingLists (remainPost, remainLarge);
      } else {
        smallCount += total;
        if (special > 0) {
          if (specialSmall == NULL) {
            specialSmall = BSNew (0L);
          }
          BSWrite (specialSmall, mptr, special * sizeof (DocUid));
        }
        if (remainder > 0) {
          if (remainSmall == NULL) {
            remainSmall = BSNew (0L);
          }
          BSWrite (remainSmall, (mptr + special), remainder * sizeof (DocUid));
        }
      }
    }
    if (specialSmall != NULL) {
      specialPost = MergeSmallLists (specialPost, specialSmall);
      specialSmall = NULL;
    }
    if (remainSmall != NULL) {
      remainPost = MergeSmallLists (remainPost, remainSmall);
      remainSmall = NULL;
    }
  } else {
    ErrPostEx (SEV_ERROR, ERR_CD_BOOL, 0, "Cannot merge > %ld element", (long) MAX_CDENTREZ_UID_LIST_SIZE);
    scanOk = FALSE;
    goOn = FALSE;
  }
  return goOn;
}

static Boolean NEAR MergeSeveralLists (Int4 i, Int4 count)

{
  if (fld != FLD_ORGN) {
    return MergeSeveralOrderedLists (i, count);
  } else {
    return MergeUnorderedLists (i, count);
  }
}

static Boolean NEAR ProcessScanResults (void)

{
  Boolean  goOn;
  Int4     i;
  Int4     j;
  Int4     max;

  ProgMon ("ProcessScanResults");
  goOn = TRUE;
  i = 0;
  j = 0;
  max = 0;
  while (j < scanCount) {
    if (scanPtr [j].offset < scanPtr [i].offset) {
      goOn = MergeSeveralLists (i, (Int4) (j - i));
      max = 0;
      i = j;
    } else {
      max = scanPtr [j].offset + scanPtr [j].totalCount *
            (Int4) sizeof (DocUid) - scanPtr [i].offset;
      if (max >= MAX_CDENTREZ_UID_LIST_SIZE) {
        if (j == i) {
          goOn = MergeSeveralLists (i, 1);
          j++;
          i = j;
          max = 0;
        } else {
          goOn = MergeSeveralLists (i, (Int4) (j - i));
          i = j;
          max = 0;
        }
      } else {
        j++;
      }
    }
  }
  if (max > 0) {
    goOn = MergeSeveralLists (i, (Int4) (j - i));
  }
  scanCount = 0;
  return goOn;
}

static Boolean  ScanOnlyProc (CdTermPtr trmp)

{
  Int4     count;
  Boolean  goOn;

  goOn = TRUE;
  if (scanCount >= SCAN_MAX) {
    goOn = ProcessScanResults ();
  }
  if (scanCount < SCAN_MAX) {
    if (trmp->total_count >= CDENTREZ_TERM_MAX) {
      while (trmp->special_count > 0) {
        if (scanCount >= SCAN_MAX) {
          goOn = ProcessScanResults ();
        }
        count = MIN (trmp->special_count, (long) CDENTREZ_TERM_MAX);
        scanPtr [scanCount].specialCount = count;
        scanPtr [scanCount].totalCount = count;
        scanPtr [scanCount].offset = trmp->offset;
        scanPtr [scanCount].specialPtr = NULL;
        scanPtr [scanCount].remainderPtr = NULL;
        scanCount++;
        trmp->special_count -= count;
        trmp->total_count -= count;
        trmp->offset += count * sizeof (DocUid);
      }
      while (trmp->total_count > 0) {
        if (scanCount >= SCAN_MAX) {
          goOn = ProcessScanResults ();
        }
        count = MIN (trmp->total_count, (long) CDENTREZ_TERM_MAX);
        scanPtr [scanCount].specialCount = 0;
        scanPtr [scanCount].totalCount = count;
        scanPtr [scanCount].offset = trmp->offset;
        scanPtr [scanCount].specialPtr = NULL;
        scanPtr [scanCount].remainderPtr = NULL;
        scanCount++;
        trmp->total_count -= count;
        trmp->offset += count * sizeof (DocUid);
      }
    } else {
      if (scanCount >= SCAN_MAX) {
        goOn = ProcessScanResults ();
      }
      scanPtr [scanCount].specialCount = trmp->special_count;
      scanPtr [scanCount].totalCount = trmp->total_count;
      scanPtr [scanCount].offset = trmp->offset;
      scanPtr [scanCount].specialPtr = NULL;
      scanPtr [scanCount].remainderPtr = NULL;
      scanCount++;
    }
  }
  return goOn;
}

static Boolean  WildCardProc (CdTermPtr trmp)

{
  Int4     diff;
  Boolean  goOn;
  CharPtr  src;
  CharPtr  tgt;

  goOn = FALSE;
  src = selection;
  tgt = trmp->term;
  diff = 0;
  while (*src != '\0' && *tgt != '\0' && diff == 0) {
    if (*src != '?') {
      diff = TO_UPPER (*src) - TO_UPPER (*tgt);
    }
    if (diff == 0) {
      src++;
      tgt++;
    }
  }
  if (diff != 0) {
    if (*src == '*') {
      goOn = TRUE;
    }
  } else if (*src == '*') {
    goOn = TRUE;
  } else if (*src == '\0' && *tgt == '\0') {
    goOn = TRUE;
  } else {
    goOn = FALSE;
  }
  return goOn;
}

static Boolean  ScanAndFreeProc (CdTermPtr trmp)

{
  Int4     compare;
  Boolean  goOn;
  Char     str [256];

  goOn = TRUE;
  if (trmp != NULL && trmp->term != NULL) {
    if (rangeScanning) {
      compare = MeshStringICmp (trmp->term, selection);
      if (compare >= 0) {
        if (topOfRange[0] == '\0')
          compare = -1;
        else
          compare = MeshStringICmp (trmp->term, topOfRange);
        if (compare > 0)
          goOn = FALSE;
        else
          goOn = ScanOnlyProc (trmp);
      }
    } else {
      StringNCpy (str, trmp->term, sizeof (str));
      TermTruncate (str);
      if (userScanProc != NULL) {
        compare = MeshStringICmp (str, wildcard);
      } else {
        compare = MeshStringICmp (str, selection);
      }
      if (compare > 0) {
        str [searchTermLen] = '\0';
        if (userScanProc != NULL) {
          compare = MeshStringICmp (str, wildcard);
        } else {
          compare = MeshStringICmp (str, selection);
        }
        if (compare > 0) {
          goOn = FALSE;
        }
      } else if (compare == 0) {
        if (userScanProc != NULL) {
          if (userScanProc (trmp)) {
            goOn = ScanOnlyProc (trmp);
          }
        } else {
          goOn = ScanOnlyProc (trmp);
        }
      }
    }
  }
  trmp = CdTermFree (trmp);
  return goOn;
}

static Boolean NEAR CdEntrezMergeTerm (DocType type, DocField field, CharPtr term,
                                        Int4Ptr spcl, Int4Ptr totl, CdTermProc userProc)

{
  Char  ch;
  Int4  remain;
  Int4  special;
  Char  str [256];
  Int4  total;
  Int4  termpage;
  CharPtr tmp;
  Int4  limit = 0;
  CharPtr prop;
  Boolean retval = FALSE;

  if (spcl != NULL) {
    *spcl = 0;
  }
  if (totl != NULL) {
    *totl = 0;
  }
  db = type;
  fld = field;
  userScanProc = userProc;
  StringNCpy (str, term, sizeof (str));
  tmp = str;
  while (*tmp != '\0') {
    tmp++;
  }
  tmp -= 3;
  if ((*tmp == '.') && (*(tmp+1) == '.') && (*(tmp+2) == '.')) {
    *tmp = '\0';
  }
  SingleSpaces (str);
  if (userProc != NULL) {
    searchTermLen = 0;
    ch = str [searchTermLen];
    while (ch != '\0' && ch != '*' && ch != '?') {
      searchTermLen++;
      ch = str [searchTermLen];
    }
  } else {
    searchTermLen = (Int4) StringLen (str);
  }
  if ((prop = (CharPtr) GetAppProperty("CdEntrezTruncLimit")) != NULL)
  {
    limit = atoi(prop);
  }
  if (searchTermLen > limit || str [0] == '?' || str [0] == '*' ||
      rangeScanning) {
    scanOk = TRUE;
    uidPtr = MemNew ((size_t) MAX_CDENTREZ_UID_LIST_SIZE);
    if (uidPtr != NULL) {
      scanPtr = MemNew (SCAN_MAX * sizeof (ScanData));
      if (scanPtr != NULL) {
        scanCount = 0;
        specialPost = NULL;
        remainPost = NULL;
        StringNCpy (selection, str, sizeof (selection));
        StringNCpy (wildcard, str, sizeof (wildcard));
        wildcard [searchTermLen] = '\0';
#ifdef _NEW_CdEntrez_
		if (_nouveau)
          termpage = cd3_CdTrmLookup (db, fld, wildcard);
#endif
#ifdef _OLD_CdEntrez_
		if (!_nouveau)
          termpage = CdTrmLookup (db, fld, wildcard);
#endif
        if (fld == FLD_MESH) {
          ch = str [0];
          str [0] = TO_UPPER (ch);
        }
        if (termpage >= 0) {
#ifdef _NEW_CdEntrez_
			if (_nouveau)
				cd3_CdTermScan (db, fld, termpage, (Int4)0, ScanAndFreeProc);
#endif
#ifdef _OLD_CdEntrez_
			if (!_nouveau)
				CdTermScan (db, fld, termpage, (Int4)0, ScanAndFreeProc);
#endif
        }
        if (scanCount > 0) {
          ProcessScanResults ();
        }
        if (specialPost != NULL && remainPost != NULL) {
          remainPost = DifferencePostingLists (remainPost, specialPost);
        }
        if (specialPost == NULL) {
          specialPost = BSNew (0);
        }
        if (remainPost == NULL) {
          remainPost = BSNew (0);
        }
        special = BSLen (specialPost) / sizeof (DocUid);
        remain = BSLen (remainPost) / sizeof (DocUid);
        total = special + remain;
        scanPtr = MemFree (scanPtr);
      }
      uidPtr = MemFree (uidPtr);
      if (scanOk && total > 0) {
		retval = TRUE;
		if (userProc == NULL && !rangeScanning) {
			StringCat (str, "...");
		}
        CdEntrezCreateTerm (str, db, fld, specialPost, remainPost, rangeScanning ? topOfRange : NULL);
        if (spcl != NULL) {
          *spcl = special;
        }
        if (totl != NULL) {
          *totl = total;
        }
      }
      specialPost = BSFree (specialPost);
      remainPost = BSFree (remainPost);
    }
  }
  return retval;
}

/*****************************************************************************
*
*   CdEntMedlineEntryListGet (result, numuid, uids, mark_missing)
*   	returns a count of entries read
*   	if (mark_missing) ids which could not be located are made negative
*
*****************************************************************************/
NLM_EXTERN Int2  CdEntMedlineEntryListGet (MedlineEntryPtr PNTR result, Int2 numuid, Int4Ptr uids, Boolean mark_missing)

{
	MedlineEntryPtr mep;
	Int2 count = 0, ctr;
	AsnIoPtr aip;
	DocType db = TYP_ML;

	if (! MedlineAsnLoad())
		return 0;

	for (ctr = 0; ctr < numuid; ctr++)
	{
		mep = NULL;

#ifdef _NEW_CdEntrez_
		if (_nouveau)
			aip = cd3_CdDocAsnOpen(db, uids[ctr]);
#endif
#ifdef _OLD_CdEntrez_
		if (!_nouveau)
			aip = CdDocAsnOpen(db, uids[ctr]);
#endif
		if (aip != NULL)
		{
		 	mep = MedlineEntryAsnRead(aip, NULL);
#ifdef _NEW_CdEntrez_
		 	if (_nouveau)
	 			cd3_CdDocAsnClose(aip);
#endif
#ifdef _OLD_CdEntrez_
		 	if (!_nouveau)
	 			CdDocAsnClose(aip);
#endif
		}
		if (mep == NULL)    /* didn't get it */
		{
			if (mark_missing)
				uids[ctr] *= -1;
		}
		else
		{
			count++;
			result[ctr] = mep;
		}
	}
	
	return count;
}

/*****************************************************************************
*
*   CdEntSeqEntryListGet (result, numuid, uids, retcode, mark_missing)
*   	returns a count of entries read
*   	if (mark_missing) ids which could not be located are made negative
*       retcode is defined in objsset.h 
*
*****************************************************************************/
static AsnIo* CdSeqAsnOpen (DocType *type, DocUid uid, Boolean isGenome);

NLM_EXTERN Int2  CdEntSeqEntryListGet (SeqEntryPtr PNTR result, Int2 numuid, Int4Ptr uids, Int2 retcode, Boolean mark_missing)
{
	SeqEntryPtr sep;
	Int2 count = 0, ctr;
	AsnIoPtr aip;
	DocType db = TYP_SEQ;
	ValNode an;

	if (! SeqSetAsnLoad())
		return 0;

    an.data.intvalue = 0;
    an.choice = SEQID_GI;

	for (ctr = 0; ctr < numuid; ctr++)
	{
		sep = NULL;
		aip = CdSeqAsnOpen(&db, uids[ctr], retcode == -1);
		if (aip != NULL)
		{
			an.data.intvalue = uids[ctr];
			if (retcode == -1)
		 		sep = SeqEntryAsnRead(aip, NULL);
			else
		 		sep = SeqEntryAsnGet(aip, NULL, &an, retcode);
#ifdef _NEW_CdEntrez_
			if (_nouveau)
	 			cd3_CdDocAsnClose(aip);
#endif
#ifdef _OLD_CdEntrez_
			if (!_nouveau)
	 			CdDocAsnClose(aip);
#endif
		}
		if (sep == NULL)    /* didn't get it */
		{
			if (mark_missing)
				uids[ctr] *= -1;
		}
		else
		{
			count++;
			result[ctr] = sep;
		}
	}
	
	return count;
}


static AsnIo* CdSeqAsnOpen (DocType *type, DocUid uid, Boolean isGenome)
{
	AsnIo *aio = NULL;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
	{
		if (isGenome) {
			if ((aio = cd3_CdDocAsnOpen(TYP_CH,uid)) != NULL)
				*type = TYP_CH;
		} else {
			if (*type != TYP_SEQ)
			{
				aio = cd3_CdDocAsnOpen(*type,uid);
			}
			else
			{
				if ((aio = cd3_CdDocAsnOpen(TYP_AA,uid)) != NULL)
					*type = TYP_AA;
				else if ((aio = cd3_CdDocAsnOpen(TYP_NT,uid)) != NULL)
						*type = TYP_NT;
			}
		}
	}
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
		aio = CdDocAsnOpen(*type,uid);
#endif

	return aio;
}

/*****************************************************************************
*
*   CdEntMlSumListGet (result, numuid, uids)
*   	returns a count of entries read
*   	head of linked list is in result
*
*****************************************************************************/

NLM_EXTERN Int2  CdEntMlSumListGet (DocSumPtr PNTR result, Int2 numuid, Int4Ptr uids)          /* Gi numbers */
{
	Int2 count = 0;

#ifdef _NEW_CdEntrez_
	if (_nouveau)
		count = CdDocSumListGet(result,numuid,TYP_ML,uids);
#endif

#ifdef _OLD_CdEntrez_
	if (!_nouveau)
	{
		Int2 ctr;
		DocType db = TYP_ML;
		AsnIoPtr aip;
	
		for (ctr = 0; ctr < numuid; ctr++)
		{
			result[ctr] = NULL;
			aip = CdDocAsnOpen (db, uids[ctr]);
		    if (aip != NULL)
			{
				result[ctr] = MedSumAsnRead(aip, uids[ctr]);
				CdDocAsnClose(aip);
				if (result[ctr] != NULL)
					count++;
			}
		}
	}
#endif
	
	return count;
}


/*****************************************************************************
*
*   CdEntMlSumGet(uid)
*   	get one MlSummary
*
*****************************************************************************/
#ifdef _OLD_CdEntrez_

static DocSumPtr NEAR CdEntMlSumGet (Int4 uid)
{
	DocSumPtr dsp = NULL;

	CdEntMlSumListGet(&dsp, 1, &uid);
	return dsp;
}

#endif

/*****************************************************************************
*
*   void StripAuthor(author)
*
*****************************************************************************/
static void NEAR StripAuthor (CharPtr author)

{
  CharPtr  p1, p2;

  p1 = author;
  while ((p1 = StringChr (p1, ' ')) != NULL) {
    for (p2 = p1 + 1; *p2 != '\0'; p2++) {
      if (*p2 == ' ') break;
      if (IS_ALPHA (*p2) && IS_LOWER (*p2)) break;
    }
    if (*p2 == '\0' || *p2 == ' ') {
      *p1 = '\0';
      return;
    }
    p1++;
  }
}

/*****************************************************************************
*
*   MedSumAsnRead(aip, uid)
*
*****************************************************************************/
static void NEAR FindAsnType (AsnTypePtr PNTR atp, AsnModulePtr amp, CharPtr str)

{
  if (atp != NULL && (*atp) == NULL) {
    *atp = AsnTypeFind (amp, str);
  }
}


static DocSumPtr NEAR MedSumAsnRead (AsnIoPtr aip, DocUid uid)

{
  DataVal       av;
  AsnModulePtr  amp;
  AsnTypePtr    atp;
  Boolean       citFound;
  DocSumPtr     dsp;
  Boolean       goOn;
  Int2          i;
  CharPtr       ptr;
  Char          caption [50];
  Char          author [40];
  Char          year [10];

  if ((aip == NULL) || (! AllObjLoad ()))
    return NULL;

	  amp = AsnAllModPtr ();

	  FindAsnType (&MEDLINE_ENTRY, amp, "Medline-entry");
	  FindAsnType (&MEDLINE_ENTRY_cit, amp, "Medline-entry.cit");
	  FindAsnType (&MEDLINE_ENTRY_abstract, amp, "Medline-entry.abstract");
	  FindAsnType (&TITLE_E_trans, amp, "Title.E.trans");
	  FindAsnType (&AUTH_LIST_names_ml_E, amp, "Auth-list.names.ml.E");
	  FindAsnType (&AUTH_LIST_names_str_E, amp, "Auth-list.names.str.E");
	  FindAsnType (&DATE_STD_year, amp, "Date-std.year");
	  FindAsnType (&DATE_str, amp, "Date.str");
	  FindAsnType (&TITLE_E_name, amp, "Title.E.name");
	  FindAsnType (&MEDLINE_ENTRY_mesh, amp, "Medline-entry.mesh");
	  FindAsnType (&MEDLINE_ENTRY_substance, amp, "Medline-entry.substance");
	  FindAsnType (&MEDLINE_ENTRY_xref, amp, "Medline-entry.xref");
	  FindAsnType (&MEDLINE_ENTRY_idnum, amp, "Medline-entry.idnum");
	  FindAsnType (&MEDLINE_ENTRY_gene, amp, "Medline-entry.gene");

  atp = AsnReadId (aip, amp, MEDLINE_ENTRY);
  AsnReadVal (aip, atp, &av);

  dsp = MemNew (sizeof (DocSum));
  if (dsp != NULL) {
    dsp->no_abstract = TRUE;
    dsp->translated_title = FALSE;
    dsp->no_authors = TRUE;
    author [0] = '\0';
    year [0] = '\0';
    citFound = FALSE;
    goOn = TRUE;
    while (goOn) {
      atp = AsnReadId (aip, amp, atp);
      if (atp == MEDLINE_ENTRY) {
        AsnReadVal (aip, atp, NULL);
        goOn = FALSE;
      } else if (atp == MEDLINE_ENTRY_cit) {
        AsnReadVal (aip, atp, NULL);
        citFound = TRUE;
      } else if (atp == MEDLINE_ENTRY_abstract) {
        AsnReadVal (aip, atp, NULL);
        dsp->no_abstract = FALSE;
        goOn = FALSE;
      } else if (atp == TITLE_E_trans) {
        AsnReadVal (aip, atp, &av);
        dsp->translated_title = TRUE;
        if (dsp->title != NULL) {
          dsp->title = MemFree (dsp->title);
        }
        dsp->title = MemNew ((size_t) StringLen ((CharPtr) av.ptrvalue) + 3);
        ptr = dsp->title;
        *ptr = '[';
        ptr++;
        ptr = StringMove (ptr, (CharPtr) av.ptrvalue);
        *ptr = ']';
        ptr++;
        *ptr = '\0';
        AsnKillValue (atp, &av);
      } else if (atp == AUTH_LIST_names_ml_E) {
        AsnReadVal (aip, atp, &av);
        dsp->no_authors = FALSE;
        if (author [0] == '\0') {
          StringNCpy (author, (CharPtr) av.ptrvalue, sizeof (author));
        }
        AsnKillValue (atp, &av);
      } else if (atp == AUTH_LIST_names_str_E) {
        AsnReadVal (aip, atp, &av);
        dsp->no_authors = FALSE;
        if (author [0] == '\0') {
          StringNCpy (author, (CharPtr) av.ptrvalue, sizeof (author));
        }
        AsnKillValue (atp, &av);
      } else if (atp == DATE_STD_year) {
        AsnReadVal (aip, atp, &av);
        if (citFound) {
          sprintf (year, "%ld", (long) av.intvalue);
        }
      } else if (atp == DATE_str) {
        AsnReadVal (aip, atp, &av);
        if (citFound) {
          i = 0;
          ptr = av.ptrvalue;
          while (ptr [i] != '\0' && ptr [i] != ' ' && i < sizeof (year) - 1) {
            year [i] = ptr [i];
            i++;
          }
          year [i] = '\0';
        }
        AsnKillValue (atp, &av);
      } else if (atp == TITLE_E_name) {
        AsnReadVal (aip, atp, &av);
        if (dsp->title == NULL) {
          dsp->title = StringSave ((CharPtr) av.ptrvalue);
        }
        AsnKillValue (atp, &av);
      } else if (atp == MEDLINE_ENTRY_mesh || atp == MEDLINE_ENTRY_substance ||
                 atp == MEDLINE_ENTRY_xref || atp == MEDLINE_ENTRY_idnum ||
                 atp == MEDLINE_ENTRY_gene) {
        AsnReadVal (aip, atp, NULL);
        goOn = FALSE;
      } else {
        AsnReadVal (aip, atp, NULL);
      }
    }
    if (dsp->no_authors) {
      sprintf (caption, "[%ld], %s", (long) uid, year);
    } else if (author [0] != '\0') {
      StripAuthor (author);
      author [12] = '.';
      author [12] = '\0';
      sprintf (caption, "%s, %s", author, year);
    } else {
      sprintf (caption, "[%ld], %s", (long) uid, year);
    }
    dsp->caption = StringSave (caption);
    dsp->uid = uid;
  }
  AsnIoReset (aip);
  return dsp;
}


/*****************************************************************************
*
*   CdSeqIdForGI(Int4 gi)
*
*****************************************************************************/
NLM_EXTERN SeqIdPtr CdSeqIdForGI (Int4 gi)
{
#ifdef _NEW_CdEntrez_
	DocSum* dsp;
	SeqIdPtr sip = NULL, tmp, next;

	dsp = cd3_CdGetDocSum (TYP_NT, gi);   /* nucleic acid? */
	if (dsp == NULL)
		dsp = cd3_CdGetDocSum (TYP_AA, gi);  /* protein? */
	if (dsp != NULL)
	{
		tmp = SeqIdParse(dsp->extra);
		DocSumFree(dsp);

		while (tmp != NULL)
		{
			next = tmp->next;
			tmp->next = NULL;
			if (tmp->choice == SEQID_GI)
				SeqIdFree(tmp);
			else
				sip = tmp;
			tmp = next;
		}
	}
	return sip;

#else

	SeqIdPtr sip = NULL, ids, curr, best;
	AsnIoPtr aip;
	AsnModulePtr amp;
	AsnTypePtr atp;
	Boolean gotit;
	DocType db = TYP_SEQ;
	GiimPtr gip;

	static Uint1 pick_order[20] = {
 	83, /* 0 = not set */
	65, /* 1 = local Object-id */
	65,  /* 2 = gibbsq */
	65,  /* 3 = gibbmt */
	70, /* 4 = giim Giimport-id */
	60, /* 5 = genbank */
	60, /* 6 = embl */
	60, /* 7 = pir */
	60, /* 8 = swissprot */
	65,  /* 9 = patent */
	65, /* 10 = other TextSeqId */
	65, /* 11 = general Dbtag */
	90,  /* 12 = gi */
	60, /* 13 = ddbj */
	60, /* 14 = prf */
	60,  /* 15 = pdb */
	0,	/* extras for new ids */
	0,
	0,
	0
    };

	if (! AllObjLoad()) return sip;
	amp = AsnAllModPtr();
	FindAsnType (&SEQ_ENTRY, amp, "Seq-entry");
    FindAsnType (&BIOSEQ_id, amp, "Bioseq.id");
    FindAsnType (&BIOSEQ_id_E, amp, "Bioseq.id.E");

	aip = CdSeqAsnOpen (&db, gi, FALSE);
	if (aip == NULL) return sip;

	atp = SEQ_ENTRY;
	while ((atp = AsnReadId(aip, amp, atp)) != NULL)
	{
		if (atp == BIOSEQ_id)
		{
			gotit = FALSE;
		    ids = SeqIdSetAsnRead(aip, atp, BIOSEQ_id_E);
			for (curr = ids; curr != NULL; curr = curr->next)
			{
				if (curr->choice == SEQID_GIIM)
				{
					gip = (GiimPtr)(curr->data.ptrvalue);
					if (gip->id == gi)
					{
						gotit = TRUE;
						break;
					}
				}
				else if (curr->choice == SEQID_GI)
				{
					if (curr->data.intvalue == gi)
					{
						gotit = TRUE;
						break;
					}
				}
			}
			if (gotit)
			{
				best = SeqIdSelect(ids, pick_order, 20);
				sip = ValNodeExtract(&ids, (Int2)(best->choice));
			}
			SeqIdSetFree(ids);
			if (gotit)
				break;

		}
		else
			AsnReadVal(aip, atp, NULL);
		if (! AsnGetLevel(aip))       /* finished reading a Seq-entry */
			break;                    /* failed */
	}
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
	  cd3_CdDocAsnClose(aip);
#endif
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
	  CdDocAsnClose(aip);
#endif

	return sip;
#endif
}



/*****************************************************************************
*
*   CdEntSeqSumListGet (result, numuid, db, uids)
*   	returns a count of entries read
*   	head of linked list is in result
*
*****************************************************************************/

NLM_EXTERN Int2  CdEntSeqSumListGet (DocSumPtr PNTR result, Int2 numuid, DocType db, Int4Ptr uids)          /* Gi numbers */
{
	Int2 count = 0;
	
#ifdef _NEW_CdEntrez_
	if (_nouveau)
	{
		ASSERT(db != TYP_SEQ);
		count = CdDocSumListGet(result,numuid,db,uids);
	}
#endif
	
#ifdef _OLD_CdEntrez_
	if (!_nouveau)
	{
		Int2 ctr;
		AsnIoPtr aip;
	
		for (ctr = 0; ctr < numuid; ctr++)
		{
			result[ctr] = NULL;
			aip = CdDocAsnOpen (db, uids[ctr]);
		    if (aip != NULL)
			{
				result[ctr] = CdSeqSumAsnRead(aip, uids[ctr]);
				CdDocAsnClose(aip);
				if (result[ctr] != NULL)
					count++;
			}
		}
	}
#endif

	return count;
}

/*****************************************************************************
*
*   CdEntSeqSumGet(uid, type)
*   	get one SeqSummary
*
*****************************************************************************/
#ifdef _OLD_CdEntrez_

static DocSumPtr NEAR CdEntSeqSumGet (Int4 uid, DocType type)
{
	DocSumPtr dsp = NULL;

	CdEntSeqSumListGet(&dsp, 1, type, &uid);
	return dsp;
}

#endif

NLM_EXTERN DocSumPtr CdSeqSumAsnRead (AsnIoPtr aip, DocUid uid)

{
  DataVal       av;
  AsnModulePtr  amp;
  AsnTypePtr    atp;
  DocSumPtr     dsp;
  Boolean       goOn;
  Char          caption [50];
  Char          author [40];
  Char          year [10];
  Char          locus [40];
  Char          cds [10];
  CharPtr       chptr;
  Int2          proteins;
  CharPtr       recentTitle;
  Boolean       backbone;
  Boolean       genBank;
  Boolean       embl;
  Boolean       ddbj;
  Boolean       pir;
  Boolean       swissprot;
  Boolean       isaNA;
  Boolean       isaAA;
  Boolean       isaSEG;
  Boolean		in_id;
  Int2          level;

  if ((aip == NULL) || (! AllObjLoad ()))
    return NULL;

  amp = AsnAllModPtr ();

  FindAsnType (&SEQ_ENTRY, amp, "Seq-entry");
  FindAsnType (&SEQ_ENTRY_seq, amp, "Seq-entry.seq");
  FindAsnType (&SEQ_ENTRY_set, amp, "Seq-entry.set");
  FindAsnType (&TEXTSEQ_ID_name, amp, "Textseq-id.name");
  FindAsnType (&TEXTSEQ_ID_accession, amp, "Textseq-id.accession");
  FindAsnType (&AUTH_LIST_names_str_E, amp, "Auth-list.names.str.E");
  FindAsnType (&DATE_STD_year, amp, "Date-std.year");
  FindAsnType (&DATE_str, amp, "Date.str");
  FindAsnType (&SEQ_DESCR_E_title, amp, "Seq-descr.E.title");
  FindAsnType (&GIIMPORT_ID_id, amp, "Giimport-id.id");
  FindAsnType (&BIOSEQ_inst, amp, "Bioseq.inst");
  FindAsnType (&SEQ_INST_mol, amp, "Seq-inst.mol");
  FindAsnType (&SEQ_INST_repr, amp, "Seq-inst.repr");
  FindAsnType (&SEQ_ID_gibbsq, amp, "Seq-id.gibbsq");
  FindAsnType (&SEQ_ID_gibbmt, amp, "Seq-id.gibbmt");
  FindAsnType (&SEQ_ID_genbank, amp, "Seq-id.genbank");
  FindAsnType (&SEQ_ID_gi, amp, "Seq-id.gi");
  FindAsnType (&SEQ_ID_embl, amp, "Seq-id.embl");
  FindAsnType (&SEQ_ID_ddbj, amp, "Seq-id.ddbj");
  FindAsnType (&SEQ_ID_pir, amp, "Seq-id.pir");
  FindAsnType (&SEQ_ID_swissprot, amp, "Seq-id.swissprot");
  FindAsnType (&PDB_BLOCK_compound_E, amp, "PDB-block.compound.E");
  FindAsnType (&PDB_SEQ_ID_MOL, amp, "PDB-seq-id.mol");
  FindAsnType (&BIOSEQ_id, amp, "Bioseq.id");
  FindAsnType (&CIT_PAT_title, amp, "Cit-pat.title");

  atp = AsnReadId (aip, amp, SEQ_ENTRY);
  AsnReadVal (aip, atp, &av);

  atp = AsnReadId (aip, amp, atp);
  AsnReadVal (aip, atp, &av);

  dsp = MemNew (sizeof (DocSum));
  if (dsp != NULL) {
    dsp->no_abstract = TRUE;
    dsp->translated_title = FALSE;
    dsp->no_authors = TRUE;
    author [0] = '\0';
    year [0] = '\0';
    locus [0] = '\0';
    cds [0] = '\0';
    proteins = 1;
    recentTitle = NULL;
    backbone = FALSE;
    genBank = FALSE;
    embl = FALSE;
	ddbj = FALSE;
    pir = FALSE;
    swissprot = FALSE;
    isaNA = FALSE;
    isaAA = FALSE;
    isaSEG = FALSE;
	in_id = FALSE;
    goOn = TRUE;
    level = AsnGetLevel (aip);
    while (goOn) {
      atp = AsnReadId (aip, amp, atp);
      if (atp == SEQ_ENTRY_seq || atp == SEQ_ENTRY_set) {
        AsnReadVal (aip, atp, NULL);
        if (AsnGetLevel (aip) <= level) {
          goOn = FALSE;
	    }
      } else if (atp == BIOSEQ_id) {
        AsnReadVal (aip, atp, &av);
		if (in_id) {
			in_id = FALSE;
		} else {
			in_id = TRUE;
        }
      } else if (in_id && ((atp == TEXTSEQ_ID_name) ||
 	  		(atp == PDB_SEQ_ID_MOL))) {
        AsnReadVal (aip, atp, &av);
        if (locus [0] == '\0') {
          StringNCpy (locus, (CharPtr) av.ptrvalue, sizeof (locus));
        }
        AsnKillValue (atp, &av);
      } else if (in_id && (atp == TEXTSEQ_ID_accession)) {
        AsnReadVal (aip, atp, &av);
        if (locus [0] == '\0') {
          StringNCpy (locus, (CharPtr) av.ptrvalue, sizeof (locus));
        }
        AsnKillValue (atp, &av);
      } else if (atp == AUTH_LIST_names_str_E) {
        AsnReadVal (aip, atp, &av);
        if (author [0] == '\0') {
          StringNCpy (author, (CharPtr) av.ptrvalue, sizeof (author));
        }
        AsnKillValue (atp, &av);
      } else if (atp == DATE_STD_year) {
        AsnReadVal (aip, atp, &av);
        sprintf (year, "%ld", (long) av.intvalue);
      } else if (atp == DATE_str) {
        AsnReadVal (aip, atp, &av);
        StringNCpy (year, (CharPtr) av.ptrvalue, sizeof (year));
        AsnKillValue (atp, &av);
      } else if ((atp == SEQ_DESCR_E_title) ||
 	  	(atp == PDB_BLOCK_compound_E) || (atp == CIT_PAT_title)) {
        AsnReadVal (aip, atp, &av);
		if (*((CharPtr)av.ptrvalue) != '\0')
		{
	        if (recentTitle != NULL) {
    	      recentTitle = MemFree (recentTitle);
        	}

	        if (dsp->uid == uid && dsp->title == NULL &&
				atp != CIT_PAT_title) {
    	      dsp->title = (CharPtr)av.ptrvalue;
	        }
			else
				recentTitle = (CharPtr)av.ptrvalue;
		}
		else
	        AsnKillValue (atp, &av);
      } else if (atp == GIIMPORT_ID_id || atp == SEQ_ID_gi) {
        AsnReadVal (aip, atp, &av);
        if (av.intvalue == uid) {
          dsp->uid = uid;
        }
      } else if (atp == SEQ_INST_mol) {
        AsnReadVal (aip, atp, &av);
        if ((! isaNA) && (! isaAA) && dsp->uid == uid) {
          isaNA = (Boolean) ISA_na (av.intvalue);
          isaAA = (Boolean) ISA_aa (av.intvalue);
          if (isaAA && cds [0] == '\0') {
            sprintf (cds, " cds%d", (int) proteins);
          }
        }
        if (ISA_aa (av.intvalue)) {
          proteins++;
        }
      } else if (atp == SEQ_INST_repr) {
        AsnReadVal (aip, atp, &av);
        if (av.intvalue == Seq_repr_seg) {
          isaSEG = TRUE;
        }
      } else if (atp == BIOSEQ_inst) {
        AsnReadVal (aip, atp, NULL);
        if (dsp->uid == uid && dsp->title == NULL) {
          dsp->title = recentTitle;
          recentTitle = NULL;
        }
      } else if (atp == SEQ_ID_gibbsq || atp == SEQ_ID_gibbmt) {
        AsnReadVal (aip, atp, NULL);
        backbone = TRUE;
      } else if (atp == SEQ_ID_genbank) {
        AsnReadVal (aip, atp, NULL);
		if (in_id)
	        genBank = TRUE;
      } else if (atp == SEQ_ID_embl) {
        AsnReadVal (aip, atp, NULL);
		if (in_id)
	        embl = TRUE;
      } else if (atp == SEQ_ID_ddbj) {
        AsnReadVal (aip, atp, NULL);
		if (in_id)
	        ddbj = TRUE;
      } else if (atp == SEQ_ID_pir) {
        AsnReadVal (aip, atp, NULL);
		if (in_id)
	        pir = TRUE;
      } else if (atp == SEQ_ID_swissprot) {
        AsnReadVal (aip, atp, NULL);
		if (in_id)
	        swissprot = TRUE;
      } else {
        AsnReadVal (aip, atp, NULL);
      }
      if (dsp->title != NULL && dsp->uid == uid) {
        if (backbone) {
          if (author [0] != '\0' && year [0] != '\0') {
            goOn = FALSE;
          }
        } else if (genBank || embl || ddbj) {
          if (locus [0] != '\0') {
            if (isaAA && cds [0] != '\0') {
              goOn = FALSE;
            } else if (isaNA) {
              goOn = FALSE;
            }
          }
        } else if (pir) {
          if (locus [0] != '\0') {
            goOn = FALSE;
          }
        } else if (swissprot) {
          if (locus [0] != '\0') {
            goOn = FALSE;
          }
        } else if (embl) {
        }
      }
    }
    if (backbone) {
      chptr = StringChr (author, ',');
      if (chptr != NULL) {
        *chptr = '\0';
      }
      chptr = StringChr (year, ' ');
      if (chptr != NULL) {
        *chptr = '\0';
      }
      author [12] = '.';
      author [12] = '\0';
      sprintf (caption, "%s, %s", author, year);
      dsp->caption = StringSave (caption);
    } else if (genBank || embl || ddbj) {
      if (isaAA) {
        sprintf (caption, "%s%s", locus, cds);
      } else if (isaSEG) {
        sprintf (caption, "%s segs", locus);
      } else {
        sprintf (caption, "%s", locus);
      }
      dsp->caption = StringSave (caption);
    } else {
      sprintf (caption, "%s", locus);
      dsp->caption = StringSave (caption);
    }
    dsp->uid = uid;
    if (recentTitle != NULL) {
      recentTitle = MemFree (recentTitle);
    }
  }
  AsnIoReset (aip);
  return dsp;
}

/*****************************************************************************
*
*   CdEntrezFindSeqId(sip)
*       given a Seq-id, get the uid.
*       returns 0 on failure
*
*****************************************************************************/
NLM_EXTERN Int4 CdEntrezFindSeqId (SeqIdPtr sip)
{
    Int4 uid = 0;
    DocType db = -1;
    TextSeqIdPtr tsip;
    PDBSeqIdPtr psip;
    PatentSeqIdPtr patsip;
    CharPtr locus = NULL;
    Char localbuf[40];
    ValNodePtr lst;
    LinkSetPtr lsp;
    Boolean check_both, done;
    EntrezInfoPtr eip;
    Int4 index;

    if ((eip = CdEntrezGetInfo()) != NULL && eip->field_count > FLD_SQID &&
	eip->types[TYP_NT].fields[FLD_SQID].num_terms > 0)
    {
        done = FALSE;
        check_both = TRUE;
	db = TYP_NT;
	SeqIdWrite(sip, localbuf, PRINTID_FASTA_LONG, sizeof(localbuf));
        while (! done)     /* might need to check 2 types */
        {
            lst = CdEntTLNew(db);
            if (lst == NULL) return uid;
            CdEntTLAddTerm(lst, localbuf, db, FLD_SQID, TRUE, NULL);
            lsp = CdEntTLEval(lst);
            CdEntTLFree(lst);
            if (lsp != NULL)
            {
                for (index = 0; index < lsp->num; index++)
		{ /* choose the highest one */
		    if (lsp->uids[index] > uid)
                        uid = lsp->uids[index];
		}
                LinkSetFree(lsp);
            }
            if ((! check_both) || (uid > 0))
                done = TRUE;
            else
            {
                if (db == TYP_AA)
                    db = TYP_NT;
                else
                    db = TYP_AA;
                check_both = FALSE;
            }
        }
    }

    if (uid > 0)
    {
	return uid;
    }

    check_both = FALSE;
    switch (sip->choice)
    {
        case SEQID_NOT_SET:           /* not set */
        case SEQID_LOCAL:           /* local */
            break;
        case SEQID_GIBBSQ:           /* gibbsq */
        case SEQID_GIBBMT:           /* gibbmt */
            sprintf(localbuf, "B%ld", (long)(sip->data.intvalue));
            locus = (CharPtr)localbuf;
            db = TYP_AA;   /* guess it's a protein */
            check_both = TRUE;
            break;             /* not on cdrom */
        case SEQID_GIIM:           /* giim */
            uid = ((GiimPtr)sip->data.ptrvalue)->id;
            break;
        case SEQID_GI:
            uid = sip->data.intvalue;
            break;
        case SEQID_GENBANK:             /* genbank */
        case SEQID_EMBL:                /* embl */
        case SEQID_DDBJ:
            db = TYP_NT;   /* guess it's a nucleic acid */
            check_both = TRUE;
        case SEQID_PIR:             /* pir */
        case SEQID_SWISSPROT:
        case SEQID_PRF:
            if (db < 0)
                db = TYP_AA;
            tsip = (TextSeqIdPtr)sip->data.ptrvalue;
            if (tsip->accession != NULL)
                locus = tsip->accession;
            else
                locus = tsip->name;
            break;
        case SEQID_PDB:
            psip = (PDBSeqIdPtr)(sip->data.ptrvalue);
            if (psip->chain == '\0' || psip->chain == ' ')
                StrCpy (localbuf, psip->mol);
	    else
                sprintf(localbuf, "%s-%c", psip->mol, (Char)psip->chain);
            locus = localbuf;
            db = TYP_AA;   /* guess protein */
            check_both = TRUE;
            break;
        case SEQID_PATENT:
            patsip = (PatentSeqIdPtr)(sip->data.ptrvalue);
            sprintf(localbuf, "%s%s %d", patsip->cit->country, patsip->cit->number,
                (int)patsip->seqid);
            locus = localbuf;
            db = TYP_AA;   /* guess protein */
            check_both = TRUE;
            break;
        default:
            break;
    }

    if ((! uid) && (locus != NULL))   /* got a term to find */
    {
        done = FALSE;
        while (! done)     /* might need to check 2 types */
        {
            lst = CdEntTLNew(db);
            if (lst == NULL) return uid;
            CdEntTLAddTerm(lst, locus, db, FLD_ACCN, TRUE, NULL);
            lsp = CdEntTLEval(lst);
            CdEntTLFree(lst);
            if (lsp != NULL)
            {
                for (index = 0; index < lsp->num; index++)
		{ /* choose the highest one */
		    if (lsp->uids[index] > uid)
                        uid = lsp->uids[index];
		}
                LinkSetFree(lsp);
            }
            if ((! check_both) || (uid > 0))
                done = TRUE;
            else
            {
                if (db == TYP_AA)
                    db = TYP_NT;
                else
                    db = TYP_AA;
                check_both = FALSE;
            }
        }
    }

    return uid;
}

#ifdef Biostruc_supported
NLM_EXTERN BiostrucPtr CdEntrezBiostrucGet (DocUid uid, Int4 mdlLvl, Int4 maxModels)
{
	Biostruc *struc = NULL;
	AsnIo *stream = NULL;

	if (! BiostrucAvail ()) return NULL;
	stream = cd3_CdDocAsnOpen(TYP_ST,uid);
	if (stream != NULL)
	{
		struc = BiostrucAsnGet(stream,NULL, mdlLvl, maxModels);
		cd3_CdDocAsnClose(stream);
	}
	return struc;
}


#ifdef OS_UNIX

NLM_EXTERN BiostrucAnnotSetPtr CdEntrezBiostrucAnnotSetGet (DocUid uid)
{
	BiostrucAnnotSetPtr retval = NULL;
	AsnIoPtr  aip;
	FILE *pipe;
	char command[PATH_MAX+5];
	char fname[PATH_MAX];
	
	if (CdMountEntrezVolume(1,fname,PATH_MAX-32))
	{
		sprintf(strchr(fname,0), "/vast/%ld.bas.Z", (long) uid);
		if (FileLength(fname) <= 0)
		{
			return NULL;
		}
		sprintf(command,"zcat %s", fname);
		if ((pipe=popen(command,"r")) ==NULL)
		{
			ErrPostEx(SEV_ERROR,0,0,"Unable to open pipe [%s]",command);
			return NULL;
		}
		aip = AsnIoNew(ASNIO_TEXT_IN, pipe, NULL, NULL, NULL);
		if (aip != NULL)
		{
			retval = BiostrucAnnotSetAsnRead(aip, NULL);
		}
		AsnIoFree(aip,FALSE);
		pclose(pipe);
	}
	return retval;
}

#else

NLM_EXTERN BiostrucAnnotSetPtr CdEntrezBiostrucAnnotSetGet (DocUid uid)
{
	return NULL;
}

#endif


NLM_EXTERN BiostrucAnnotSetPtr LIBCALL CdEntrezBiostrucAnnotSetGetByFid (DocUid mmdbid, Int4 feature_id, Int4 feature_set_id)
{
    BiostrucAnnotSetPtr basp = CdEntrezBiostrucAnnotSetGet (mmdbid);
    BiostrucAnnotSetPtr basp2 = NULL;
    BiostrucFeatureSetPtr pbsfs = NULL;
    BiostrucFeaturePtr pbsf = NULL;

    if (basp == NULL)
	return NULL;
 
    pbsfs = basp->features;
    while (pbsfs)
     {
       if (pbsfs->id == feature_set_id)
        {
          pbsf =  pbsfs->features;
          while(pbsf)
            {
              if (pbsf->id == feature_id)
                {  /* found it */
                     basp2 = BiostrucAnnotSetNew();
     		     basp2->id = basp->id;
    		     basp2->descr = basp->descr; 
    		     basp->descr = NULL;  /* unlink the descr from basp object */
    		     basp2->features = BiostrucFeatureSetNew();
                     basp2->features->id = pbsfs->id;
                     basp2->features->descr = pbsfs->descr;
                     pbsfs->descr = NULL; /* unlink the feature-set descr from basp  object */
                     basp2->features->features = BiostrucFeatureNew();
                     basp2->features->features->id = pbsf->id;
                     basp2->features->features->name = StringSave(pbsf->name);
		     basp2->features->features->type = pbsf->type;
		     basp2->features->features->Property_property = pbsf->Property_property;
		     pbsf->Property_property = NULL; /* unlink the property from basp  object */
		     basp2->features->features->Location_location = pbsf->Location_location;
		     pbsf->Location_location = NULL; /* unlink the location from basp  object */ 
		     BiostrucAnnotSetFree(basp);
                     return basp2;
                }
               pbsf = pbsf->next;
            }
        }
       pbsfs = pbsfs->next;
     }
   
    BiostrucAnnotSetFree(basp);
    return basp2;
}


NLM_EXTERN LinkSetPtr LIBCALL CdEntrezBiostrucFeatIds(DocUid mmdbid, Int2 feature_type, Int4 feature_set_id)
{
    BiostrucAnnotSetPtr basp = CdEntrezBiostrucAnnotSetGet (mmdbid);
    LinkSetPtr retval = NULL;
    Int4Ptr ids = NULL;
    Int4Ptr scores = NULL;
    Int4 count = 0;
    BiostrucFeatureSetPtr pbsfs = NULL;
    BiostrucFeaturePtr pbsf = NULL;
    ChemGraphAlignmentPtr  pcga = NULL;
    
    
    if (basp == NULL)
	return NULL;
    
    /* count the number of features of type feature_type */
    pbsfs = basp->features;
    while (pbsfs)
     {
       if (pbsfs->id == feature_set_id)
        {
          pbsf =  pbsfs->features;
          while(pbsf)
            {
              if (pbsf->type == feature_type)
                { 
		   count++;
                }
               pbsf = pbsf->next;
            }
        }
       pbsfs = pbsfs->next;
     }
    
     /* allocate vectors for ids, scores iff alignment data */
   
    ids = (Int4Ptr) MemNew(sizeof(Int4) * count);
    if (feature_type == 200) /* NCBI alignments */
      scores = (Int4Ptr) MemNew(sizeof(Int4) * count);
    
    count = 0;   
    /* collect the feature-id's and scores  */
    pbsfs = basp->features;
    while (pbsfs)
     {
       if (pbsfs->id == feature_set_id)
        {
          pbsf =  pbsfs->features;
          while(pbsf)
            {
              if (pbsf->type == feature_type)
                {
		  
		   ids[count] = pbsf->id;
		   if (feature_type == 200) /* alignment type id */
		    {
		     pcga = (ChemGraphAlignmentPtr) pbsf->Location_location->data.ptrvalue;
		     scores[count] = pcga->aligndata->vast_mlogp;  /* an Int4 already */
		    }
		   count++;
                }
               pbsf = pbsf->next;
            }  /* while feature */
          retval = LinkSetNew();
          retval->num = count;
          retval->uids = ids;
          retval->weights = scores;
          MemFree(basp);
          return retval;
        }  /* if feature_set_id */
       pbsfs = pbsfs->next;
     }  /* while feature_set */
  MemFree(basp);
  return NULL;
}
#endif /* Biostruc_supported */