summaryrefslogtreecommitdiff
path: root/api/objmgr.c
blob: eaba72d1ba2e11e6e63994c9f06891211dc7f4ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
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
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
/*  objmgr.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.   
*
* ===========================================================================
*
* File Name:  objmgr.c
*
* Author:  James Ostell
*   
* Version Creation Date: 9/94
*
* $Revision: 6.52 $
*
* File Description:  Manager for Bioseqs and BioseqSets
*
* Modifications:  
* --------------------------------------------------------------------------
* $Log: objmgr.c,v $
* Revision 6.52  2004/04/21 19:40:51  kans
* ObjMgrReap calculate tempcnt based on temp loaded records, but excluded locked ones - more work still to do in other functions to completely avoid unnecessary thrashing
*
* Revision 6.51  2004/04/01 13:43:05  lavr
* Spell "occurred", "occurrence", and "occurring"
*
* Revision 6.50  2003/12/22 15:29:28  kans
* ObjMgrSendMsg calls SeqMgrClearFeatureIndexes on OM_MSG_DEL as well as OM_MSG_UPDATE
*
* Revision 6.49  2002/07/30 14:41:45  kans
* removed omdp->rearranged
*
* Revision 6.48  2002/07/29 21:30:17  kans
* added rearranged flag to omdp
*
* Revision 6.47  2002/07/01 14:29:02  kans
* changed totobj, currobj to Uint4
*
* Revision 6.46  2002/06/07 21:24:57  kans
* update entityID/omdp index in BioseqReloadFunc, ObjMgrConnectFunc, ObjMgrDetachFunc
*
* Revision 6.45  2002/06/01 05:52:00  vakatov
* Fix to R6.44 -- add LIBCALL and NLM_EXTERN modifiers to match the func proto
*
* Revision 6.44  2002/05/31 21:53:26  yaschenk
* changing lookup by EntityID to array[][]
*
* Revision 6.43  2001/12/13 13:59:14  kans
* ObjMgrSendMsg clears feature indexes if OM_MSG_UPDATE
*
* Revision 6.42  2001/11/30 12:19:47  kans
* ObjMgrDelete bails if omdp->bulkIndexFree
*
* Revision 6.41  2001/11/19 15:27:52  kans
* minor fix to ObjMgrDeleteAllInRecord
*
* Revision 6.40  2001/11/19 15:26:19  kans
* added ObjMgrDeleteAllInRecord, still need to bail in ObjMgrDelete if bulkIndexFree, then call from BioseqFree and BioseqSetFree
*
* Revision 6.39  2001/11/15 18:15:48  kans
* set bsp->omdp at creation, SeqMgrDeleteIndexesInRecord sets omdp->bulkIndexFree
*
* Revision 6.38  2001/10/02 12:22:57  kans
* ObjMgrRecordOmdpByEntityID for quick access to top omdp by entity
*
* Revision 6.37  2001/05/31 22:58:25  kans
* added ObjMgrReapOne, DEFAULT_MAXOBJ, autoclean reaps and frees one entity at a time, as needed
*
* Revision 6.36  2001/05/31 22:33:02  kans
* added autoclean and maxobj to ObjMgr structure, ObjMgrAddFunc optionally calls ObjMgrReap and ObjMgrFreeCache to completely clear out least recently accessed objects if currobj >= maxobj
*
* Revision 6.35  2001/05/24 21:54:34  kans
* check for incrementing totobj or currobj above UINT2_MAX, reducing currobj below 0
*
* Revision 6.34  2001/02/16 21:34:49  ostell
* changed GetSecs() to ObjMgrTouchCnt() to reduce system calls
*
* Revision 6.33  2000/11/28 22:58:08  kans
* removed omdp->lockcnt == 0 debugging breakpoint statement
*
* Revision 6.32  2000/11/28 21:43:54  kans
* added ObjMgrReportFunc for debugging
*
* Revision 6.31  2000/10/30 21:26:08  shavirin
* Changes and fixes for some MT-safety related problems.
*
* Revision 6.30  2000/03/27 23:10:23  kans
* initial readlock/lookup/unlock removed from ObjMgrDelete by request of EY
*
* Revision 6.29  2000/03/23 17:45:44  madden
* Use ObjMgrWriteLock instead of ObjMgrReadLock in ObjMgrFreeCache
*
* Revision 6.28  2000/03/20 23:38:40  aleksey
* Finally submitted the changes which have been made by serge bazhin
* and been kept in my local directory.
*
* These changes allow to establish user callback functions
* in 'Asn2ffJobPtr' structure which are called within
* 'SeqEntryToFlatAjp' function call.
* The new members are:
* user_data       - pointer to a user context for passing data
* ajp_count_index - user defined function
* ajp_print_data  - user defined function
* ajp_print_index - user defined function
*
* Revision 6.27  1999/10/20 17:17:37  lewisg
* delete rest of userdata when using OM_OPT_FREE_IF_NO_VIEW in ObjMgrFreeUserDataFunc
*
* Revision 6.26  1999/10/18 20:58:47  lewisg
* add rowID to ObjMgrSendMsgFunc
*
* Revision 6.25  1999/09/27 20:03:14  kans
* added rowID to OMMsgStruct, new ObjMgrSendRowMsg function
*
* Revision 6.24  1999/08/13 19:43:35  kans
* ObjMgrDelete and ObjMgrGetEntityIDForPointer now multithread-safe (EY)
*
* Revision 6.23  1999/08/11 15:17:53  kans
* added ObjMgrFreeByEntityID
*
* Revision 6.22  1999/06/11 16:42:39  kans
* remove from recycle just shrinks stack if removing last element
*
* Revision 6.21  1999/06/10 21:10:28  kans
* added ObjMgrRemoveEntityIDFromRecycle, called from RestoreSeqEntryObjMgrData
*
* Revision 6.20  1999/06/01 21:06:48  ywang
* get rid of (sip1->strand == sip2->strand) in ObjMgrRegionMatch
*
* Revision 6.19  1999/05/17 02:11:23  chappey
* remove the temporary fix
*
* Revision 6.18  1999/05/17 00:41:54  chappey
* temporary fix in ObjMgrRegionComp when SeqLocStop==APPEND_RESIDUE
*
* Revision 6.17  1999/02/19 19:24:34  chappey
* Possible deselection of a region included in a selected region
*
* Revision 6.16  1999/01/22 16:19:51  chappey
* AlsoSelect does not Deselect anymore when selected region of an entityID is already selected. Only one selection remains
*
* Revision 6.15  1999/01/21 19:45:32  chappey
* bug fixed in ObjMgrSelectFunc2, CheckRedondantSelect, ObjMgrRegionComp
*
* Revision 6.14  1998/12/02 01:56:24  kans
* when recycling entityID, check to see if it is already in list, do not add second copy - will see why this is happening later
*
* Revision 6.13  1998/11/30 20:59:01  egorov
* Add ObjMgrNextAvailableEntityID() to avoid overflowing
*
* Revision 6.12  1998/10/07 22:25:43  kans
* reapextra, like freeextra, takes omdp, not omdp->extradata
*
* Revision 6.11  1998/10/07 21:20:14  kans
* ObjMgrAlsoSelect changes (CC)
*
* Revision 6.10  1998/09/28 19:54:10  kans
* made ObjMgrDump debugging function public, no longer conditionally compiled
*
* Revision 6.9  1998/08/18 14:57:02  kans
* protect against nulls in ObjMgrRegionMatch
*
* Revision 6.8  1998/07/01 19:11:45  kans
* added fromProcID, toProcID, OM_MSG_PROCESS, ObjMgrSendProcMsg, time of indexing, ObjMgrGetProcID, moved protFeat and cdsOrRnaFeat to seqmgr structure
*
* Revision 6.7  1998/06/26 23:01:24  kans
* ObjMgrDelete frees extra data
*
* Revision 6.6  1998/06/02 16:53:27  kans
* fixed bug that prevented userdata from being freed, and decrement highest entity if attaching highest to something else
*
* Revision 6.5  1997/12/11 14:37:28  ostell
* corrected a deadlock with DeSelectRegion
*
* Revision 6.4  1997/12/05 16:42:42  ostell
* added objmgrunlock() around "Free if no views"
*
* Revision 6.3  1997/11/22 16:49:57  ostell
* fixed deadlock in ObjMgrReap
*
* Revision 6.2  1997/11/19 22:14:35  ostell
* added support for multithreaded programs
*
* Revision 6.1  1997/09/11 15:55:45  ostell
* Added support for SetColor messages
*
* Revision 6.0  1997/08/25 18:06:43  madden
* Revision changed to 6.0
*
* Revision 5.9  1997/08/01 14:12:19  ostell
* put check for time_t being signed int back into ObjMgrReap for Solaris
*
* Revision 5.8  1997/07/31 16:06:07  kans
* ObjMgrReap lowest time uses UINT4_MAX because of overflow of the number of seconds since 1900
*
* Revision 5.7  1997/07/25 21:31:20  ostell
* free if no view now checks that omudp->messagefunc != NULL instead of checking
* all of them.
*
* Revision 5.6  1997/06/19 18:38:27  vakatov
* [WIN32,MSVC++]  Adopted for the "NCBIOBJ.LIB" DLL'ization
*
* Revision 5.5  1997/06/02 17:04:09  kans
* added ObjMgrProcLoadEx
*
* Revision 5.4  1997/04/29 16:11:30  kans
* send deselect message AFTER removing item from list of selected items
*
 * Revision 5.3  1997/01/22  05:29:46  ostell
 * made objmgrget static
 * made seqmgrget static
 *
 * Revision 5.2  1996/07/30  21:18:15  chappey
 * don't return FALSE in ObjMgrSetTempLoad when index == 0
 *
 * Revision 5.1  1996/06/26  20:07:48  chappey
 * ObjMgrRegionMatch now returs TRUE when the regions are identical
 *
 * Revision 5.0  1996/05/28  13:23:23  ostell
 * Set to revision 5.0
 *
 * Revision 4.14  1996/05/22  21:46:59  kans
 * don't return on OBJ_MSG_RET_DONE in ObjMgrSendStructMsgFunc
 *
 * Revision 4.13  1996/03/05  19:15:01  kans
 * fixed bug in ObjMgrSetOptions and ObjMgrClearOptions
 *
 * Revision 4.12  1996/02/28  04:53:06  ostell
 * added ObjMgrHold suport
 *
 * Revision 4.10  1996/01/22  13:28:11  kans
 * cast first parameter of MemSet to (Pointer) for SunOS compiler
 *
 * Revision 4.9  1996/01/05  14:39:12  ostell
 * fix for control chars in comment
 *
 * Revision 4.7  1995/12/22  20:12:01  ostell
 * added lock in ObjMgrTempLoad to protect new record from ObjMgrReap
 *
 * Revision 4.6  1995/12/22  14:45:45  ostell
 * added do_not_reload_from_cache to OmProcControl so that DataGet
 * functions from gather can control this behvior
 * added protection from recursion in ObjMgrDelete
 *
 * Revision 4.5  1995/12/15  02:47:01  ostell
 * fix to ObjMgrReap so highest time_t is INT4_MAX not UINT4_MAX to compensate
 * for buggy include files from vendors
 *
 * Revision 4.4  1995/10/03  15:50:37  ostell
 * added support for selection by region.. now fully implemented
 *
 * Revision 4.3  1995/10/02  14:36:55  ostell
 * fixed ObjMgrFreeUserData to get options from omp or omdp
 *
 * Revision 4.2  1995/09/30  03:38:31  ostell
 * Changed ObjMgrMessage functions to pass a structure
 * Added support for selecting regions
 * Added ability to remove entity when no more views on it
 *
 * Revision 4.1  1995/09/25  18:06:41  ostell
 * added ObjMgrGenericAsnTextRead
 *
 * Revision 4.0  1995/07/26  13:49:01  ostell
 * force revision to 4.0
 *
 * Revision 1.25  1995/07/20  18:30:32  kans
 * changed SeqIdPrint to SeqIdWrite
 *
 * Revision 1.24  1995/07/08  15:21:01  ostell
 * Added ObjMgrSetOptions() and related functions
 * Added support for delete of entity when no more user data on it
 * Added support for DirtyFlag
 *
 * Revision 1.23  1995/05/15  21:46:05  ostell
 * added Log line
 *
*
*
* ==========================================================================
*/

/** for ErrPostEx() ****/

static char *this_module = "ncbiapi";
#define THIS_MODULE this_module
static char *this_file = __FILE__;
#define THIS_FILE this_file

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

#include <objmgr.h>		   /* the interface */
#include <objsset.h>       /* temporary for caching functions */
#include <ncbithr.h>       /* for thread safe functions */
#include <sequtil.h>
#include <explore.h>       /* for SeqMgrClearFeatureIndexes */

/***
#define DEBUG_OBJMGR
***/

#define OBJMGR_MAX UINT4_MAX


/*****************************************************************************
*
*   Data Object local functions
*
*****************************************************************************/
static Uint4 NEAR ObjMgrTouchCnt PROTO((void));
static Boolean NEAR ObjMgrExtend PROTO((ObjMgrPtr omp));
static ObjMgrDataPtr NEAR ObjMgrFindByEntityID PROTO((ObjMgrPtr omp, Uint2 entityID, ObjMgrDataPtr PNTR prev));
static Boolean NEAR ObjMgrFreeClipBoardFunc PROTO((ObjMgrPtr omp));
static Boolean NEAR ObjMgrFreeCacheFunc PROTO((ObjMgrPtr omp, Uint2 type, Uint2Ptr rettype, VoidPtr PNTR retval));
static Boolean NEAR ObjMgrAddFunc PROTO((ObjMgrPtr omp, Uint2 type, Pointer data));
static Boolean NEAR ObjMgrFreeUserDataFunc PROTO((ObjMgrPtr omp, Uint2 entityID,
								Uint2 procid, Uint2 proctype, Uint2 userkey));
static Int4 NEAR ObjMgrLockFunc (ObjMgrPtr omp, Uint2 type, Pointer data, Boolean lockit);
/*****************************************************************************
*
*   Procedure Management local Functions
*
*****************************************************************************/
static Boolean NEAR ObjMgrProcExtend PROTO((ObjMgrPtr omp));

/*****************************************************************************
*
*   Type Management Local functions
*
*****************************************************************************/
static Boolean NEAR ObjMgrTypeExtend PROTO((ObjMgrPtr omp));

/*****************************************************************************
*
*   Messaging/Selection local functions
*
*****************************************************************************/
static Boolean NEAR ObjMgrSendMsgFunc PROTO((ObjMgrPtr omp, ObjMgrDataPtr omdp,
				Int2 msg, Uint2 entityID, Uint2 itemID,	Uint2 itemtype, Uint2 rowID,
				Uint2 fromProcID, Uint2 toProcID, Pointer procmsgdata));
static Boolean NEAR ObjMgrSendStructMsgFunc PROTO((ObjMgrPtr omp, ObjMgrDataPtr omdp,
				OMMsgStructPtr ommsp));
static SelStructPtr NEAR ObjMgrAddSelStruct PROTO((ObjMgrPtr omp,
	 Uint2 entityID, Uint2 itemID, Uint2 itemtype, Uint1 regiontype, Pointer region));
static Boolean NEAR ObjMgrSelectFunc PROTO((ObjMgrPtr omp, Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region));
static Boolean NEAR ObjMgrDeSelectFunc PROTO((ObjMgrPtr omp, Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region));
static Boolean NEAR ObjMgrDeSelectStrucFunc PROTO((ObjMgrPtr omp, SelStructPtr ssp));
static Boolean NEAR ObjMgrDeSelectAllFunc PROTO((ObjMgrPtr omp));
static Boolean NEAR ObjMgrRegionMatch PROTO((Uint1 regiontype1, Pointer region1,
						Uint1 regiontype2, Pointer region2));
static Pointer NEAR ObjMgrRegionCopy PROTO((ObjMgrPtr omp, Uint1 regiontype, Pointer region));
static Pointer NEAR ObjMgrRegionFree PROTO((ObjMgrPtr omp, Uint1 regiontype, Pointer region));
static Pointer NEAR ObjMgrMemCopyFunc PROTO((ObjMgrPtr omp, Uint2 type, Pointer ptr, Boolean unlock));
static Pointer NEAR ObjMgrFreeFunc PROTO((ObjMgrPtr omp, Uint2 type, Pointer ptr, Boolean unlock));

/*****************************************************************************
*
*   ObjMgr Functions
*
*****************************************************************************/
static TNlmMutex omctr_mutex = NULL;
static Uint4 NEAR ObjMgrTouchCnt (void)
{
	static Uint4 ObjMgrTouchCtr = 1; /* start at 1 to avoid rollover signal */
	Int4 ret, imax, i;
	ObjMgrPtr omp;
	ObjMgrDataPtr PNTR omdpp;
	Uint4 tmpctr;

	if (! ObjMgrTouchCtr)  /* rolled over */
	{
		ret = NlmMutexLockEx(&omctr_mutex); /* protect this section */
		if (ret)  /* error */
		{
			ErrPostEx(SEV_FATAL,0,0,"ObjMgrTouchCnt failed [%ld]", (long)ret);
			return ObjMgrTouchCtr;
		}
		
		/**** reset the touch values *****/
		/** all calls to this function should already have ObjMgrWriteLock **/

		if (! ObjMgrTouchCtr) /* check that this was not a stalled thread */
		{
			tmpctr = 0;
			omp = ObjMgrGet();
			imax = omp->currobj;
			omdpp = omp->datalist;
			for (i = 0; i < imax; i++)
			{
				if (omdpp[i]->parentptr == NULL)
					omdpp[i]->touch = ++tmpctr;
			}
			ObjMgrTouchCtr = tmpctr;
		}
		NlmMutexUnlock(omctr_mutex);
	}

	return ++ObjMgrTouchCtr;

}

NLM_EXTERN ObjMgrDataPtr LIBCALL ObjMgrGetData (Uint2 entityID)
{
	ObjMgrDataPtr prev, retval=NULL;
	ObjMgrPtr omp;

	omp = ObjMgrReadLock();
	retval = ObjMgrFindByEntityID (omp, entityID, &prev);
	ObjMgrUnlock();
	return retval;
}

NLM_EXTERN ObjMgrDataPtr LIBCALL ObjMgrGetDataStruct (ObjMgrPtr omp, Uint2 entityID)
{
	ObjMgrDataPtr prev;

	return ObjMgrFindByEntityID (omp, entityID, &prev);
}

/* cache to avoid linear search of all objects in ObjMgrFindByEntityID */

#define TOP_ID_STACK_SIZE  100

static Uint2 topEntityIDs [TOP_ID_STACK_SIZE];
static ObjMgrDataPtr topOMDPs [TOP_ID_STACK_SIZE];
static Int2  topIDStackPt = 0;

extern void ObjMgrRecordOmdpByEntityID (Uint2 entityID, ObjMgrDataPtr omdp);
extern void ObjMgrRecordOmdpByEntityID (Uint2 entityID, ObjMgrDataPtr omdp)

{
	Int2  i;

	if (entityID < 1) return;

	/* check for preexisting entry, update */

	for (i = 0; i < topIDStackPt; i++) {
		if (entityID == topEntityIDs [i]) {
			topOMDPs [i] = omdp; /* record in stack */
			if (omdp == NULL) { /* remove if null */
				if (topIDStackPt > i + 1) {
					topIDStackPt--;
					topEntityIDs [i] = topEntityIDs [topIDStackPt];
					topOMDPs [i] = topOMDPs [topIDStackPt];
				} else {
					topIDStackPt--;
				}
			}
			return;
		}
	}

	/* add if not found */

	if (omdp == NULL) return;
	if (topIDStackPt < TOP_ID_STACK_SIZE) {
		topEntityIDs [topIDStackPt] = entityID;
		topOMDPs [topIDStackPt] = omdp;
		topIDStackPt++;
	}
	ObjMgrAddIndexOnEntityID(NULL,entityID,omdp);
}

static ObjMgrDataPtr NEAR ObjMgrFindByEntityID (ObjMgrPtr omp, Uint2 entityID, ObjMgrDataPtr PNTR prev)
{
	ObjMgrDataPtr omdp, prevptr=NULL;
	ObjMgrDataPtr PNTR omdpp;
	Int4 i, imax;

	/* check cache first to avoid linear search through all objects */
	if((omdp=ObjMgrLookupIndexOnEntityID(omp,entityID)) != NULL) return omdp;

	for (i = 0; i < topIDStackPt; i++) {
		if (entityID == topEntityIDs [i]) {
			omdp = topOMDPs [i];
			if (omdp != NULL && omdp->parentptr == NULL && omdp->EntityID == entityID) {
				if (prev != NULL)
					*prev = prevptr;
				return omdp;
			}
		}
	}

	imax = omp->currobj;
	omdpp = omp->datalist;
	for (i = 0; i < imax; i++)
	{
		omdp = omdpp[i];    /* emptys always at end */
		if (omdp->parentptr == NULL)
		{
			if (omdp->EntityID == entityID)
			{
				if (prev != NULL)
					*prev = prevptr;
				return omdp;
			}
		}
	}
	return NULL;
}

NLM_EXTERN ObjMgrDataPtr LIBCALL ObjMgrFindByData (ObjMgrPtr omp, Pointer ptr)
{
	ObjMgrDataPtr omdp;
	ObjMgrDataPtr PNTR omdpp;
	Int4 i, imax;
	
	if (ptr == NULL) return NULL;

	imax = omp->currobj;
	omdpp = omp->datalist;

	i = ObjMgrLookup(omp, ptr);   /* find by binary search on dataptr? */
	if (i >= 0)
		return omdpp[i];          /* found it */

	for (i = 0; i < imax; i++)
	{
		omdp = omdpp[i];    /* emptys always at end */
		if ((Pointer)(omdp->choice) == ptr)
		{
			return omdp;
		}
	}
	return NULL;
}

#define ENTITY_ID_STACK_SIZE  100

static Uint2 recycledEntityIDs [ENTITY_ID_STACK_SIZE];
static Int4  recycledIDStackPt = 0;

extern void ObjMgrRemoveEntityIDFromRecycle (Uint2 entityID, ObjMgrPtr omp);
extern void ObjMgrRemoveEntityIDFromRecycle (Uint2 entityID, ObjMgrPtr omp)

{
	Int4  i;

	if (entityID < 1) return;
	if (omp != NULL) {
		for (i = 0; i < recycledIDStackPt; i++) {
			if (entityID == recycledEntityIDs [i]) {
				recycledEntityIDs [i] = 0; /* remove from recycle list */
				if (recycledIDStackPt > i + 1) {
					recycledIDStackPt--;
					recycledEntityIDs [i] = recycledEntityIDs [recycledIDStackPt];
				} else {
					recycledIDStackPt--;
				}
			}
		}
	}
}

static Uint2 ObjMgrNextAvailEntityID (ObjMgrPtr omp)

{
	Uint2      entityID = 0;
	if (omp != NULL) {
		if (recycledIDStackPt > 0) {
			recycledIDStackPt--;
			entityID = recycledEntityIDs [recycledIDStackPt];
		} else {
			entityID = ++(omp->HighestEntityID);
		}
	}
	return entityID;
}

static void ObjMgrRecycleEntityID (Uint2 entityID, ObjMgrPtr omp)

{

	Int4  i;

	if (entityID < 1) return;
	if (omp != NULL) {
		/* check to see if entity is already on stack (e.g., entity 1), abort if so */
		for (i = 0; i < recycledIDStackPt; i++) {
			if (entityID == recycledEntityIDs [i]) return;
		}
		if (recycledIDStackPt < ENTITY_ID_STACK_SIZE) {
			recycledEntityIDs [recycledIDStackPt] = entityID;
			recycledIDStackPt++;
		}
	}
}

NLM_EXTERN Uint2 LIBCALL ObjMgrAddEntityID (ObjMgrPtr omp, ObjMgrDataPtr omdp)
{
	if (omdp == NULL) return 0;

	if (omdp->EntityID)
	   return omdp->EntityID;

	/* omdp->EntityID = ++(omp->HighestEntityID); */
	omdp->EntityID = ObjMgrNextAvailEntityID (omp);
	ObjMgrRecordOmdpByEntityID (omdp->EntityID, omdp);

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrAddEntityID-A");
#endif

	ObjMgrSendMsgFunc(omp, omdp, OM_MSG_CREATE, omdp->EntityID, 0, 0, 0, 0, 0, NULL);

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrAddEntityID-B");
#endif

	return omdp->EntityID;
}
static Boolean NEAR ObjMgrSendMsgFunc (ObjMgrPtr omp, ObjMgrDataPtr omdp,
				Int2 msg, Uint2 entityID, Uint2 itemID,	Uint2 itemtype, Uint2 rowID,
				Uint2 fromProcID, Uint2 toProcID, Pointer procmsgdata)
{
	OMMsgStruct omms;

	MemSet((Pointer)(&omms), 0, sizeof(OMMsgStruct));

	omms.message = msg;
	omms.entityID = entityID;
	omms.itemID = itemID;
	omms.itemtype = itemtype;
	omms.fromProcID = fromProcID;
	omms.toProcID = toProcID;
	omms.procmsgdata = procmsgdata;
    omms.rowID = rowID;
	
	return ObjMgrSendStructMsgFunc (omp, omdp, &omms);
}

/*********************************************************************
*
*   ObjMgrSendStructMsgFunc()
*   This function actually sends the messages to registered proceedures.
*   It has to unlock the objmgr so the proceedures can read or write the
*   objmgr. This is risky, but I am not sure how to do this safer. It does
*   keep an array of messages to send before it unlocks anything, in case
*   the message list changes from a callback. This imposes a fixed limit to 
*   the number of messages that can be sent at once to MAXMSG. This may become
*   a problem.
*
*********************************************************************/
static Boolean NEAR ObjMgrSendStructMsgFunc (ObjMgrPtr omp, ObjMgrDataPtr omdp,
				OMMsgStructPtr ommsp)
{
#define MAXMSG 250  /* max number of messages to save */
	OMUserDataPtr prev=NULL, curr, next, PNTR root, msgs[MAXMSG], omudp;
	Int2 retval;
	Int2 ctr, nummsg, i;
	Boolean is_write_locked, too_many, done;

	is_write_locked = omp->is_write_locked;   /* remember state */
	nummsg = 0;      /* no messages known yet */
	  
	                  /*****************************************
					  *  First find all messages to send while locked
					  *****************************************/
	curr = omp->userdata;
	root = &(omp->userdata);
	ctr = 2;
	too_many = FALSE;
	while ((ctr) && (! too_many))
	{
		prev = NULL;
		while ((curr != NULL) && (! too_many))
		{
			next = curr->next;
			if (curr->messagefunc != NULL)
			{
				if (ommsp->toProcID == 0 || ommsp->toProcID == curr->procid) {
					if (nummsg < MAXMSG)
					{
						msgs[nummsg] = curr;
						nummsg++;
					}
					else
						too_many = TRUE;
				}
			}
			curr = next;
		}

		if (omdp == NULL)
			ctr -= 2;
		else if (ctr == 2)
		{
			ctr--;
			curr = omdp->userdata;
			root = &(omdp->userdata);
		}
		else
			ctr--;
	}

	if (too_many)
	{
		ErrPostEx(SEV_ERROR,0,0,"ObjMgrSendMessage: more than %d messages",
			(int)nummsg);
	}



                      /*****************************************
					  *  now send the messages confirming that each
					  *    still exists
					  *****************************************/

	for (i = 0; i < nummsg; i++)
	{
		omudp = msgs[i];
		done = FALSE;
	curr = omp->userdata;
	root = &(omp->userdata);
	ctr = 2;
	while ((ctr) && (! done))
	{
		prev = NULL;
		while ((curr != NULL) && (! done))
		{
			next = curr->next;
			if (curr == omudp)
			{
			  done = TRUE;   /* found this one */
			  if (curr->messagefunc != NULL)
			  {
				ommsp->omuserdata = (Pointer)curr;

				ObjMgrUnlock();   /* have to allow message to react */
				retval = (* (curr->messagefunc))(ommsp);
				if (is_write_locked)
					ObjMgrWriteLock();
				else
					ObjMgrReadLock();

				if (retval == OM_MSG_RET_ERROR)
					ErrShow();
				else if (retval == OM_MSG_RET_DEL)
				{
					if (prev == NULL)
						*root = next;
					else
						prev->next = next;
					if (curr->freefunc != NULL)
						(* (curr->freefunc))(curr->userdata.ptrvalue);
					MemFree(curr);
				}
			  }
			}
			curr = next;
		}

		if (omdp == NULL)
			ctr -= 2;
		else if (ctr == 2)
		{
			ctr--;
			curr = omdp->userdata;
			root = &(omdp->userdata);
		}
		else
			ctr--;
	  }
	}
	return TRUE;

}
/*****************************************************************************
*
*   Return the current ObjMgr
*   	ObjMgrGet is obsolete
*       ObjMgrReadLock, ReadUnlock, WriteLock, WriteUnlock are thread safe
*
*****************************************************************************/
static TNlmMutex omp_mutex = NULL;
static ObjMgrPtr global_omp = NULL;
static TNlmRWlock omp_RWlock = NULL;

/*****************************************************************************
*
*   Return the current ObjMgr
*   	Initialize if not done already
*       This function will become obsolete
*
*****************************************************************************/
NLM_EXTERN ObjMgrPtr LIBCALL ObjMgrGet (void)
{
	Int4 ret;
	ObjMgrPtr omp;

	if (global_omp != NULL)
		return global_omp;

	ret = NlmMutexLockEx(&omp_mutex);  /* protect this section */
	if (ret)  /* error */
	{
		ErrPostEx(SEV_FATAL,0,0,"ObjMgrGet failed [%ld]", (long)ret);
		return NULL;
	}

	if (global_omp == NULL)  /* check again after mutex */
	{
	                             /*** have to initialize it **/
		omp = (ObjMgrPtr) MemNew (sizeof(ObjMgr));
		omp->maxtemp = DEFAULT_MAXTEMP;
		omp->maxobj = DEFAULT_MAXOBJ;
		omp_RWlock = NlmRWinit();  /* initialize RW lock */
		global_omp = omp;       /* do this last for mutex safety */
	}

	NlmMutexUnlock(omp_mutex);

	return global_omp;
}

/*****************************************************************************
*
*   ObjMgrReadLock()
*   	Initialize if not done already
*       A thread can have only one read or write lock at a time
*       Many threads can have read locks
*       Only one thread can have a write lock
*       No other threads may have read locks if a write lock is granted
*       If another thread holds a write lock, this call blocks until write
*          is unlocked.
*
*****************************************************************************/
NLM_EXTERN ObjMgrPtr LIBCALL ObjMgrReadLock (void)
{
	ObjMgrPtr omp;
	Int4 ret;

	omp = ObjMgrGet();  /* ensure initialization */

        ret = NlmRWrdlock(omp_RWlock); 
	/* ret = NlmRWwrlock(omp_RWlock); */

	if (ret != 0)
	{
		ErrPostEx(SEV_ERROR,0,0,"ObjMgrReadLock: RWrdlock error [%ld]",
			(long)ret);
		return NULL;
	}

	omp->is_write_locked = TRUE;

	return omp;
}

/*****************************************************************************
*
*   ObjMgrWriteLock
*   	Initialize if not done already
*       A thread can have only one read or write lock at a time
*       Many threads can have read locks
*       Only one thread can have a write lock
*       No other threads may have read locks if a write lock is granted
*       If another thread holds a read or write lock, this call blocks until write
*          is unlocked.
*
*****************************************************************************/
NLM_EXTERN ObjMgrPtr LIBCALL ObjMgrWriteLock (void)
{
	ObjMgrPtr omp;
	Int4 ret;

	omp = ObjMgrGet();  /* ensure initialization */

	ret = NlmRWwrlock(omp_RWlock);
	if (ret != 0)
	{
		ErrPostEx(SEV_ERROR,0,0,"ObjMgrWriteLock: RWwrlock error [%ld]",
			(long)ret);
		return NULL;
	}
	omp->is_write_locked = TRUE;
	return omp;
}


/*****************************************************************************
*
*  ObjMgrUnlock()
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrUnlock (void)
{
	ObjMgrPtr omp;
	Int4 ret;

	omp = ObjMgrGet();  /* ensure initialization */

	ret = NlmRWunlock(omp_RWlock);
	if (ret != 0)
	{
		ErrPostEx(SEV_ERROR,0,0,"ObjMgrUnlock: RWunlock error [%ld]",
			(long)ret);
		return FALSE;
	}
	omp->is_write_locked = FALSE;  /* can't be write locked */
	return TRUE;
}




/*****************************************************************************
*
*   ObjMgrSetOptions(Uint2 option, Uint2 entityID)
*     Sets options on the ObjMgr. All Options are 1 bit flags set with
*       defines. Several Options may be ORed together.
*       returns current options.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrSetOptions (Uint2 option, Uint2 entityID)
{
	ObjMgrPtr omp;
	Uint2Ptr optionptr;
	ObjMgrDataPtr omdp, prev;

	omp = ObjMgrGet();
	if (entityID == 0)
		optionptr = &(omp->options);
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, &prev);
		if (omdp == NULL)
			return 0;
		optionptr = &(omdp->options);
	} 
	*optionptr |= (option & 0xFFFF);
	return *optionptr;
}

/*****************************************************************************
*
*   ObjMgrClearOptions(Uint2 option, Uint2 entityID)
*     Clears options on the ObjMgr. All Options are 1 bit flags set with
*       defines. Several Options may be ORed together.
*       returns current options.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrClearOptions (Uint2 option, Uint2 entityID)
{
	ObjMgrPtr omp;
 	Uint2Ptr optionptr;
	ObjMgrDataPtr omdp, prev;


	omp = ObjMgrGet();
	if (entityID == 0)
		optionptr = &(omp->options);
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, &prev);
		if (omdp == NULL)
			return 0;
		optionptr = &(omdp->options);
	} 
	*optionptr &= ~(option & 0xFFFF);
	return *optionptr;
}

/*****************************************************************************
*
*   ObjMgrGetOptions(entityID)
*     Returns options on the ObjMgr. All Options are 1 bit flags set with
*       defines. Several Options may be ORed together.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrGetOptions (Uint2 entityID)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp, prev;
	Uint2 retval = 0;

	omp = ObjMgrReadLock();
	if (entityID == 0)
		 retval = omp->options;
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, &prev);
		if (omdp != NULL)
			retval = omdp->options;
	}
	ObjMgrUnlock();
	return retval; 
}

/*****************************************************************************
*
*   ObjMgrTestOptions(Uint2 option)
*     Tests options on the ObjMgr. All Options are 1 bit flags set with
*       defines. Several Options may be ORed together.
*       returns TRUE if ANY flags in "option" are set in the ObjMgr.
*       Normally one would supply only 1 option to test. If many were to
*       be tested, use ObjMgrGetOptions()
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrTestOptions (Uint2 option, Uint2 entityID)
{
	ObjMgrPtr omp;
	Uint2Ptr optionptr;
	ObjMgrDataPtr omdp, prev;
	Boolean retval = FALSE;

	omp = ObjMgrReadLock();
	if (entityID == 0)
		optionptr = &(omp->options);
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, &prev);
		if (omdp == NULL)
			goto erret;
		optionptr = &(omdp->options);
	}
	
	if (*optionptr & (option & 0xFFFF))
		retval = TRUE;
erret:

	ObjMgrUnlock();

	return retval;
}

/*****************************************************************************
*
*   ObjMgrSetHold()
*     Increments hold count in ObjMgr
*       returns current hold count
*     if hold != 0, then no tempload records are cached out of memory
*     This is useful if you are doing a complex task involving repeated
*      access to many records and you want them to stay in memory while
*      the task is performed, even though they are loaded temporarily by
*      BioseqLock..
*     Be sure to call ObjMgrClearHold() when you are done so they can be
*      cached out.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrSetHold (void)
{
	ObjMgrPtr omp;

	omp = ObjMgrWriteLock();

	if (omp->hold < OBJMGR_MAX)
		omp->hold++;
	else
		ErrPostEx(SEV_ERROR,0,0, "ObjMgrSetHold: hold > OBJMGR_MAX");
	ObjMgrUnlock();
	return omp->hold;
}

/*****************************************************************************
*
*   ObjMgrClearHold()
*     Decrements hold count in ObjMgr
*       returns current hold count
*       will never decrement below 0
*     if hold == 0, then tempload records will be cached out of memory
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrClearHold (void)
{
	ObjMgrPtr omp;

	omp = ObjMgrWriteLock();

	if (omp->hold)
	{
		omp->hold--;
		if (! (omp->hold))  /* down to 0 */
			ObjMgrReap(omp);
	}
	else
		ErrPostEx(SEV_ERROR,0,0, "ObjMgrClearHold: hold = 0");
	ObjMgrUnlock();
	return omp->hold;
}

/*****************************************************************************
*
*   ObjMgrCheckHold()
*       returns current hold count
*     if hold == 0, then tempload records will be cached out of memory
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrCheckHold (void)
{
	ObjMgrPtr omp;

	omp = ObjMgrReadLock();
	ObjMgrUnlock();
	return omp->hold;
}



/*****************************************************************************
*
*   Data Management Functions
*
*****************************************************************************/


/*****************************************************************************
*
*   ObjMgrExtend(omp)
*
*****************************************************************************/
static Boolean NEAR ObjMgrExtend (ObjMgrPtr omp)
{
	Boolean result = FALSE;
	OMDataPtr omdp, prev=NULL;
	ObjMgrDataPtr PNTR tmp;
	Int4 i, j;

	for (omdp = omp->ncbidata; omdp != NULL; omdp = omdp->next)
		prev = omdp;

	omdp = (OMDataPtr)MemNew(sizeof(OMData));
	if (omdp == NULL) return result;
	tmp = (ObjMgrDataPtr PNTR)MemNew((size_t)(sizeof(ObjMgrDataPtr) * (omp->totobj + NUM_OMD)));
	if (tmp == NULL)
	{
		MemFree(omdp);
		return result;
	}

	if (prev != NULL)
	{
		prev->next = omdp;
		MemMove(tmp, omp->datalist, (size_t)(sizeof(ObjMgrDataPtr) * omp->totobj));
		MemFree(omp->datalist);
	}
	else
		omp->ncbidata = omdp;

	j = omp->totobj;

	for (i = 0; i < NUM_OMD; i++, j++)
		tmp[j] = &(omdp->data[i]);

	if (omp->totobj < OBJMGR_MAX - NUM_OMD)
		omp->totobj += NUM_OMD;
	else
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrExtend: incrementing totobj above OBJMGR_MAX");
	omp->datalist = tmp;

	result = TRUE;
	return result;
}
/*****************************************************************************
*
*   ObjMgrAdd(type, data)
*   	adds a pointer (data) of type (type) to the sequence manager
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrAdd (Uint2 type, Pointer data)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	retval = ObjMgrAddFunc(omp, type, data);
	ObjMgrUnlock();
	return retval;
}


/*****************************************************************************
*
*   ObjMgrAddFunc(omp, type, data)
*   	adds a pointer (data) of type (type) to the sequence manager
*
*****************************************************************************/
static Boolean NEAR ObjMgrAddFunc (ObjMgrPtr omp, Uint2 type, Pointer data)
{
	ObjMgrDataPtr omdp;
	ObjMgrDataPtr PNTR omdpp;
	Int4 i, imin, imax;
	Boolean retval = FALSE;
	unsigned long tmp, datai;
	BioseqPtr bsp;
#ifdef DEBUG_OBJMGR
	FILE * fp;

	fp = FileOpen("ObjMgr.log", "a");
#endif

	/* if autoclean is set and above maxobj, remove least recently accessed objects */
	if (omp->autoclean && omp->currobj >= omp->maxobj) {
		ObjMgrReapOne (omp);
		ObjMgrFreeCache (0);
	}

	if (omp->currobj >= omp->totobj)
	{
		if (! ObjMgrExtend(omp))
			goto erret;
	}

	i = omp->currobj;
	omdpp = omp->datalist;
	omdp = omdpp[i];    /* emptys always at end */
	omdp->options = omp->options;   /* set default options */

	imin = 0;                   /* find where it goes */
	imax = omp->currobj-1;

	datai = (unsigned long)data;

	if ((i) && (datai < (unsigned long)(omdpp[imax]->dataptr)))
	{
		i = (imax + imin) / 2;
		while (imax > imin)
		{
			tmp = (unsigned long)(omdpp[i]->dataptr);
#ifdef DEBUG_OBJMGR
			fprintf(fp, "Sort: i=%d tmp=%ld data=%ld imax=%d imin=%d\n",
				(int)i, (long)tmp, (long)data, (int)imax, (int)imin);
#endif
			if (tmp > datai)
				imax = i - 1;
			else if (tmp < datai)
				imin = i + 1;
			else
				break;
			i = (imax + imin)/2;
		}

#ifdef DEBUG_OBJMGR
			fprintf(fp, "End: i=%d tmp=%ld data=%ld imax=%d imin=%d\n",
				(int)i, (long)tmp, (long)data, (int)imax, (int)imin);
#endif
		if (datai > (unsigned long)(omdpp[i]->dataptr)) /* check for off by 1 */
		{
			i++;
#ifdef DEBUG_OBJMGR
			fprintf(fp, "Adjust: i=%d\n", (int)i);
#endif
		}


		imax = omp->currobj - 1;	 /* open the array */
		while (imax >= i)
		{
			omdpp[imax+1] = omdpp[imax];
			imax--;
		}
	}

	omdpp[i] = omdp;    /* put in the pointer in order */
	if (omp->currobj < OBJMGR_MAX)
		omp->currobj++;     /* got one more */
	else
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrAddFunc: incrementing currobj above OBJMGR_MAX");

	omdp->dataptr = data;  /* fill in the values */
	omdp->datatype = type;
	omdp->touch = ObjMgrTouchCnt();   /* stamp with time */

	if (type == OBJ_BIOSEQ) {
		bsp = (BioseqPtr) data;
		if (bsp != NULL) {
			/* used for feature indexing, rapid delete from SeqID index */
			bsp->omdp = (Pointer) omdp;
		}
	}

#ifdef DEBUG_OBJMGR
	FileClose(fp);
	ObjMgrDump(NULL, "ObjMgrAdd");
#endif
	retval = TRUE;
erret: 
	return retval;
}

/*****************************************************************************
*
*   ObjMgrRegister (datatype, data)
*   	datatype is the datatype of data to register
*   	if data is already registered in ObjMgr, returns entityID
*   	if not, is added to the ObjMgr, returns entityID
*
*   	if (datatype is a choice type, uses data as a ValNodePtr)
*   
*   	on failure returns 0
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrRegister (Uint2 datatype, Pointer data)
{
	Uint2 dtype, retval = 0;
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	ObjMgrTypePtr omtp;
	Pointer ptr;


	if (data == NULL) return retval;

	dtype = datatype;  /* sets the default state */
	ptr = data;

	omp = ObjMgrWriteLock();

	omdp = ObjMgrFindByData(omp, data);  /* already have it? */
	if (omdp != NULL)
	{
		if (! omdp->EntityID)
		{
			if (omdp->parentptr != NULL)
				ErrPostEx(SEV_ERROR,0,0, "ObjMgrRegister: parent != NULL");

			ObjMgrAddEntityID(omp, omdp);
		}

		retval = omdp->EntityID;
		goto erret;
	}
								/* have to add it to ObjMgr */
	omtp = ObjMgrTypeFind(omp, datatype, NULL, NULL);
	if (omtp == NULL)
	{
		ErrPostEx(SEV_ERROR,0,0, "ObjMgrRegister: invalid data type [%d]", (int)datatype);
		goto erret;
	}
      
      /*** this was to register things like SeqEntry.. currently we register data.ptrvalue directly **
      
	if (omtp->fromchoicefunc == NULL)
	{
		dtype = datatype;
		ptr = data;
	}
	else
	{
		vnp = (ValNodePtr)data;
		dtype = (*(omtp->fromchoicefunc))(vnp);
		ptr = vnp->data.ptrvalue;
	}

      ***********************************************************************************************/
      
	ObjMgrAddFunc(omp, dtype, ptr);
	omdp = ObjMgrFindByData(omp, ptr);
	if (omdp == NULL) goto erret;

	ObjMgrAddEntityID(omp, omdp);
	retval = omdp->EntityID;
erret:
	ObjMgrUnlock();

	return retval;
}


/*****************************************************************************
*
*   ObjMgrAddUserData(entityID, procid, proctype, userkey)
*   	creates a new OMUserData struct attached to entityID
*   	if entityID = 0, attaches to the desktop (all objects)
*   	Caller must fill in returned structure
*   	returns NULL on failure
*
*****************************************************************************/
NLM_EXTERN OMUserDataPtr LIBCALL ObjMgrAddUserData (Uint2 entityID, Uint2 procid, Uint2 proctype, Uint2 userkey)
{
	OMUserDataPtr omudp=NULL, tmp;
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;

	omp = ObjMgrWriteLock();

	omudp = MemNew(sizeof(OMUserData));
	omudp->procid = procid;
	omudp->proctype = proctype;
	omudp->userkey = userkey;

	if (entityID == 0)
	{
		if (omp->userdata == NULL)
			omp->userdata = omudp;
		else
		{
			for (tmp = omp->userdata; tmp->next != NULL; tmp = tmp->next)
				continue;
			tmp->next = omudp;
		}
	}
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
		if (omdp == NULL)
			omudp = MemFree(omudp);
		else
		{
			if (omdp->userdata == NULL)
				omdp->userdata = omudp;
			else
			{
				for (tmp = omdp->userdata; tmp->next != NULL; tmp = tmp->next)
					continue;
				tmp->next = omudp;

			}
		}
	}

	ObjMgrUnlock();
	return omudp;
}

/*****************************************************************************
*
*   ObjMgrGetUserData(entityID, procid, proctype, userkey)
*   	Finds an OMUserData struct attached to entityID
*   	if entityID = 0, gets from the desktop
*   	returns NULL on failure
*
*****************************************************************************/
NLM_EXTERN OMUserDataPtr LIBCALL ObjMgrGetUserData (Uint2 entityID, Uint2 procid, Uint2 proctype, Uint2 userkey)
{
	OMUserDataPtr omudp=NULL;
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;

	omp = ObjMgrReadLock();

	if (entityID == 0)
	{
		omudp = omp->userdata;
	}
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
		if (omdp != NULL)
			omudp = omdp->userdata;
	}

	while (omudp != NULL)
	{
		if ((omudp->procid == procid) || (! procid))
		{
			if ((omudp->proctype == proctype) || (! proctype))
			{
				if ((omudp->userkey == userkey) || (! userkey))
					break;
			}
		}
		omudp = omudp->next;
	}

	ObjMgrUnlock();
	return omudp;
}
/*****************************************************************************
*
*   ObjMgrFreeUserData(entityID, procid, proctype, userkey)
*   	frees OMUserData attached to entityID by procid
*       if procid ==0, frees all OMUserData of proctype
*   	if proctype ==0, matches any proctype
*       if userkey == matches any userkey
*   	returns TRUE if any freed
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrFreeUserData (Uint2 entityID, Uint2 procid, Uint2 proctype, Uint2 userkey)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	retval = ObjMgrFreeUserDataFunc(omp, entityID, procid, proctype, userkey);
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrFreeUserDataFunc(omp, entityID, procid, proctype, userkey)
*   	frees OMUserData attached to entityID by procid
*       if procid ==0, frees all OMUserData of proctype
*   	if proctype ==0, matches any proctype
*       if userkey == matches any userkey
*   	returns TRUE if any freed
*
*****************************************************************************/
static Boolean NEAR ObjMgrFreeUserDataFunc (ObjMgrPtr omp, Uint2 entityID,
								Uint2 procid, Uint2 proctype, Uint2 userkey)
{
	OMUserDataPtr omudp=NULL, prev, next;
	ObjMgrDataPtr omdp;
	Boolean got_one = FALSE, view_left;
	ObjMgrTypePtr omtp;
	Uint2 type, options;
	Pointer ptr;
	Boolean is_write_locked;

	options = omp->options;

	if (entityID == 0)
	{
		omudp = omp->userdata;
	}
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
		if (omdp != NULL)
		{
			omudp = omdp->userdata;
			options = omdp->options;
		}
	}

	prev = NULL;
	view_left = FALSE;  /* assume nothing left to receive messages */
	while (omudp != NULL)
	{
		next = omudp->next;
		if ((omudp->procid == procid) || (! procid))
		{
			if ((omudp->proctype == proctype) || (! proctype))
			{
				if ((omudp->userkey == userkey) || (! userkey))
				{
					got_one = TRUE;
					if (prev == NULL)
					{
						if (entityID == 0)
							omp->userdata = next;
						else
							omdp->userdata = next;
					}
					else
						prev->next = next;
					if (omudp->freefunc != NULL)
						(* (omudp->freefunc))(omudp->userdata.ptrvalue);
					omudp = MemFree(omudp);
				}
			}
		}
		if (omudp != NULL)
		{
			prev = omudp;
			if (omudp->messagefunc != NULL) /* gets messages */
				view_left = TRUE;
		}
		omudp = next;
	}

	if (options & OM_OPT_FREE_IF_NO_VIEW)  /* free data if no more views */
	{
		if ((got_one) && (! view_left) && (omdp != NULL))   /* no more views */
		{
			if (! omdp->being_freed)  /* being freed by ObjMgrDelete */
			{
				if (omdp->choice != NULL)
				{
					type = omdp->choicetype;
					ptr = omdp->choice;
				}
				else
				{
					type = omdp->datatype;
					ptr = omdp->dataptr;
				}

				omtp = ObjMgrTypeFind(omp, type, NULL, NULL);
				if (omtp != NULL)
				{
					omdp->being_freed = TRUE; /* flag not to call this func */
                    /* get rid of extra user data */
                    ObjMgrFreeUserDataFunc(omp, entityID, 0, 0, 0);
					is_write_locked = omp->is_write_locked;
					ObjMgrUnlock();
					(*(omtp->freefunc))(ptr);
					if (is_write_locked)
						ObjMgrWriteLock();
					else
						ObjMgrReadLock();
				}
			}
		}
	}
	return got_one;
}



/*****************************************************************************
*
*   ObjMgrLookup(omp, data)
*   	Binary lookup of data in omp->datalist
*   	returns index (>=0) if found
*       returns -1 if not found
*
*****************************************************************************/
NLM_EXTERN Int4 LIBCALL ObjMgrLookup(ObjMgrPtr omp, Pointer data)
{
	Int4 imin, imax, i;
	ObjMgrDataPtr PNTR omdpp;
	unsigned long tmp, datai;

	imin = 0;
	imax = omp->currobj - 1;
	omdpp = omp->datalist;

	datai = (unsigned long)data;

	while (imax >= imin)
	{
		i = (imax + imin)/2;
		tmp = (unsigned long)(omdpp[i]->dataptr);
		if (tmp > datai)
			imax = i - 1;
		else if (tmp < datai)
			imin = i + 1;
		else
			return i;
	}

	return (Int4)(-1);
}

/*****************************************************************************
*
*   ObjMgrDelete(type, data)
*   	deletes a pointer (data) of type (type) to the sequence manager
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrDelete (Uint2 type, Pointer data)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	ObjMgrDataPtr PNTR omdpp, PNTR to, PNTR from;
	Int4 i, j;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();  /* really remove the entity */
	i = ObjMgrLookup(omp, data);  /* make sure it is still current */
	if (i < 0)  /* not found */
	{
	   /***	may not be registered with objmgr ***
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrDelete: pointer [%ld] type [%d] not found",
			(long)data, (int)type);
		***/
		goto erret;
	}

	omdpp = omp->datalist;
	omdp = omdpp[i];    /* emptys always at end */

	if (omdp == NULL) goto erret;

	if (omdp->EntityID != 0)
	{
		ObjMgrSendMsgFunc(omp, omdp, OM_MSG_DEL, omdp->EntityID, 0, 0, 0, 0, 0, NULL);
		ObjMgrDeSelectFunc(omp, omdp->EntityID,0,0,0,NULL);
		if (! omdp->being_freed)  /* ObjMgrFreeUserData can call delete */
		{
			omdp->being_freed = TRUE;  /* break cycle */
			ObjMgrFreeUserDataFunc(omp, omdp->EntityID, 0, 0, 0);
		}
	}

	if (omdp->clipboard)    /* update the clipboard */
		omp->clipboard = NULL;

	if (omdp->lockcnt)
		ErrPostEx(SEV_ERROR, 0,0,"ObjMgrDelete: deleting locked element");
	else if (omdp->tempload == TL_LOADED)
	{
		if (omp->tempcnt)
			omp->tempcnt--;
		else
			ErrPostEx(SEV_ERROR, 0,0, "ObjMgrDelete: reducing tempcnt below 0");
	}

	/* if (omdp->EntityID != 0 && omdp->EntityID == omp->HighestEntityID)
		omp->HighestEntityID--; */
	if (omdp->EntityID != 0)
		ObjMgrRecycleEntityID (omdp->EntityID, omp);

	ObjMgrDeleteIndexOnEntityID(omp,omdp->EntityID);

	if (omdp->extradata != NULL && omdp->freeextra != NULL) {
		omdp->freeextra ((Pointer) omdp);
	}

	if (omdp->bulkIndexFree) {
		ObjMgrUnlock(); /* if bulk free, delete at end of BioseqFree or BioseqSetFree */
		return TRUE;
	}

	MemSet((Pointer)omdp, 0, sizeof(ObjMgrData));
	if (omp->currobj)
		omp->currobj--;
	else
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrDelete: reducing currobj below 0");
	j = omp->currobj - i;
	if (j)
	{
		to = omdpp + i;
		from = to + 1;
		MemMove(to, from, (size_t)(sizeof(ObjMgrDataPtr) * j));
	}
	omdpp[omp->currobj] = omdp;  /* put in pointer to empty data space */

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrDelete");
#endif

	retval = TRUE;
erret:
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrDeleteAllInRecord()
*   	deletes all omdp entries in a record
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrDeleteAllInRecord (
  void
)

{
  Int4                i, j, k, num;
  ObjMgrDataPtr       omdp;
  ObjMgrDataPtr PNTR  omdpp;
  ObjMgrPtr           omp;
  ObjMgrDataPtr PNTR  tmp;

  omp = ObjMgrWriteLock ();

  if (omp != NULL) {
    omdpp = omp->datalist;
    if (omdpp != NULL) {

      num = omp->currobj;
      tmp = (ObjMgrDataPtr PNTR) MemNew (sizeof (ObjMgrDataPtr) * (size_t) (num + 1));
      if (tmp != NULL) {

        for (i = 0, j = 0, k = 0; i < num; i++) {
          omdp = omdpp [i];
          if (omdp != NULL && omdp->bulkIndexFree) {
            MemSet ((Pointer) omdp, 0, sizeof (ObjMgrData));
            tmp [k] = omdp;
            k++;
          } else {
            omdpp [j] = omdpp [i];
            j++;
          }
        }
        omp->currobj = j;
        MemMove (omdpp + j, tmp, sizeof (ObjMgrDataPtr) * (size_t) k);
      }

      MemFree (tmp);
    }
  }

  ObjMgrUnlock ();

  return TRUE;
}

/*****************************************************************************
*
*   ObjMgrGetClipBoard()
*     returns ObjMgrDataPtr to current clipboard object or NULL if none
*
*****************************************************************************/
NLM_EXTERN ObjMgrDataPtr LIBCALL ObjMgrGetClipBoard (void)
{
	ObjMgrPtr omp;
	
	omp = ObjMgrReadLock();
	ObjMgrUnlock();
	return omp->clipboard;
}

/*****************************************************************************
*
*   ObjMgrAddToClipBoard(entityID, ptr)
*   	if entityID > 0, then uses it.
*   	else, looks up entityID using ptr
*       adds entityID if needed
*       sends OM_MSG_TO_CLIPBOARD
*
*   	Anything in the clipboard is deleted
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrAddToClipBoard (Uint2 entityID, Pointer ptr)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	if (! entityID)
	{
		omdp = ObjMgrFindByData(omp, ptr);
		if (omdp != NULL)
		{
			if (omdp->parentptr != NULL)
			{
				ErrPostEx(SEV_ERROR,0,0,"AddToClipBoard: ParentPtr != NULL");
				goto erret;
			}
			/* if (omdp->EntityID == 0)
				omdp->EntityID = ++(omp->HighestEntityID); */
			if (omdp->EntityID == 0) {
				omdp->EntityID = ObjMgrNextAvailEntityID (omp);
				ObjMgrRecordOmdpByEntityID (omdp->EntityID, omdp);
			}
		}
	}
	else
	{
		omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	}

	if (omdp == NULL)
	{
		ErrPostEx(SEV_ERROR,0,0,"AddToClipBoard: data not found");
		goto erret;
	}

	ObjMgrFreeClipBoardFunc(omp);

	omdp->clipboard = TRUE;
	omp->clipboard = omdp;

	ObjMgrSendMsgFunc(omp, omdp, OM_MSG_TO_CLIPBOARD, omdp->EntityID, 0, 0, 0, 0, 0, NULL);

	retval = TRUE;
erret:
	ObjMgrUnlock();

	return retval;
}

/*****************************************************************************
*
*   ObjMgrFreeClipBoard()
*     clears any data from the clipboard
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrFreeClipBoard (void)
{
	ObjMgrPtr omp;
	Boolean retval;
	
	omp = ObjMgrWriteLock();
	retval = ObjMgrFreeClipBoardFunc(omp);
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrFreeClipBoardFunc()
*     clears any data from the clipboard
*
*****************************************************************************/
static Boolean NEAR ObjMgrFreeClipBoardFunc (ObjMgrPtr omp)
{
	ObjMgrTypePtr omtp;
	ObjMgrDataPtr omdp;
	Uint2 type;
	Pointer ptr;
	
	omdp = omp->clipboard;
	if (omdp == NULL) return TRUE;

	if (omdp->choice != NULL)
	{
		type = omdp->choicetype;
		ptr = omdp->choice;
	}
	else
	{
		type = omdp->datatype;
		ptr = omdp->dataptr;
	}

	omtp = ObjMgrTypeFind(omp, type, NULL, NULL);
	if (omtp == NULL)
	{
		ErrPostEx(SEV_ERROR,0,0,"ObjMgrFreeClipBoard: cant find type [%d]", (int)type);
		return FALSE;
	}
	else
		(*(omtp->freefunc))(ptr);
	ObjMgrDelete(omdp->datatype, omdp->dataptr);
	omp->clipboard = NULL;
	return TRUE;
}
/*****************************************************************************
*
*   ObjMgrConnect (type, data, parenttype, parentdata)
*   	Adds parent info to element
*       Updates EntityID
*   		if both are 0, assigns it by incrementing HighestEntityID
*   		if one is 0, assigns it the other
*           if neither is 0 and not the same ID
*                assigns parent to child (and cascades to its children)
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrConnect (Uint2 type, Pointer data, Uint2 parenttype, Pointer parentdata)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;
	
	omp = ObjMgrWriteLock();
	retval = ObjMgrConnectFunc(omp, type, data, parenttype, parentdata);
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrConnectFunc (type, data, parenttype, parentdata)
*   	Adds parent info to element
*       Updates EntityID
*   		if both are 0, assigns it by incrementing HighestEntityID
*   		if one is 0, assigns it the other
*           if neither is 0 and not the same ID
*                assigns parent to child (and cascades to its children)
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrConnectFunc (ObjMgrPtr omp, Uint2 type, Pointer data, Uint2 parenttype, Pointer parentdata)
{
	Int4 i;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;
	
	i = ObjMgrLookup(omp, data);
	if (i < 0)  /* not found */
	{
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrConnect: pointer [%ld] type [%d] not found",
			(long)data, (int)type);
		goto erret;
	}

	omdp = omp->datalist[i];

	if ((omdp->EntityID != 0) && (parentdata != NULL))
	{                         /* registered type, inform any attached procs */

		ObjMgrSendMsgFunc(omp, omdp, OM_MSG_CONNECT, omdp->EntityID, 0, 0, 0, 0, 0, NULL);
		ObjMgrDeSelectFunc(omp, omdp->EntityID,0,0,0,NULL);
		ObjMgrFreeUserDataFunc(omp, omdp->EntityID, 0, 0, 0);

		/* if (omp->HighestEntityID == omdp->EntityID) {
			(omp->HighestEntityID)--;
		} */
		ObjMgrRecycleEntityID (omdp->EntityID, omp);
		ObjMgrDeleteIndexOnEntityID (omp, omdp->EntityID);
		omdp->EntityID = 0;   /* reset.. now has a parent */
	}
	omdp->parenttype = parenttype;
	omdp->parentptr = parentdata;

	if (parentdata != NULL)
	{
		i = ObjMgrLookup(omp, parentdata);
		if (i < 0)  /* not found */
		{
			ErrPostEx(SEV_ERROR, 0,0, "ObjMgrConnect: parent pointer [%ld] type [%d] not found",
				(long)parentdata, (int)parenttype);
			goto erret;
		}

		
	}

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrConnect");
#endif
	retval = TRUE;
erret:
	return retval;
}
/*****************************************************************************
*
*   ObjMgrDetach (type, data)
*   	Removes parent info from element
*       Adds to objmgr if necessary
*       Does NOT register entity
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrDetach (Uint2 type, Pointer data)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;
	
	omp = ObjMgrWriteLock();
	retval = ObjMgrDetachFunc(omp, type, data);
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrDetach (type, data)
*   	Removes parent info from element
*       Adds to objmgr if necessary
*       Does NOT register entity
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrDetachFunc (ObjMgrPtr omp, Uint2 type, Pointer data)
{
	Int4 i;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;
	
	i = ObjMgrLookup(omp, data);
	if (i < 0)  /* not found */
	{
		retval = ObjMgrAddFunc(omp, type, data);
		goto erret;
	}

	omdp = omp->datalist[i];
	if (omdp->parentptr == NULL)  /* not connected anyway */
		return TRUE;

	omdp->parenttype = 0;
	omdp->parentptr = NULL;
	ObjMgrDeleteIndexOnEntityID (omp, omdp->EntityID);
	omdp->EntityID = 0;   /* reset.. now has a parent */

	retval = TRUE;
erret:
	return retval;
}

/*****************************************************************************
*
*   ObjMgrSetDirtyFlag (entityID, the_flag)
*     record that an entity has been changed but not yet saved.
*       the_flag sets or unsets this state
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSetDirtyFlag (Uint2 entityID, Boolean the_flag)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	if (entityID <= 0) return FALSE;

	omp = ObjMgrWriteLock();
	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp != NULL)
	{
		omdp->dirty = the_flag;
		retval = TRUE;
	}
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrGetDirtyFlag (entityID)
*     returns the state of the dirty flag for entityID
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrGetDirtyFlag (Uint2 entityID)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	if (entityID <= 0) return retval;

	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp != NULL)
		retval = omdp->dirty;
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrSetChoice(type, choice, data)
*   	Adds the ValNodePtr pointing directly to this Bioseq or BioseqSet
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSetChoice (Uint2 type, ValNodePtr choice, Pointer data)
{
	ObjMgrPtr omp;
	Int4 i;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;
	
	omp = ObjMgrWriteLock();

	i = ObjMgrLookup(omp, data);
	if (i < 0)  /* not found */
	{
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrChoice: pointer [%ld] type [%d] not found",
			(long)data, (int)type);
		goto erret;
	}

	omdp = omp->datalist[i];
	omdp->choicetype = type;
	omdp->choice = choice;
	retval = TRUE;
erret:
	ObjMgrUnlock();

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrChoice");
#endif

	return retval;
}

/*****************************************************************************
*
*   ObjMgrFindTop(omp, omdp)
*   	finds the highest parent of omdp
*       returns a ObjMgrDataPtr to the top
*
*****************************************************************************/
NLM_EXTERN ObjMgrDataPtr LIBCALL ObjMgrFindTop (ObjMgrPtr omp, ObjMgrDataPtr omdp)
{
	Int4 i;

	if ((omp == NULL) || (omdp == NULL)) return NULL;

	while (omdp->parentptr != NULL)
	{
		i = ObjMgrLookup(omp, omdp->parentptr);
		if (i < 0)  /* not found */
		{
			ErrPostEx(SEV_ERROR, 0,0, "ObjMgrFindTop: parentptr [%ld] not found",
				(long)(omdp->parentptr));
			return NULL;
		}
		omdp = omp->datalist[i];
	}

	return omdp;
}

/*****************************************************************************
*
*   ObjMgrWholeEntity(omdp, itemID, itemtype)
*		returns TRUE if itemID, itemtype identify a complete entity omdp
*       returns FALSE if these are an internal part of the entity
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrWholeEntity (ObjMgrDataPtr omdp, Uint2 itemID, Uint2 itemtype)
{
	if (omdp == NULL)
		return FALSE;

	if ((itemID == 0) && (itemtype == 0))
		return TRUE;

	if ((itemID == 1) && (itemtype == omdp->datatype))
		return TRUE;

	return FALSE;

}

/*****************************************************************************
*
*   ObjMgrFreeCache(type)
*   	Frees all cached objects of type and subtypes of type
*   		based on ObjMgrMatch()
*   	if type == 0, frees all cached objects
*   	returns TRUE if no errors occurred
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrFreeCache (Uint2 type)
{
	ObjMgrPtr omp;
	Boolean more_to_go = TRUE;
	Uint2 rettype;
	VoidPtr retval;

	while (more_to_go)
        {
           omp = ObjMgrWriteLock();
/*
                omp = ObjMgrReadLock ();
*/
                more_to_go = ObjMgrFreeCacheFunc(omp, type, &rettype, &retval);
		if (more_to_go)
		{
			switch (rettype)
			{
			case OBJ_SEQENTRY:
				SeqEntryFree((SeqEntryPtr)retval);
				break;
			case OBJ_BIOSEQ:
				BioseqFree((BioseqPtr)retval);
				break;
			case OBJ_BIOSEQSET:
				BioseqSetFree((BioseqSetPtr)retval);
				break;
			default:
				break;
			}
		}
		ObjMgrUnlock();
	}

        /*        if(type == 0)
                  omp->HighestEntityID = 0; */
        
	return TRUE;
}

/*****************************************************************************
*
*   ObjMgrFreeCacheFunc(type)
*   	Finds next cached objects of type and subtypes of type
*   		based on ObjMgrMatch()
*   	if type == 0, frees all cached objects
*   	returns TRUE if no more found
*
*****************************************************************************/
static Boolean NEAR ObjMgrFreeCacheFunc (ObjMgrPtr omp, Uint2 type, Uint2Ptr rettype, VoidPtr PNTR retval)
{
    Int4 i, num;
	ObjMgrDataPtr PNTR omdpp, omdp;

	if (omp->hold)   /* things are being held */
		return FALSE;   /* nothing to do, but send a warning */

	omdpp = omp->datalist;
	num = omp->currobj;
    for (i = 0; i < num; i++)
    {
		omdp = omdpp[i];
		if ((omdp->parentptr == NULL) &&     /* top level */
			(omdp->tempload == TL_CACHED))   /* cached */
		{
			if ((! type) ||
				(ObjMgrMatch(type, omdp->datatype)) ||
				(ObjMgrMatch(type, omdp->choicetype)))
			{
				/** here is where the freefunc should be called **/

				if (omdp->choice != NULL)
				{
					switch (omdp->choicetype)
					{
						case OBJ_SEQENTRY:
							*rettype = omdp->choicetype;
							*retval = omdp->choice;
							return TRUE;
						default:
							ErrPostEx(SEV_ERROR,0,0, "ObjMgrFreeCache: unsupported choicetype[%d]",
								(int)(omdp->choicetype));
							break;
					}
				}
				else
				{
					switch(omdp->datatype)
					{
						case OBJ_BIOSEQ:
						case OBJ_BIOSEQSET:
							*rettype = omdp->datatype;
							*retval = omdp->dataptr;
							return TRUE;
						default:
							ErrPostEx(SEV_ERROR,0,0,"ObjMgrFreeCache: usupported datatype [%d]",
								(int)(omdp->datatype));
							break;
					}
				}
			}
		}
    }
    return FALSE;
	
}


/*****************************************************************************
*
*   ObjMgrMatch(type1, type2)
*   	returns 0 if no match
*   	1 if identical
*   	2 if 2 is a subset of 1   (e.g. 1=OBJ_SEQENTRY, 2=BIOSEQ)
*       current type1 that can have subtypes are:
*   		OBJ_SEQENTRY
*   		OBJ_PUB
*   		OBJ_SEQANNOT
*   		OBJ_SEQCODE_SET
*   		OBJ_GENETIC_CODE_SET
*
*****************************************************************************/
NLM_EXTERN Int2 LIBCALL ObjMgrMatch (Uint2 type1, Uint2 type2)
{
	if (type1 == type2)
		return 1;

	switch (type1)
	{
		case OBJ_SEQENTRY:
			switch (type2)
			{
				case OBJ_BIOSEQ:
				case OBJ_BIOSEQSET:
					return 2;
			}
			break;
		case OBJ_SEQANNOT:
			switch (type2)
			{
				case OBJ_SEQFEAT:
				case OBJ_SEQALIGN:
				case OBJ_SEQGRAPH:
					return 2;
			}
			break;
		case OBJ_SEQCODE_SET:
			switch (type2)
			{
				case OBJ_SEQCODE:
					return 2;
			}
			break;
		case OBJ_GENETIC_CODE_SET:
			switch (type2)
			{
				case OBJ_GENETIC_CODE:
					return 2;
			}
			break;
		default:
			break;
	}

	return 0;
}


/*****************************************************************************
*
*   ObjMgrGetChoiceForData(data)
*   	returns ValNodePtr for a BioseqPtr or BioseqSetPtr
*       choice must have been put in ObjMgr using ObjMgrChoice
*       the Bioseq/BioseqSets it is a part of must also be in ObjMgr
*       returns NULL on failure.
*
*****************************************************************************/
NLM_EXTERN ValNodePtr LIBCALL ObjMgrGetChoiceForData (Pointer data)
{
	ObjMgrPtr omp;
	Int4 i;
	ValNodePtr choice = NULL;

	if (data == NULL) return choice;
	omp = ObjMgrReadLock();
	i = ObjMgrLookup(omp, data);
	if (i < 0)
	{
		ErrPostEx(SEV_ERROR, 0,0, "ChoiceGetChoiceForData: data not in ObjMgr");
	}
	else
	{
		choice = omp->datalist[i]->choice;
	}
	ObjMgrUnlock();

	return choice;
}

/*****************************************************************************
*
*   ObjMgrGetEntityIDForChoice(choice)
*   	returns the EntityID for a ValNodePtr
*       choice must have been put in ObjMgr using ObjMgrChoice
*       the Bioseq/BioseqSets it is a part of must also be in ObjMgr
*       This function will move up to the top of the Choice tree it may be
*          in. If top level EntityID is 0, one is assigned at this point.
*       If an element is moved under a different hierarchy, its EntityID will
*          change.
*       returns 0 on failure.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrGetEntityIDForChoice (ValNodePtr choice)
{
	Pointer data;

	if (choice == NULL) return 0;
	data = choice->data.ptrvalue;
	if (data == NULL) return 0;

	return ObjMgrGetEntityIDForPointer (data);
}

/*****************************************************************************
*
*   ObjMgrGetEntityIDForPointer(data)
*   	returns the EntityID for any pointer, Choice or Data
*       This function will move up to the top of the tree it may be
*          in. If top level EntityID is 0, one is assigned at this point.
*       If an element is moved under a different hierarchy, its EntityID will
*          change.
*
*       Either ObjMgrGetEntityIDForPointer() or ObjMgrGetEntityIDForChoice()
*   		MUST be called to have an OM_MSG_CREATE message sent to any
*           registered proceedures
*   
*       returns 0 on failure.
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrGetEntityIDForPointer (Pointer ptr)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Uint2 retval = 0;

	if (ptr == NULL)
		return retval;

	omp = ObjMgrWriteLock(); /* (EY) */
	omdp = ObjMgrFindByData(omp, ptr);

	if (omdp == NULL) goto erret;

	omdp = ObjMgrFindTop(omp, omdp);
	if (omdp == NULL) goto erret;

	if (omdp->EntityID == 0)     /* need to assign it */
		ObjMgrAddEntityID(omp, omdp);

	retval = omdp->EntityID;
erret:
	ObjMgrUnlock();

	return retval;
}

/*****************************************************************************
*
*   ObjMgrGetChoiceForEntityID (id)
*
*****************************************************************************/
NLM_EXTERN ValNodePtr LIBCALL ObjMgrGetChoiceForEntityID (Uint2 id)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	ValNodePtr retval = NULL;

	if (id <= 0) return retval;

	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByEntityID(omp, id, NULL);
	if (omdp != NULL)
		retval = omdp->choice;
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrLock(type, data, lockit)
*   	if lockit=TRUE, locks the element
*       else unlocks it
*       returns the current lock count or -1 on failure
*
*****************************************************************************/
NLM_EXTERN Int4 LIBCALL ObjMgrLock (Uint2 type, Pointer data, Boolean lockit)
{
	ObjMgrPtr omp;
	Int4 retval = -1;
	
	omp = ObjMgrWriteLock();
	if (omp != NULL)
		retval = ObjMgrLockFunc(omp, type, data, lockit);
	ObjMgrUnlock();
	return retval;
}

static Int4 NEAR ObjMgrLockFunc (ObjMgrPtr omp, Uint2 type, Pointer data, Boolean lockit)
{
	Int4 i, lockcnt = -1;
	ObjMgrDataPtr omdp;

#ifdef DEBUG_OBJMGR
	Char buf[80];
#endif

	i = ObjMgrLookup(omp, data);
	if (i < 0)  /* not found */
	{
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrLock: pointer [%ld] type [%d] not found",
			(long)data, (int)type);
		return lockcnt;
	}

	omdp = ObjMgrFindTop(omp, omp->datalist[i]);

	if (lockit) {
		omdp->lockcnt++;

		/******** desktop can do this *******
		if (omdp->tempload == TL_CACHED)
		{
			ErrPostEx(SEV_ERROR, 0,0,"ObjMgrLock: locking a cached entity");
		}
		*************************************/
	}
	else
	{
		if (omdp->lockcnt) {
			omdp->lockcnt--;
		}
		else
		{
			ErrPostEx(SEV_ERROR, 0,0,"ObjMgrLock: unlocking 0 lockcnt");
			return lockcnt;
		}
	}

	lockcnt = omdp->lockcnt;

	if (! lockit)     /* check for automatic delete */
	{
		if ((omdp->tempload != TL_NOT_TEMP) && (! omdp->lockcnt))
		{
			omdp->touch = ObjMgrTouchCnt();   /* stamp with time */
			/*
			omp->tempcnt++;
			*/
			ObjMgrReap(omp);
		}
	}


#ifdef DEBUG_OBJMGR
	if (lockit)
		sprintf(buf, "ObjMgrLock   Lock [%d]", (int)i);
	else
		sprintf(buf, "ObjMgrLock   Unlock [%d]", (int)i);
	ObjMgrDump(NULL, buf);
#endif

	return lockcnt;
}

/*****************************************************************************
*
*   Boolean ObjMgrSetTempLoad (ObjMgrPtr omp, Pointer ptr)
*   Sets a Loaded element to "temporary"
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSetTempLoad (ObjMgrPtr omp, Pointer ptr)
{
	Int4 index;
	ObjMgrDataPtr omdp;

	index = ObjMgrLookup(omp, ptr);
	if (index < 0) return FALSE;

	omdp = ObjMgrFindTop(omp, omp->datalist[index]);
	if (omdp == NULL) return FALSE;

	if (omdp->tempload == TL_NOT_TEMP)
	{
		omdp->tempload = TL_LOADED;
		omp->tempcnt++;
	}
	omdp->touch = ObjMgrTouchCnt();

	omdp->lockcnt++;    /* protect against reaping this one */
	ObjMgrReap (omp);   /* check to see if we need to reap */
	omdp->lockcnt--;    /* reset to previous state */

	return TRUE;
}

/*****************************************************************************
*
*   ObjMgrReap(omp)
*   	Checks to see if memory needs to be cleared, and does it
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrReap (ObjMgrPtr omp)
{
	Uint4 lowest;
	Int4 num, j;
	Uint2 tempcnt;
	ObjMgrDataPtr tmp, ditch, PNTR omdpp;
	Boolean is_write_locked, did_one = FALSE;

	if (omp->hold)      /* keep all tempload records around while hold is on */
		return FALSE;

	if (omp->reaping)   /* protect against recursion caused by ObjMgrSendMsg */
		return FALSE;

    tempcnt = 0;
	num = omp->currobj;
	omdpp = omp->datalist;
	for (j = 0; j < num; j++, omdpp++)
	{
		tmp = *omdpp;
		if ((tmp->tempload == TL_LOADED) && (! tmp->lockcnt))
		{
			tempcnt++;
		}
	}

	while (/* omp-> */ tempcnt > omp->maxtemp)   /* time to reap */
	{
		lowest = UINT4_MAX;

        tempcnt = 0;
		num = omp->currobj;
		omdpp = omp->datalist;
		ditch = NULL;
		for (j = 0; j < num; j++, omdpp++)
		{
			tmp = *omdpp;
			if ((tmp->tempload == TL_LOADED) && (! tmp->lockcnt))
			{
			    tempcnt++;
				if (lowest > tmp->touch)
				{
					lowest = tmp->touch;
					ditch = tmp;
				}
			}
		}
		if (ditch == NULL)    /* nothing to free */
			return FALSE;

		omp->reaping = TRUE;
		ditch->tempload = TL_CACHED;
		ObjMgrSendMsgFunc(omp, ditch, OM_MSG_CACHED, ditch->EntityID, 0, 0, 0, 0, 0, NULL);
		omp->tempcnt--;
		tempcnt--;
		is_write_locked = omp->is_write_locked;

		/* null out feature pointers in seqmgr feature indices via reap function */

		if (ditch->extradata != NULL && ditch->reapextra != NULL) {
			ditch->reapextra ((Pointer) ditch);
		}

		if (ditch->choice != NULL)
		{
			switch (ditch->choicetype)
			{
				case OBJ_SEQENTRY:
					did_one = TRUE;
					ObjMgrUnlock();
					SeqEntryFreeComponents(ditch->choice);
					break;
			}
		}
		else
		{
			switch (ditch->datatype)
			{
				case OBJ_BIOSEQ:
					did_one = TRUE;
					ObjMgrUnlock();
					BioseqFreeComponents((BioseqPtr)(ditch->dataptr));
					break;
				case OBJ_BIOSEQSET:
					did_one = TRUE;
					ObjMgrUnlock();
					BioseqSetFreeComponents((BioseqSetPtr)(ditch->dataptr), FALSE);
					break;
				default:
					ErrPostEx(SEV_ERROR,0,0,"ObjMgrUnlock: ditching unknown type");
					break;
			}
		}

		if (did_one)
		{
			if (is_write_locked)
				omp = ObjMgrWriteLock();
			else
				omp = ObjMgrReadLock();
		}
		
		omp->reaping = FALSE;

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrReap");
#endif

	}

	return TRUE;
}

/*****************************************************************************
*
*   ObjMgrReapOne(omp)
*   	Reaps the single least recently accessed entity
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrReapOne (ObjMgrPtr omp)
{
	Uint4 lowest;
	Int4 num, j;
	ObjMgrDataPtr tmp, ditch, PNTR omdpp;
	Boolean is_write_locked, did_one = FALSE;

	if (omp->hold)      /* keep all tempload records around while hold is on */
		return FALSE;

	if (omp->reaping)   /* protect against recursion caused by ObjMgrSendMsg */
		return FALSE;

		lowest = UINT4_MAX;
		
		num = omp->currobj;
		omdpp = omp->datalist;
		ditch = NULL;
		for (j = 0; j < num; j++, omdpp++)
		{
			tmp = *omdpp;
			if ((tmp->tempload == TL_LOADED) && (! tmp->lockcnt))
			{
				if (lowest > tmp->touch)
				{
					lowest = tmp->touch;
					ditch = tmp;
				}
			}
		}
		if (ditch == NULL)    /* nothing to free */
			return FALSE;

		omp->reaping = TRUE;
		ditch->tempload = TL_CACHED;
		ObjMgrSendMsgFunc(omp, ditch, OM_MSG_CACHED, ditch->EntityID, 0, 0, 0, 0, 0, NULL);
		omp->tempcnt--;
		is_write_locked = omp->is_write_locked;

		/* null out feature pointers in seqmgr feature indices via reap function */

		if (ditch->extradata != NULL && ditch->reapextra != NULL) {
			ditch->reapextra ((Pointer) ditch);
		}

		if (ditch->choice != NULL)
		{
			switch (ditch->choicetype)
			{
				case OBJ_SEQENTRY:
					did_one = TRUE;
					ObjMgrUnlock();
					SeqEntryFreeComponents(ditch->choice);
					break;
			}
		}
		else
		{
			switch (ditch->datatype)
			{
				case OBJ_BIOSEQ:
					did_one = TRUE;
					ObjMgrUnlock();
					BioseqFreeComponents((BioseqPtr)(ditch->dataptr));
					break;
				case OBJ_BIOSEQSET:
					did_one = TRUE;
					ObjMgrUnlock();
					BioseqSetFreeComponents((BioseqSetPtr)(ditch->dataptr), FALSE);
					break;
				default:
					ErrPostEx(SEV_ERROR,0,0,"ObjMgrUnlock: ditching unknown type");
					break;
			}
		}

		if (did_one)
		{
			if (is_write_locked)
				omp = ObjMgrWriteLock();
			else
				omp = ObjMgrReadLock();
		}
		
		omp->reaping = FALSE;

#ifdef DEBUG_OBJMGR
	ObjMgrDump(NULL, "ObjMgrReapOne");
#endif

	return TRUE;
}

/*****************************************************************************
*
*   Boolean ObjMgrIsTemp(data)
*   	returns TRUE if data is a temporarily loaded item
*       data must be BioseqPtr or BioseqSetPtr
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrIsTemp (Pointer data)
{
	ObjMgrPtr omp;
	Int4 i;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;
	
	omp = ObjMgrReadLock();

	i = ObjMgrLookup(omp, data);
	if (i < 0)  /* not found */
	{
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrIsTemp: pointer [%ld] not found",
			(long)data);
		goto erret;
	}

	omdp = ObjMgrFindTop(omp, omp->datalist[i]);
	if (omdp == NULL) goto erret;

	if (omdp->tempload != TL_NOT_TEMP)
		retval = TRUE;
erret:
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   Boolean ObjMgrIsParent(parent, child)
*   	returns TRUE if child is a child of parent
*       if parent = NULL, returns TRUE if child has no parent
*       child must never be NULL
*       returns TRUE if they are the equal
*       data must be BioseqPtr or BioseqSetPtr
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrIsChild (Pointer parent, Pointer child)
{
	ObjMgrPtr omp;
	Int4 i;
	ObjMgrDataPtr omdp, PNTR omdpp;
	Boolean retval = FALSE;

	if (child == NULL) return FALSE;
	if (parent == child) return TRUE;

	omp = ObjMgrReadLock();
	omdpp = omp->datalist;

	i = ObjMgrLookup(omp, child);
	if (i < 0)  /* not found */
	{
		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrIsChild: pointer [%ld] not found",
			(long)child);
		goto erret;
	}

	omdp = omdpp[i];
	if (parent == NULL)
	{
		if (omdp->parentptr == NULL)
			retval = TRUE;
		goto erret;
	}

	while (omdp->parentptr != NULL)
	{
		if (omdp->parentptr == parent)
		{
			retval = TRUE;
			goto erret;
		}
		i = ObjMgrLookup(omp, omdp->parentptr);
		if (i < 0)
			goto erret;
		omdp = omdpp[i];
	}
erret:
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrDump(fp)
*
*****************************************************************************/

NLM_EXTERN void LIBCALL ObjMgrDump (FILE * fp, CharPtr title)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Int4 i;
	Char buf[80];
	BioseqPtr bsp;
	Boolean close_it = FALSE;
	
	if (fp == NULL)
	{
		fp = FileOpen("ObjMgr.log", "a");
		close_it = TRUE;
	}

	omp = ObjMgrGet();
	fprintf(fp, "\n%s currobj=%d tempcnt=%d\n", title, (int)(omp->currobj),
		(int)(omp->tempcnt));
	for (i = 0; i < (Int4)(omp->currobj); i++)
	{
		omdp = omp->datalist[i];
		fprintf(fp, "[%d] [%d %d %ld] [%d %ld] %ld (%d) %uld\n", (int)i,
		    (int)omdp->EntityID, (int)(omdp->datatype),
			(long)(omdp->dataptr), (int)(omdp->parenttype),
			(long)(omdp->parentptr), (long)(omdp->choice), (int)(omdp->lockcnt),
			(unsigned long)(omdp->touch));
		if ((omdp->datatype == OBJ_BIOSEQ) && (omdp->dataptr != NULL))
		{
			bsp = (BioseqPtr)(omdp->dataptr);
			SeqIdWrite(bsp->id, buf, PRINTID_FASTA_LONG, sizeof (buf));
			fprintf(fp, "[%s %ld]\n", buf, (long)(bsp));
		}
	}
	
	if (close_it)
		FileClose(fp);
	return;
}

/*****************************************************************************
*
*   Procedure Management Functions
*
*****************************************************************************/


/*****************************************************************************
*
*   ObjMgrProcExtend(omp)
*
*****************************************************************************/
static Boolean NEAR ObjMgrProcExtend (ObjMgrPtr omp)
{
	Boolean result = FALSE;
	OMProcPtr omdp, prev=NULL;
	ObjMgrProcPtr PNTR tmp;
	Int4 i, j;

	for (omdp = omp->ncbiproc; omdp != NULL; omdp = omdp->next)
		prev = omdp;

	omdp = (OMProcPtr)MemNew(sizeof(OMProc));
	if (omdp == NULL) return result;
	tmp = (ObjMgrProcPtr PNTR)MemNew((size_t)(sizeof(ObjMgrProcPtr) * (omp->totproc + NUM_OMD)));
	if (tmp == NULL)
	{
		MemFree(omdp);
		return result;
	}

	if (prev != NULL)
	{
		prev->next = omdp;
		MemMove(tmp, omp->proclist, (size_t)(sizeof(ObjMgrProcPtr) *omp->totproc));
		MemFree(omp->proclist);
	}
	else
		omp->ncbiproc = omdp;

	j = omp->totproc;

	for (i = 0; i < NUM_OMD; i++, j++)
		tmp[j] = &(omdp->data[i]);

	omp->totproc += NUM_OMD;
	omp->proclist = tmp;

	result = TRUE;
	return result;
}

/*****************************************************************************
*
*   ObjMgrProcAdd(data, priority)
*   	adds an ObjMgrProc at given priority
*		priority must be > 0
*       highest priority function is called first.
*       if priority == 0 (default)
*   		gets the next highest priority over previous procs of same type
*       if priority == PROC_PRIORITY_HIGHEST
*           is always the highest priority (first one wins)
*   	if priority == PROC_PRIORITY_LOWEST
*           is always the lowest priority
*
*****************************************************************************/
NLM_EXTERN Uint2  LIBCALL ObjMgrProcAdd (ObjMgrProcPtr data, Int2 priority)
{
	ObjMgrPtr omp;
	ObjMgrProcPtr omdp;
	ObjMgrProcPtr PNTR omdpp;
	Int4 i;
	Uint2 procID;
	Uint2 retval = 0;

	omp = ObjMgrWriteLock();

	if (priority == 0)   /* set to next highest */
	{
		omdp = ObjMgrProcFindNext(omp, data->proctype, data->inputtype,
								data->outputtype, NULL);
		if (omdp != NULL)
			priority = omdp->priority + 10;
	}


	if (omp->currproc >= omp->totproc)
	{
		if (! ObjMgrProcExtend(omp))
			goto erret;
	}

	i = omp->currproc;
	omdpp = omp->proclist;
	omdp = omdpp[i];    /* emptys always at end */

	omp->currproc++;     /* got one more */
	procID = ++(omp->HighestProcID);

	MemMove(omdp, data, sizeof(ObjMgrProc));
	omdp->priority = priority;
	omdp->procid = procID;  /* fill in the values */
	omdp->proclabel = StringSave(data->proclabel);
	omdp->procname = StringSave(data->procname);
	omdp->submenu = StringSave(data->submenu);
	retval = procID;
erret:
	ObjMgrUnlock();

	return retval;
}

/*****************************************************************************
*
*   ObjMgrProcLoadEx(proctype, procname, proclabel, inputtype, subinputtype,
*              outputtype, suboutputtype,
*   				data, func, priority, submenu)
*   	adds a new proceedure with these parameters
*   	returns the procid
*   	if a procedure of the same name and type are already loaded
*   		returns the procid of the loaded proc.. does not reload
*
*****************************************************************************/
NLM_EXTERN Uint2 ObjMgrProcLoadEx (Uint2 proctype, CharPtr procname, CharPtr proclabel,
							Uint2 inputtype, Uint2 subinputtype,
							Uint2 outputtype, Uint2 suboutputtype, Pointer userdata,
							ObjMgrGenFunc func, Int2 priority, CharPtr submenu)
{
	ObjMgrPtr omp;
	ObjMgrProcPtr ompp;
	ObjMgrProc ompd;

	omp = ObjMgrWriteLock();
	ompp = ObjMgrProcFind(omp, 0, procname, proctype);
	ObjMgrUnlock();
	if (ompp != NULL)  /* already enabled */
	{
		return ompp->procid;
	}

	ompp = &ompd;
	MemSet((Pointer)ompp, 0, sizeof(ObjMgrProc));
	
	ompp->proctype = proctype;
	ompp->procname = procname;
	ompp->proclabel = proclabel;
	ompp->inputtype = inputtype;
	ompp->subinputtype = subinputtype;
	ompp->outputtype = outputtype;
	ompp->suboutputtype = suboutputtype;
	ompp->procdata = userdata;
	ompp->func = func;
	ompp->submenu = submenu;

	return ObjMgrProcAdd(ompp, priority); /* order determines priority */
	
}

/*****************************************************************************
*
*   ObjMgrProcLoad(proctype, procname, proclabel, inputtype, subinputtype,
*              outputtype, suboutputtype,
*   				data, func, priority)
*   	adds a new proceedure with these parameters
*   	returns the procid
*   	if a procedure of the same name and type are already loaded
*   		returns the procid of the loaded proc.. does not reload
*
*****************************************************************************/
NLM_EXTERN Uint2 ObjMgrProcLoad (Uint2 proctype, CharPtr procname, CharPtr proclabel,
							Uint2 inputtype, Uint2 subinputtype,
							Uint2 outputtype, Uint2 suboutputtype, Pointer userdata,
							ObjMgrGenFunc func, Int2 priority)

{
	return ObjMgrProcLoadEx (proctype, procname, proclabel, inputtype, subinputtype,
							outputtype, suboutputtype, userdata, func, priority, NULL);
}

/*****************************************************************************
*
*   ObjMgrProcLookup(omp, procid)
*   	these are currently just stored in order
*   	returns index (>=0) if found
*       returns -1 if not found
*
*****************************************************************************/
NLM_EXTERN Int4 LIBCALL ObjMgrProcLookup(ObjMgrPtr omp, Uint2 procid)
{
	if (omp == NULL)
		return (Int4)(-1);

	if (procid)
		return (Int4)(procid - 1);
	else
		return (Int4)(-1);
}

/*****************************************************************************
*
*   ObjMgrProcFind(omp, procid, procname, proctype)
*   	if procid != NULL looks for it
*   	else matches on procname and proctype
*   		proctype = 0, matches all proctypes
*
*****************************************************************************/
NLM_EXTERN ObjMgrProcPtr LIBCALL ObjMgrProcFind(ObjMgrPtr omp, Uint2 procid,
										CharPtr procname, Uint2 proctype)
{
	ObjMgrProcPtr ompp=NULL, PNTR omppp, tmp;
	Int4 i, imax;

	omppp = omp->proclist;
	imax = omp->currproc;

	if (procid)   /* procid lookup is different */
	{
		i = ObjMgrProcLookup(omp, procid);
		if (i >= 0)
			ompp = omppp[i];
		return ompp;
	}

	for (i = 0; i < imax; i++)
	{
		tmp = omppp[i];
		if ((! proctype) || (proctype == tmp->proctype))
		{
			if (! StringCmp(procname, tmp->procname))
				return tmp;
		}
	}
	return ompp;
}

/*****************************************************************************
*
*   ObjMgrGetProcID(omp, procname, proctype)
*   	returns procid given procname and proctype
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrGetProcID (ObjMgrPtr omp, CharPtr procname, Uint2 proctype)

{
	ObjMgrProcPtr  ompp;

	ompp = ObjMgrProcFind (omp, 0, procname, proctype);
	if (ompp == NULL) return 0;
	return ompp->procid;
}

/*****************************************************************************
*
*   ObjMgrProcFindNext(omp, proctype, inputtype, outputtype, last)
*   	looks for proctype of highest priority that
*   		matches inputtype and outputtype
*   	0 on proctype or inputtype or outputtype matches any
*   	if last != NULL, then gets next after last
*       if omp == NULL, will ObjMgrReadLock() and Unlock() within the function
*
*****************************************************************************/
NLM_EXTERN ObjMgrProcPtr LIBCALL ObjMgrProcFindNext (ObjMgrPtr tomp, Uint2 proctype,
						Uint2 inputtype, Uint2 outputtype, ObjMgrProcPtr last)
{
	ObjMgrPtr omp;
	ObjMgrProcPtr best = NULL, tmp, retval = NULL;
	Int4 i, bestpriority=-32766, imax, maxpriority=32767;
	ObjMgrProcPtr PNTR omppp;
	Boolean unlock = FALSE;

	if (tomp == NULL)
	{
		omp = ObjMgrReadLock();
		unlock = TRUE;
	}
	else
		omp = tomp;

	omppp = omp->proclist;
	imax = omp->currproc;

	if (last != NULL)
	{
		maxpriority = last->priority;
		i = ObjMgrProcLookup(omp, last->procid);
		i++;
		while (i < imax)  /* find next of equal priority */
		{
			tmp = omppp[i];
			if ((! proctype) || (tmp->proctype == proctype))
			{
				if ((! inputtype) || (tmp->inputtype == inputtype))
				{
					if ((! outputtype) || (tmp->outputtype == outputtype))
					{
						if (tmp->priority == maxpriority)
						{
							retval = tmp;
							goto erret;
						}
					}
				}
			}
			i++;
		}
	}

	for (i = 0; i < imax; i++)  /* find the highest priority less than any previous */
	{
		tmp = omppp[i];
		if ((! proctype) || (tmp->proctype == proctype))
		{
			if ((! inputtype) || (tmp->inputtype == inputtype))
			{
				if ((! outputtype) || (tmp->outputtype == outputtype))
				{
					if ((tmp->priority > bestpriority) &&
						(tmp->priority < maxpriority))
					{
						best = tmp;
						bestpriority = tmp->priority;
					}
				}
			}
		}

	}

	retval = best;
erret:
	if (unlock)
		ObjMgrUnlock();
	return retval;
}

NLM_EXTERN Int2 LIBCALL ObjMgrProcOpen (ObjMgrPtr omp, Uint2 outputtype)
{
	ObjMgrProcPtr ompp=NULL, currp=NULL;
	Int2 retval;
	Boolean did_one = FALSE;
	OMProcControl ompc;

	MemSet((Pointer)(&ompc), 0, sizeof(OMProcControl));
	ompc.output_itemtype = outputtype;

	while ((currp = ObjMgrProcFindNext(omp, OMPROC_OPEN, 0, outputtype, currp)) != NULL)
	{
		ompc.proc = currp;
		retval = (*(currp->func)) (&ompc);
		did_one = TRUE;
		if (retval == OM_MSG_RET_DONE)
			break;
	}

	if (! did_one)
	{
		ErrPostEx(SEV_ERROR,0,0, "No OPEN function found");
		retval = OM_MSG_RET_ERROR;
	}
	return retval;
}

NLM_EXTERN Uint2 LIBCALL OMGetNextUserKey (void)

{
  ObjMgrPtr  omp;
  Uint2 retval = 0;

  omp = ObjMgrWriteLock ();
  if (omp == NULL) return retval;
  (omp->HighestUserKey)++;
  if (omp->HighestUserKey == 0) {
    (omp->HighestUserKey)++;
  }
  retval = omp->HighestUserKey;
  ObjMgrUnlock();
  return retval;
}

/*****************************************************************************
*
*   Data Type Functions
*
*****************************************************************************/

static Int2 LIBCALLBACK ObjMgrDefaultLabelFunc ( Pointer data, CharPtr buffer, Int2 buflen, Uint1 content)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	ObjMgrTypePtr omtp;
	CharPtr label=NULL;
	static CharPtr defaultlabel="NoLabel";
	Int2 retval = 0;

	label = defaultlabel;
	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByData(omp, data);
	if (omdp != NULL)
	{
		omtp = ObjMgrTypeFind(omp, omdp->datatype, NULL, NULL);
		if (omtp != NULL)
		{
			if (omtp->label != NULL)
				label = omtp->label;
			else if (omtp->name != NULL)
				label = omtp->name;
			else
				label = omtp->asnname;
		}
	}

	retval = LabelCopy(buffer, label, buflen);
	ObjMgrUnlock();
	return retval;
}

static Uint2 LIBCALLBACK ObjMgrDefaultSubTypeFunc (Pointer ptr)
{
	return 0;
}

/*****************************************************************************
*
*   ObjMgrTypeExtend(omp)
*
*****************************************************************************/
static Boolean NEAR ObjMgrTypeExtend (ObjMgrPtr omp)
{
	Boolean result = FALSE;
	OMTypePtr omdp, prev=NULL;
	ObjMgrTypePtr PNTR tmp;
	Int4 i, j;

	for (omdp = omp->ncbitype; omdp != NULL; omdp = omdp->next)
		prev = omdp;

	omdp = (OMTypePtr)MemNew(sizeof(OMType));
	if (omdp == NULL) return result;
	tmp = (ObjMgrTypePtr PNTR)MemNew((size_t)(sizeof(ObjMgrTypePtr) * (omp->tottype + NUM_OMD)));
	if (tmp == NULL)
	{
		MemFree(omdp);
		return result;
	}

	if (prev != NULL)
	{
		prev->next = omdp;
		MemMove(tmp, omp->typelist, (size_t)(sizeof(ObjMgrTypePtr) * omp->tottype));
		MemFree(omp->typelist);
	}
	else
		omp->ncbitype = omdp;

	j = omp->tottype;

	for (i = 0; i < NUM_OMD; i++, j++)
		tmp[j] = &(omdp->data[i]);

	omp->tottype += NUM_OMD;
	omp->typelist = tmp;

	result = TRUE;
	return result;
}

/*****************************************************************************
*
*   ObjMgrTypeAddFunc(omp, type, data)
*   	adds a pointer (data) of type (type) to the sequence manager
*       Currently this MUST be predefined and < OBJ_MAX
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrTypeAdd (ObjMgrTypePtr data)
{
	ObjMgrPtr omp;
	ObjMgrTypePtr omdp;
	ObjMgrTypePtr PNTR omdpp;
	Int4 i, imin, imax;
	Uint2 tmp, type,retval = 0;

	if (data == NULL) return retval;

	omp = ObjMgrWriteLock();

	type = data->datatype;
	if ((! type) || (type >= OBJ_MAX))
	{
		/***
		type = ++(omp->HighestObjMgrType);
	    ***/

		ErrPostEx(SEV_ERROR, 0,0, "ObjMgrTypeAdd: Can't register new object types yet");
		goto erret;
	}

	if (omp->currtype >= omp->tottype)
	{
		if (! ObjMgrTypeExtend(omp))
			goto erret;
	}

	i = omp->currtype;
	omdpp = omp->typelist;
	omdp = omdpp[i];    /* emptys always at end */

	imin = 0;                   /* find where it goes */
	imax = omp->currtype-1;

	if ((i) && (type < omdpp[imax]->datatype))
	{
		i = (imax + imin) / 2;
		while (imax > imin)
		{
			tmp = omdpp[i]->datatype;
			if (tmp > type)
				imax = i - 1;
			else if (tmp < type)
				imin = i + 1;
			else
				break;
			i = (imax + imin)/2;
		}

		if (type > omdpp[i]->datatype)     /* check for off by 1 */
			i++;

		imax = omp->currtype - 1;	 /* open the array */
		while (imax >= i)
		{
			omdpp[imax+1] = omdpp[imax];
			imax--;
		}
	}

	omdpp[i] = omdp;    /* put in the pointer in order */
	omp->currtype++;     /* got one more */

	MemMove(omdp, data, sizeof(ObjMgrType));
	omdp->datatype = type;  /* fill in the values */
	omdp->asnname = StringSave(data->asnname);
	omdp->label = StringSave(data->label);
	omdp->name = StringSave(data->name);
	if (omdp->labelfunc == NULL)
		omdp->labelfunc = ObjMgrDefaultLabelFunc;
	if (omdp->subtypefunc == NULL)
		omdp->subtypefunc = ObjMgrDefaultSubTypeFunc;
	retval = type;
erret:
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrTypeLoad(args)
*
*****************************************************************************/
NLM_EXTERN Uint2 LIBCALL ObjMgrTypeLoad ( Uint2 type, CharPtr asnname,
		CharPtr label, CharPtr name, AsnTypePtr atp, OMNewFunc newfunc,
		AsnReadFunc asnread, AsnWriteFunc asnwrite, OMFreeFunc freefunc,
		OMLabelFunc labelfunc, OMSubTypeFunc subtypefunc)
{
	ObjMgrType omt;
	Uint2 newtype;

	MemSet((Pointer)(&omt), 0, sizeof(ObjMgrType));
	omt.datatype = type;
	omt.asnname = asnname;
	omt.label = label;
	omt.name = name;
	omt.atp = atp;
	omt.newfunc = newfunc;
	omt.asnread = asnread;
	omt.asnwrite = asnwrite;
	omt.freefunc = freefunc;
	omt.labelfunc = labelfunc;
	omt.subtypefunc = subtypefunc;

	newtype = ObjMgrTypeAdd(&omt);

	return newtype;
}

/*****************************************************************************
*
*   ObjMgrTypeLookup(omp, data)
*   	Binary lookup of data in omp->typelist
*   	returns index (>=0) if found
*       returns -1 if not found
*
*****************************************************************************/
NLM_EXTERN Int4 LIBCALL ObjMgrTypeLookup(ObjMgrPtr omp, Uint2 data)
{
	Int4 imin, imax, i;
	ObjMgrTypePtr PNTR omdpp;
	Uint2 tmp;

	imin = 0;
	imax = omp->currtype - 1;
	omdpp = omp->typelist;

	while (imax >= imin)
	{
		i = (imax + imin)/2;
		tmp = omdpp[i]->datatype;
		if (tmp > data)
			imax = i - 1;
		else if (tmp < data)
			imin = i + 1;
		else
			return i;
	}

	return (Int4)(-1);
}

/*****************************************************************************
*
*   ObjMgrTypeFind(omp, type, asnname, name)
*   	returns the objmgrptr by looking for
*   		type: if type != 0
*   		asnname: if asnname != NULL
*   		name: if name != NULL
*       in that order of preference.
*       if omp == NULL, then does temporary read lock in this function
*   	returns NULL if can't match on highest priority key
*
*****************************************************************************/
NLM_EXTERN ObjMgrTypePtr LIBCALL ObjMgrTypeFind (ObjMgrPtr tomp, Uint2 type, CharPtr asnname, CharPtr name)
{
	ObjMgrTypePtr omtp = NULL;
	ObjMgrTypePtr PNTR omdpp;
	Int4 i, imax, result;
	ObjMgrPtr omp;
	Boolean unlock = FALSE;

	if (tomp == NULL)
	{
		omp = ObjMgrReadLock();
		unlock = TRUE;
	}
	else
		omp = tomp;

	omdpp = omp->typelist;
	imax = omp->currtype;
	if (type)
	{
		i = ObjMgrTypeLookup(omp, type);
		if (i >= 0)
			omtp = omdpp[i];
	}
	else
	{
		for (i = 0; i < imax; i++)
		{
			if (asnname != NULL)
				result = StringCmp(omdpp[i]->asnname, asnname);
			else
				result = StringCmp(omdpp[i]->name, name);
			if (! result)
			{
				omtp = omdpp[i];
				break;
			}
		}
	}

	if (unlock)
		ObjMgrUnlock();

	return omtp;
}

/*****************************************************************************
*
*   ObjMgrTypeSetLabelFunc(type, labelfunc)
*   	replaces the labelfunc for type with a new one
*   	can also set it for the first time
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrTypeSetLabelFunc(Uint2 type, OMLabelFunc labelfunc)
{
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	omtp = ObjMgrTypeFind(omp, type, NULL, NULL);
	if (omtp != NULL)
	{
		omtp->labelfunc = labelfunc;
		retval = TRUE;
	}
	ObjMgrUnlock();
	return retval;
}

/**************************************************************************
*
* ObjMgrTypeFindNext(omp, omtp)
*    returns next ObjMgrType after omtp
*    Exhaustively traverses registered types if omtp starts as NULL
*
***************************************************************************/		
NLM_EXTERN ObjMgrTypePtr LIBCALL ObjMgrTypeFindNext (ObjMgrPtr omp, ObjMgrTypePtr last)
{
	ObjMgrTypePtr PNTR omdpp;
	Int4 i, imax;
	Boolean got_it = FALSE;

	omdpp = omp->typelist;
	imax = omp->currtype;
	if (last == NULL)   /* take the first one */
		got_it = TRUE;
	for (i = 0; i < imax; i++)
	{
		if (got_it)
			return omdpp[i];
			
		if (omdpp[i] == last)
			got_it = TRUE;
	}
	
	return NULL;
}

/*****************************************************************************
*
*   Selection Functions for data objects
*
*****************************************************************************/
static Boolean NEAR ObjMgrSendSelMsg (ObjMgrPtr omp, Uint2 entityID,
         Uint2 itemID, Uint2 itemtype, Uint1 regiontype, Pointer region)
{
        ObjMgrDataPtr omdp;
        OMMsgStruct ommds;

        omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
        if (omdp == NULL)
           return FALSE;

        MemSet((Pointer)(&ommds), 0, sizeof(OMMsgStruct));
        ommds.message = OM_MSG_SELECT;
        ommds.entityID = entityID;
        ommds.itemtype = itemtype;
        ommds.itemID = itemID;
        ommds.regiontype = regiontype;
        ommds.region = region;

        ObjMgrSendStructMsgFunc(omp, omdp, &ommds);
	return TRUE;
}

static Boolean NEAR ObjMgrSendDeSelMsg (ObjMgrPtr omp, Uint2 entityID,
         Uint2 itemID, Uint2 itemtype, Uint1 regiontype, Pointer region)
{
        ObjMgrDataPtr omdp;
        OMMsgStruct ommds;

        omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
        if (omdp == NULL)
           return FALSE;

        MemSet((Pointer)(&ommds), 0, sizeof(OMMsgStruct));
        ommds.message = OM_MSG_DESELECT;
        ommds.entityID = entityID;
        ommds.itemtype = itemtype;
        ommds.itemID = itemID;
        ommds.regiontype = regiontype;
        ommds.region = region;

	ObjMgrSendStructMsgFunc(omp, omdp, &ommds);
	return TRUE;
}

static SelStructPtr NEAR ObjMgrAddSelStruct (ObjMgrPtr omp, Uint2 entityID,
		 Uint2 itemID, Uint2 itemtype, Uint1 regiontype, Pointer region)
{
	SelStructPtr ssp, tmp;

	tmp = omp->sel;

	if (tmp != NULL)
	{
		while (tmp->next != NULL)
			tmp = tmp->next;
	}

	ssp = MemNew(sizeof(SelStruct));
	if (tmp != NULL)
	{
		tmp->next = ssp;
		ssp->prev = tmp;
	}
	else
		omp->sel = ssp;

	ssp->entityID = entityID;
	ssp->itemID = itemID;
	ssp->itemtype = itemtype;
	ssp->regiontype = regiontype;
	ssp->region = region;

	return ssp;
}


static Boolean NEAR ObjMgrDeSelectStructFunc (ObjMgrPtr omp, SelStructPtr ssp)
{
	SelStructPtr next, prev;

	if (ssp == NULL) 
		return FALSE;

	next = ssp->next;
	prev = ssp->prev;
	if (prev != NULL)
		prev->next = next;
	else
		omp->sel = next;
	if (next != NULL)
		next->prev = prev;

        ObjMgrSendDeSelMsg (omp, ssp->entityID, ssp->itemID, ssp->itemtype, ssp->regiontype, ssp->region);

	ObjMgrRegionFree(omp, ssp->regiontype, ssp->region); /* free any region */

	MemFree(ssp);

	return TRUE;
}

static Boolean NEAR ObjMgrDeSelectAllFunc (ObjMgrPtr omp)
{
	SelStructPtr tmp, prev;

	tmp = omp->sel;
	if (tmp == NULL)
		return TRUE;

	prev = NULL;

	while (tmp->next != NULL)
	{
		prev = tmp;
		tmp = tmp->next;
	}

	while (tmp != NULL)
	{
		ObjMgrDeSelectStructFunc(omp, tmp);
		tmp = prev;
		if (tmp != NULL)
			prev = tmp->prev;
	}

	return TRUE;
}

static Boolean NEAR ObjMgrRegionMatch (Uint1 regiontype1, Pointer region1,
					Uint1 regiontype2, Pointer region2)
{
	SeqLocPtr slp;
	SeqIntPtr sip1, sip2;

	if (regiontype1 != regiontype2) return FALSE;
	if (! regiontype1) return FALSE;
	if ((region1 == NULL) || (region2 == NULL))	 return FALSE;

	switch (regiontype1)
	{
		case OM_REGION_SEQLOC:    /* SeqLocs of type SeqInt */
			slp = (SeqLocPtr)region1;
			sip1 = (SeqIntPtr)(slp->data.ptrvalue);
			slp = (SeqLocPtr)(region2);
			sip2 = (SeqIntPtr)(slp->data.ptrvalue);
			if (sip1 == NULL || sip2 == NULL) return FALSE;
			if ( ((sip1->from == sip2->from) &&
				(sip1->to == sip2->to)))
                       /* get rid of (sip1->strand == sip2->strand) */
					return TRUE;
			break;
		default:
			break;
	}
	return FALSE;	
}

static Pointer NEAR ObjMgrRegionCopy (ObjMgrPtr omp, Uint1 regiontype, Pointer region)
{
	Pointer newregion = NULL;

	if (region != NULL)
	{
		switch (regiontype)
		{
			case OM_REGION_SEQLOC:
				newregion = ObjMgrMemCopyFunc(omp, OBJ_SEQLOC, region, FALSE);
				break;
			default:
				break;
		}
	}
	return newregion;
}

static Pointer NEAR ObjMgrRegionFree (ObjMgrPtr omp, Uint1 regiontype, Pointer region)
{
	if (region != NULL)
	{
		switch (regiontype)
		{
			case OM_REGION_SEQLOC:
				ObjMgrFreeFunc(omp, OBJ_SEQLOC, region, FALSE);
				break;
			default:
				break;
		}
	}

	return NULL;
}

/*****************************************************************************
*
*   ObjMgrSelect(entityID, itemID, itemtype)
*      if entityID == 0, just deselects everything
*      if entityID,itemID, itemtype already selected, deselects everything else
*      if something else selected, deselects it first, then selects requested
*        item
*      returns TRUE if item is now currently selected, FALSE if not
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSelect (Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	retval = ObjMgrSelectFunc(omp, entityID, itemID, itemtype,
		        regiontype, region);
	ObjMgrUnlock();
	return retval;
}


/*****************************************************************************
*
*   ObjMgrSelect(entityID, itemID, itemtype)
*      if entityID == 0, just deselects everything
*      if entityID,itemID, itemtype already selected, deselects everything else
*      if something else selected, deselects it first, then selects requested
*        item
*      returns TRUE if item is now currently selected, FALSE if not
*
*****************************************************************************/
static Boolean NEAR ObjMgrSelectFunc (ObjMgrPtr omp, Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region)
{
	SelStructPtr ssp, next;
	Boolean was_selected = FALSE, is_selected, remove_this, retval = TRUE;


	if (entityID == 0)    /* desktop */
	{
		ObjMgrDeSelectAllFunc(omp);
		goto erret;
	}
	else
	{
		ssp = omp->sel;
		while (ssp != NULL)
		{
			remove_this = TRUE;
			next = ssp->next;
			if (ssp->entityID == entityID)
			{
				if ((ssp->itemID == itemID) || (! itemID))
				{
					if ((ssp->itemtype == itemtype) || (! itemtype))
					{
						if ((ssp->regiontype == regiontype) || (! regiontype))
						{
							is_selected = TRUE;
							if (regiontype)
								is_selected = ObjMgrRegionMatch(ssp->regiontype,
									ssp->region, regiontype, region);
							if (is_selected)
							{
								remove_this = FALSE;
								was_selected = TRUE;
							}
						}
					}
				}
			}
			if (remove_this)
				ObjMgrDeSelectStructFunc(omp, ssp);

			ssp = next;
		}
	}

	if (was_selected)  /* no more action needed */
	{
		retval = TRUE;
	}
	else
	{
		ssp = ObjMgrAddSelStruct(omp, entityID, itemID, itemtype, regiontype, region);

		if (ssp != NULL)
			retval = ObjMgrSendSelMsg(omp, entityID, itemID, itemtype, regiontype, region);;
	}

erret:
	return retval;

}

static SeqLocPtr SeqLocChangeIntervalle (SeqLocPtr slp, Int4 start, Int4 stop)
{
        SeqIntPtr sip;

        sip = (SeqIntPtr)(slp->data.ptrvalue);
        if (start > -1)
                sip->from = start;
        if (stop > -1)
                sip->to = stop;
        return slp;
}

static Int2 NEAR ObjMgrRegionComp (Pointer region1,Pointer region2, Boolean direction2_plus)
{
        SeqLocPtr slp1, slp2;
        Int2      res;

        if ((region1 == NULL) || (region2 == NULL))      
           return FALSE;

        slp1 = (SeqLocPtr)region1;
        slp2 = (SeqLocPtr)region2;
        res = SeqLocCompare (slp1,slp2);
        if (res == SLC_NO_MATCH)
        {
           if (SeqLocStop(slp1) == SeqLocStart(slp2)-1)
              return 2;
           if (SeqLocStart(slp1) == SeqLocStop(slp2)+1)
              return 3;
           return 0;
        }
        if (res == SLC_A_EQ_B)
           return 1;
        if (res == SLC_B_IN_A)
        {
	   if (SeqLocStart(slp1)==SeqLocStart(slp2))
              return 5;
           if (SeqLocStop(slp1)==SeqLocStop(slp2))
              return 6;
           if (direction2_plus)
              return 5;
           else
              return 6;
        }
        if (res == SLC_A_IN_B)
           return 4;
        if (res == SLC_A_OVERLAP_B)
        {
           if (SeqLocStart(slp1) < SeqLocStart(slp2))
              return 2;
           if (SeqLocStart(slp1) > SeqLocStart(slp2))
              return 3;
        }
        return 0;
}


static Boolean NEAR ObjMgrSelectFunc2 
(ObjMgrPtr omp, Uint2 entityID, Uint2 itemID, Uint2 itemtype, Uint1 regiontype, Pointer region)
{
        SelStructPtr ssp, next;
        Boolean      retval = FALSE;
	SeqLocPtr    tmp = NULL,
                     tmp2 = NULL;
        Int2         res=0;
	Boolean direction_plus = TRUE;

        if (entityID == 0)    /* desktop */
        {
                ObjMgrDeSelectAllFunc(omp);
                goto erret;
        }
        else if (region)
        {
/***** Colombe Patrick ****/
/** send Seq_strand_minus seqloc of selection when the cursor moves to the left **/
/** the Seq_strand_minus is now change to Seq_strand_plus     for ever **/

           if (SeqLocStrand(region)==Seq_strand_minus)
	   {
SeqIntPtr sit;
SeqLocPtr slp;
      	      slp = (SeqLocPtr)region;
	      sit = (SeqIntPtr)(slp->data.ptrvalue);
	      sit->strand = Seq_strand_plus;
              direction_plus=FALSE;
	   }
/***** Colombe Patrick ****/
                ssp = omp->sel;
                while (ssp != NULL && res == 0)
                {
                        next = ssp->next;
                        if (ssp->entityID == entityID)
                        {
                                if ((ssp->itemID == itemID) || (! itemID))
                                {
                                        if ((ssp->itemtype == itemtype) || (! itemtype))
                                        {
                                                if (ssp->regiontype && regiontype)
                                                {
                                                        res = ObjMgrRegionComp (ssp->region, region, direction_plus);
							if (res>0)
								break;
                                                }
                                        }
                                }
                        }
                        ssp = next;
                }
        }
        if (res==2)  /* extend ssp->region to right */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp->region, -1, SeqLocStop(region));
                retval=ObjMgrSendSelMsg (omp, entityID, itemID, itemtype, ssp->regiontype, ssp->region);
        }
        else if (res==3)   /* extend ssp->region to left */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp->region, SeqLocStart(region), -1);
                retval=ObjMgrSendSelMsg (omp, entityID, itemID, itemtype, ssp->regiontype, ssp->region);
        }
        else if (res==4)   /* extend ssp->regiontype both sides */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp->region, SeqLocStart(region), SeqLocStop(region));
                retval=ObjMgrSendSelMsg (omp, entityID, itemID, itemtype, ssp->regiontype, ssp->region);
        }
        else if (res==5)  /* shrink ssp->region from right */
        {
                tmp = SeqLocIntNew (SeqLocStart((SeqLocPtr)ssp->region), SeqLocStop((SeqLocPtr)region), 0, SeqLocId(region));
                tmp2 = SeqLocIntNew (SeqLocStop((SeqLocPtr)region)+1, SeqLocStop((SeqLocPtr)ssp->region), 0, SeqLocId(region));
                SeqLocChangeIntervalle ((SeqLocPtr)ssp->region, -1, (Int4)(SeqLocStop(region)));
		ValNodeFree (tmp);
                retval=ObjMgrSendDeSelMsg (omp, entityID, itemID, itemtype, OM_REGION_SEQLOC, tmp2);

		ValNodeFree (tmp2);
        }
        else if (res==6) /* shrink ssp->region from left */
        {
                tmp = SeqLocIntNew (SeqLocStart((SeqLocPtr)region), SeqLocStop((SeqLocPtr)ssp->region), 0, SeqLocId(region));
                tmp2 = SeqLocIntNew (SeqLocStart((SeqLocPtr)ssp->region), SeqLocStart((SeqLocPtr)region)-1, 0, SeqLocId(region));
                SeqLocChangeIntervalle ((SeqLocPtr)ssp->region, (Int4)(SeqLocStart(region)), -1);
		ValNodeFree (tmp);
                retval=ObjMgrSendDeSelMsg (omp, entityID, itemID, itemtype, OM_REGION_SEQLOC, tmp2);
		ValNodeFree (tmp2);
        }
        else if (res==0)
        {
                ssp = ObjMgrAddSelStruct(omp, entityID, itemID, itemtype, regiontype, region);
                if (ssp != NULL)
                        retval=ObjMgrSendSelMsg (omp, entityID, itemID, itemtype, regiontype, region);
        }

erret:
        return (Boolean)(res>0);

}

static Boolean NEAR CheckRedondantSelect (ObjMgrPtr omp)
{
        SelStructPtr ssp1, 
        		ssp2,
        		next1,
        		next2, pre2;
        SeqLocPtr    tmp;
        Boolean      retval = FALSE;
        Int2         res=0;

        if (omp!=NULL)   
        {
                ssp1 = omp->sel;
                while (ssp1 != NULL && res==0)
                {
                   next1 = ssp1->next;
                   ssp2=next1;
                   pre2=ssp1;
                   while (ssp2!=NULL && res==0)
                   {
                   	next2 = ssp2->next;
                        if (ssp1->entityID == ssp2->entityID)
                        {
                                if (ssp1->itemID == ssp2->itemID)
                                {
                                        if (ssp1->itemtype == ssp2->itemtype)
                                        {
                                                if (ssp1->regiontype && ssp2->regiontype)
                                                {
                                                        res = ObjMgrRegionComp (ssp1->region, ssp2->region, TRUE);
							if (res>0)
								break;
                                                }
                                        }
                                }
                        }
                        ssp2 = next2;
                   }
                   if (res==0)
			ssp1 = next1;
                }
        }
	if (res==1)
	{
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);
                ObjMgrSendSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
                retval=TRUE;
	}
        else if (res==2)  /* extend ssp->regiontype to right */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp1->region, -1, SeqLocStop(ssp2->region));
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);                
                ObjMgrSendSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
                retval=TRUE;
        }
        else if (res==3)   /* extend ssp->regiontype to left */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp1->region, SeqLocStart(ssp2->region), -1);
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);                
                ObjMgrSendSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
                retval=TRUE;
        }
        else if (res==4)   /* extend ssp->regiontype both sides */
        {
                SeqLocChangeIntervalle ((SeqLocPtr)ssp1->region, SeqLocStart(ssp2->region), SeqLocStop(ssp2->region));
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);                
                ObjMgrSendSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
                retval=TRUE;
        }
        else if (res==5)  /* shrink ssp->region from right */
        {
		tmp = SeqLocIntNew (SeqLocStart((SeqLocPtr)ssp1->region), SeqLocStop(ssp2->region), 0, SeqLocId(ssp2->region));
                SeqLocChangeIntervalle ((SeqLocPtr)ssp1->region, -1, SeqLocStop(ssp2->region));
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);                
                ObjMgrSendDeSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
		ValNodeFree (tmp);
                retval=TRUE;
        }
        else if (res==6) /* shrink ssp->region from left */
        {
                tmp = SeqLocIntNew (SeqLocStart(ssp2->region), SeqLocStop((SeqLocPtr)ssp1->region), 0, SeqLocId(ssp2->region));
                SeqLocChangeIntervalle ((SeqLocPtr)ssp1->region, SeqLocStart(ssp2->region), -1);
       		pre2->next=next2;
       		ssp2=MemFree(ssp2);                
                ObjMgrSendDeSelMsg (omp, ssp1->entityID, ssp1->itemID, ssp1->itemtype, 0, 0);
		ValNodeFree (tmp);
                retval=TRUE;
        }
        return retval;
}



/*****************************************************************************
*
*   ObjMgrSetColor(entityID, itemID, itemtype, regiontype, region, rgb);
*      Sets color of object in displays
*      if regiontype != 0, and restricts to region
*      rgb is a pointer to a Uint1[3] array containing an RGB value.
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSetColor (Uint2 entityID, Uint2 itemID,
                                        Uint2 itemtype, Uint1 regiontype,
                                        Pointer region, Uint1Ptr rgb)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	OMMsgStruct ommds;
	Boolean retval = FALSE;

	omp = ObjMgrReadLock();

	if (rgb == NULL) goto erret;

	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp == NULL) goto erret;

	MemSet((Pointer)(&ommds), 0, sizeof(OMMsgStruct));
	ommds.message = OM_MSG_SETCOLOR;
	ommds.entityID = entityID;
	ommds.itemtype = itemtype;
	ommds.itemID = itemID;
	ommds.regiontype = regiontype;
	ommds.region = region;
        ommds.rgb[0] = rgb[0];
        ommds.rgb[1] = rgb[1];
        ommds.rgb[2] = rgb[2];

                                /* send the message */
	ObjMgrSendStructMsgFunc(omp, omdp, &ommds);
                                /* free the region */
	retval = TRUE;
erret:
	ObjMgrUnlock();

	return retval;
}
/*****************************************************************************
*
*   ObjMgrDeSelect(entityID, itemID, itemtype)
*   	if this item was selected, then deselects and returns TRUE
*   	else returns FALSE
*
*****************************************************************************/

NLM_EXTERN Boolean LIBCALL ObjMgrDeSelect (Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region)
{
	ObjMgrPtr omp;
	Boolean retval=FALSE;

	omp = ObjMgrWriteLock();
	retval = ObjMgrDeSelectFunc (omp, entityID, itemID, itemtype,
				regiontype, region);
	ObjMgrUnlock();
	return retval;
}


/*****************************************************************************
*
*   ObjMgrDeSelect(entityID, itemID, itemtype)
*   	if this item was selected, then deselects and returns TRUE
*   	else returns FALSE
*
*****************************************************************************/

static Boolean NEAR ObjMgrDeSelectFunc (ObjMgrPtr omp, Uint2 entityID, Uint2 itemID, Uint2 itemtype,
									Uint1 regiontype, Pointer region)
{
	SelStructPtr tmp, next;
	Boolean retval=FALSE, tret, do_it;
	SeqLocPtr slp;

	if (entityID == 0)
	{
		retval = ObjMgrDeSelectAllFunc(omp);
		goto erret;
	}

	tmp = omp->sel;
	while (tmp != NULL)
	{
		next = tmp->next;
		do_it = FALSE;
		if (tmp->entityID == entityID)
		{
			if ((! itemtype) || (itemtype == tmp->itemtype))
			{
				if ((! itemID) || (itemID == tmp->itemID))
				{
					if ((tmp->regiontype == regiontype) || (! regiontype))
					{
						do_it = TRUE;
						if (regiontype)
							do_it = ObjMgrRegionMatch(tmp->regiontype,
								tmp->region, regiontype, region);
						if (do_it)
						{
							tret = ObjMgrDeSelectStructFunc(omp, tmp);
							if (tret)
								retval = TRUE;
						}
                                                else if (SeqLocCompare(tmp->region, region)==SLC_B_IN_A)
						{
							if (SeqLocStart(tmp->region)==SeqLocStart(region))
							{
                						SeqLocChangeIntervalle ((SeqLocPtr)tmp->region, (Int4)(SeqLocStop(region)+1), -1);
                						retval=ObjMgrSendDeSelMsg (omp, entityID, itemID, itemtype, OM_REGION_SEQLOC, region);
							}
							else if (SeqLocStop(tmp->region)==SeqLocStop(region))
							{
								SeqLocChangeIntervalle ((SeqLocPtr)tmp->region, -1, (Int4)(SeqLocStart(region)-1));
								retval=ObjMgrSendDeSelMsg (omp, entityID, itemID, itemtype, OM_REGION_SEQLOC, region);
							}
							else {
								slp=SeqLocIntNew(SeqLocStop(region)+1, SeqLocStop((SeqLocPtr)tmp->region), 0, SeqLocId(tmp->region));
				 				SeqLocChangeIntervalle ((SeqLocPtr)tmp->region, -1, (Int4)(SeqLocStart(region)-1));
                						ObjMgrAddSelStruct(omp, entityID, itemID, itemtype, regiontype, slp);
                                                                retval=ObjMgrSendDeSelMsg (omp, entityID, itemID, itemtype, OM_REGION_SEQLOC, region);

							}
						}
					}
				}
			}
		}
		tmp = next;
	}

erret:
	return retval;
}

NLM_EXTERN Boolean LIBCALL ObjMgrAlsoSelect (Uint2 entityID, Uint2 itemID,
					 Uint2 itemtype, Uint1 regiontype, Pointer region)
{
	ObjMgrPtr omp;
	Boolean retval;
				/* if already selected, just deselect */
/**
	if (ObjMgrDeSelect(entityID, itemID, itemtype, regiontype, region))
		return FALSE;
**/
	omp = ObjMgrWriteLock();

	retval = ObjMgrSelectFunc2 (omp, entityID, itemID, itemtype, regiontype, region);
	if (retval) {
		while (retval)
			retval=CheckRedondantSelect (omp);
	}
	ObjMgrUnlock();

        return retval;

}

NLM_EXTERN Boolean LIBCALL ObjMgrDeSelectAll (void)
{
	ObjMgrPtr omp;
	Boolean retval = FALSE;

	omp = ObjMgrWriteLock();
	retval = ObjMgrDeSelectAllFunc(omp);
	ObjMgrUnlock();
	return retval;
}

NLM_EXTERN SelStructPtr LIBCALL ObjMgrGetSelected (void)
{
	ObjMgrPtr omp;
	SelStructPtr sel;

	omp = ObjMgrReadLock();
	sel = omp->sel;
	ObjMgrUnlock();
	return sel;
}

/*****************************************************************************
*
*   ObjMgrSendMsg(msg, entityID, itemID, itemtype)
*       Directly invokes the objmgr messaging system
*       should be used cautiously
*
*****************************************************************************/
NLM_EXTERN Boolean LIBCALL ObjMgrSendMsg(Uint2 msg, Uint2 entityID, Uint2 itemID, Uint2 itemtype)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	if (msg == OM_MSG_UPDATE) {
		SeqMgrClearFeatureIndexes (entityID, NULL);
	} else if (msg == OM_MSG_DEL)
		SeqMgrClearFeatureIndexes (entityID, NULL);
	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp != NULL)
	{
		ObjMgrSendMsgFunc(omp, omdp, msg, entityID, itemID, itemtype, 0, 0, 0, NULL);
		retval = TRUE;
	}
	ObjMgrUnlock();
	return retval;
}

NLM_EXTERN Boolean LIBCALL ObjMgrSendProcMsg(Uint2 msg, Uint2 entityID, Uint2 itemID, Uint2 itemtype,
                                             Uint2 fromProcID, Uint2 toProcID, Pointer procmsgdata)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp != NULL)
	{
		ObjMgrSendMsgFunc(omp, omdp, msg, entityID, itemID, itemtype, 0, fromProcID, toProcID, procmsgdata);
		retval = TRUE;
	}
	ObjMgrUnlock();
	return retval;
}

NLM_EXTERN Boolean LIBCALL ObjMgrSendRowMsg(Uint2 msg, Uint2 entityID, Uint2 itemID, Uint2 itemtype, Uint2 rowID)
{
	ObjMgrPtr omp;
	ObjMgrDataPtr omdp;
	Boolean retval = FALSE;

	omp = ObjMgrReadLock();
	omdp = ObjMgrFindByEntityID(omp, entityID, NULL);
	if (omdp != NULL)
	{
		ObjMgrSendMsgFunc(omp, omdp, msg, entityID, itemID, itemtype, rowID, 0, 0, NULL);
		retval = TRUE;
	}
	ObjMgrUnlock();
	return retval;
}

/*****************************************************************************
*
*   ObjMgrGenericAsnTextFileRead(filename, datatypeptr, entityIDptr)
*      reads an asn1 text file for any datatype registered with the ObjMgr.
*      filename may contain a path
*      scans the start of the file to figure out the type.
*
*      if it fails, it returns NULL
*      if it succeeds, it returns a Pointer to the loaded data object
*          if datatypeptr is not NULL, fills it in with the proper OBJ_...
*          if entityIDptr is not NULL,
*                 it registers the data with the object manager
*                 it fills in entityIDptr with the entityID of the loaded object
*
*****************************************************************************/
NLM_EXTERN Pointer LIBCALL ObjMgrGenericAsnTextFileRead (CharPtr filename,
                                   Uint2Ptr datatypeptr, Uint2Ptr entityIDptr)
{
	Char line[255];
	FILE * fp;
	AsnIoPtr aip;
	Pointer ptr = NULL;
	Int2 ct, i;
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp = NULL;

	if (filename == NULL)
		return ptr;

	if (datatypeptr != NULL) *datatypeptr = 0;
	if (entityIDptr != NULL) *entityIDptr = 0;

	fp = FileOpen(filename, "r");
	ct = FileRead(line, 1, 255, fp);
	for (i = 0; i < ct; i++)
	{
		if (line[i] == ':')
		{
			if ((line[i+1] == ':') && (line[i+2] == '='))
			{
				line[i] = '\0';
				i--;
				while ((i >= 0) && (IS_WHITESP(line[i])))
				{
					line[i] = '\0';
					i--;
				}
				while ((i >= 0) && (! IS_WHITESP(line[i])))
					i--;
				omp = ObjMgrReadLock();
				omtp = ObjMgrTypeFind(omp, 0, &(line[i+1]), NULL);
				ObjMgrUnlock();
				if (omtp == NULL)
				{
					FileClose(fp);
					ErrPostEx(SEV_ERROR, 0,0, "Can't read ASN.1 type [%s]",
						&(line[i+1]));
					return ptr;
				}
				break;
			}
		}
	}
	
	if (omtp == NULL)
	{
		FileClose(fp);
		ErrPostEx(SEV_ERROR,0,0,"Don't know how to read file [%s]", filename);
		return ptr;
	}
	
	fseek(fp, (long)(i+1), SEEK_SET);
	aip = AsnIoNew(ASNIO_TEXT_IN, fp, NULL, NULL, NULL);
	if (aip != NULL)
		aip->fname = StringSave(filename);
	ptr = (*(omtp->asnread))(aip, NULL);
	AsnIoClose(aip);
	if (ptr == NULL)
	{
		ErrPostEx(SEV_ERROR,0,0,"Couldn't read [%s], type [%s]", filename, omtp->asnname);
	}
	else
	{
		if (datatypeptr != NULL)
			*datatypeptr = omtp->datatype;
		if (entityIDptr != NULL)
			*entityIDptr = ObjMgrRegister(omtp->datatype, ptr);
	}
	
	return ptr;
}

/***********************************************************************************
*
*  ObjMgrMemCopy(type, ptr)
*    Uses AsnIoMemCopy to make a copy of any ObjMgr supported type
*    ObjMgrType for "type" must have been previously loaded
*
***********************************************************************************/
NLM_EXTERN Pointer LIBCALL ObjMgrMemCopy (Uint2 type, Pointer ptr)
{
	Pointer newptr = NULL;
	ObjMgrPtr omp;

	if (ptr == NULL) return newptr;

 	omp = ObjMgrReadLock();
	newptr = ObjMgrMemCopyFunc(omp, type, ptr, TRUE);

	return newptr;
}

static Pointer NEAR ObjMgrMemCopyFunc (ObjMgrPtr omp, Uint2 type, Pointer ptr, Boolean unlock)
{
	Pointer newptr = NULL;
	ObjMgrTypePtr omtp;

	if (ptr == NULL) {

            if (unlock)
		ObjMgrUnlock();
            
            return newptr;
        }

	omtp = ObjMgrTypeFind(omp, type, NULL, NULL);
	if (unlock)
		ObjMgrUnlock();
	if (omtp == NULL) return newptr;

	newptr = AsnIoMemCopy(ptr, omtp->asnread, omtp->asnwrite);

	return newptr;
}

/***********************************************************************************
*
*  ObjMgrFree(type, ptr)
*    ObjMgrType for "type" must have been previously loaded
*
***********************************************************************************/
NLM_EXTERN Pointer LIBCALL ObjMgrFree (Uint2 type, Pointer ptr)
{
	Pointer newptr = NULL;
	ObjMgrPtr omp;

	if (ptr == NULL) return newptr;

 	omp = ObjMgrReadLock();
	newptr = ObjMgrFreeFunc(omp, type, ptr, TRUE);

	return newptr;
}

NLM_EXTERN Pointer LIBCALL ObjMgrFreeByEntityID (Uint2 entityID)
{
	ObjMgrDataPtr omdp;
	Uint2 type;
	Pointer ptr;

	if (entityID < 1) return NULL;
	omdp = ObjMgrGetData (entityID);
	if (omdp == NULL) return NULL;

	if (omdp->choice != NULL) {
		type = omdp->choicetype;
		ptr = omdp->choice;
	} else {
		type = omdp->datatype;
		ptr = omdp->dataptr;
	}

	return ObjMgrFree (type, ptr);
}

static Pointer NEAR ObjMgrFreeFunc (ObjMgrPtr omp, Uint2 type, Pointer ptr, Boolean unlock)
{
	Pointer newptr = NULL;
	ObjMgrTypePtr omtp;

	if (ptr == NULL) {
            if (unlock)
		ObjMgrUnlock();
            return newptr;
        }

	omtp = ObjMgrTypeFind(omp, type, NULL, NULL);

	if (unlock)
		ObjMgrUnlock();
	if (omtp == NULL) return newptr;
	(*(omtp->freefunc))(ptr);

	return newptr;
}

NLM_EXTERN void LIBCALL ObjMgrResetAll (void)
{
    Int4 ret;
    
    if (global_omp == NULL)
        return;
    
    ret = NlmMutexLockEx(&omp_mutex);  /* protect this section */
    if (ret) { /* error */
        ErrPostEx(SEV_FATAL,0,0,"ObjMgrResetAll failed [%ld]", (long)ret);
        return;
    }
    
    global_omp = (ObjMgrPtr) MemFree(global_omp);
    NlmRWdestroy(omp_RWlock);
    omp_RWlock = NULL;
    
    NlmMutexUnlock(omp_mutex);
    
    return;
}

static CharPtr objmgrtypestrs [] = {
  "OBJ_ALL", "OBJ_SEQENTRY", "OBJ_BIOSEQ", "OBJ_BIOSEQSET", "OBJ_SEQDESC",
  "OBJ_SEQANNOT", "OBJ_ANNOTDESC", "OBJ_SEQFEAT", "OBJ_SEQALIGN", "OBJ_SEQGRAPH",
  "OBJ_SEQSUB", "OBJ_SUBMIT_BLOCK", "OBJ_SEQSUB_CONTACT", "13", "OBJ_BIOSEQ_MAPFEAT",
  "OBJ_BIOSEQ_SEG", "OBJ_SEQHIST", "OBJ_SEQHIST_ALIGN", "OBJ_BIOSEQ_DELTA", "19",
  "OBJ_PUB", "OBJ_SEQFEAT_CIT", "OBJ_SEQSUB_CIT", "OBJ_MEDLINE_ENTRY", "OBJ_PUB_SET",
  "OBJ_SEQLOC", "OBJ_SEQID", "OBJ_SEQCODE", "OBJ_SEQCODE_SET", "OBJ_GENETIC_CODE",
  "OBJ_GENETIC_CODE_SET", "OBJ_TEXT_REPORT", "OBJ_FASTA", "OBJ_VIBRANT_PICTURE", "OBJ_PROJECT"
};

static CharPtr temploadstrs [] = {
  "TL_NOT_TEMP", "TL_LOADED", "TL_CACHED"
};

static CharPtr proctypestrs [] = {
  "0", "OMPROC_OPEN", "OMPROC_DELETE", "OMPROC_VIEW", "OMPROC_EDIT",
  "OMPROC_SAVE", "OMPROC_CUT", "OMPROC_COPY", "OMPROC_PASTE", "OMPROC_ANALYZE",
  "OMPROC_FIND", "OMPROC_REPLACE", "OMPROC_FILTER", "OMPROC_FETCH",
};

static void PrintABool (FILE *fp, CharPtr str, Boolean val)

{
  if (val) {
    fprintf (fp, "%s TRUE\n", str);
  } else {
    fprintf (fp, "%s FALSE\n", str);
  }
}

static void ReportOnEntity (ObjMgrDataPtr omdp, ObjMgrPtr omp, Boolean selected,
                            Uint2 itemID, Uint2 itemtype, Int2 index, FILE *fp)

{
  BioseqPtr      bsp;
  BioseqSetPtr   bssp;
  Char           buf [50];
  OMUserDataPtr  omudp;

  if (omdp == NULL || fp == NULL) return;
  if (selected) {
    fprintf (fp, "Data Element\n\n");
    fprintf (fp, "  EntityID %d selected\n", (int) omdp->EntityID);
    fprintf (fp, "  ItemID %d, Itemtype %d\n", (int) itemID, (int) itemtype);
  } else if (omdp->parentptr == NULL) {
    fprintf (fp, "Top Data Element %d\n\n", (int) index);
    fprintf (fp, "  EntityID %d\n", (int) omdp->EntityID);
  } else {
    fprintf (fp, "Inner Data Element %d\n\n", (int) index);
    fprintf (fp, "  EntityID %d\n", (int) omdp->EntityID);
  }
  if (omdp->datatype < OBJ_MAX) {
    fprintf (fp, "  Datatype %s", objmgrtypestrs [omdp->datatype]);
    if (omdp->datatype == OBJ_BIOSEQ) {
      bsp = (BioseqPtr) omdp->dataptr;
      if (bsp != NULL) {
        SeqIdWrite (bsp->id, buf, PRINTID_FASTA_LONG, sizeof (buf) - 1);
        fprintf (fp, " %s, length %ld", buf, (long) bsp->length);
      }
    } else if (omdp->datatype == OBJ_BIOSEQSET) {
      bssp = (BioseqSetPtr) omdp->dataptr;
      if (bssp != NULL) {
        fprintf (fp, " class %d", (int) bssp->_class);
      }
    }
    fprintf (fp, "\n");
  } else {
    fprintf (fp, "  Unregistered datatype %d\n", (int) omdp->datatype);
  }
  fprintf (fp, "  Lockcnt %d\n", (int) omdp->lockcnt);
  if (omdp->tempload < 3) {
    fprintf (fp, "  Tempload %s\n", temploadstrs [omdp->tempload]);
  } else {
    fprintf (fp, "  Unrecognized tempload %d\n", (int) omdp->tempload);
  }
  PrintABool (fp, "  Clipboard", omdp->clipboard);
  PrintABool (fp, "  Dirty", omdp->dirty);
  PrintABool (fp, "  Being_freed", omdp->being_freed);
  PrintABool (fp, "  Free", omdp->free);
  fprintf (fp, "\n");
  for (omudp = omdp->userdata; omudp != NULL; omudp = omudp->next) {
    if (omudp->proctype <= OMPROC_MAX) {
      fprintf (fp, "    Proctype %s\n", proctypestrs [omudp->proctype]);
    } else {
      fprintf (fp, "    Unrecognized proctype %d\n", (int) omudp->proctype);
    }
    fprintf (fp, "    Procid %d\n", (int) omudp->procid);
    fprintf (fp, "    Userkey %d\n", (int) omudp->userkey);
    fprintf (fp, "\n");
  }
}

NLM_EXTERN void LIBCALL ObjMgrReportFunc (CharPtr filename)

{
  FILE           *fp;
  Int2           j;
  Int2           num;
  ObjMgrPtr      omp;
  ObjMgrDataPtr  omdp;
  ObjMgrDataPtr  PNTR omdpp;

  omp = ObjMgrGet ();
  if (omp == NULL) return;
  fp = FileOpen (filename, "w");
  fprintf (fp, "Object Manager\n\n");
  fprintf (fp, "  HighestEntityID %d\n", (int) omp->HighestEntityID);
  fprintf (fp, "  Totobj %d\n", (int) omp->totobj);
  fprintf (fp, "  Currobj %d\n", (int) omp->currobj);
  fprintf (fp, "  Maxtemp %d\n", (int) omp->maxtemp);
  fprintf (fp, "  Tempcnt %d\n", (int) omp->tempcnt);
  fprintf (fp, "  Hold %d\n", (int) omp->hold);
  PrintABool (fp, "  Reaping", omp->reaping);
  PrintABool (fp, "  Is_write_locked", omp->is_write_locked);
  fprintf (fp, "\n");
  num = omp->currobj;
  for (j = 0, omdpp = omp->datalist; j < num && omdpp != NULL; j++, omdpp++) {
    omdp = *omdpp;
    if (omdp->parentptr == NULL) {
      ReportOnEntity (omdp, omp, FALSE, 0, 0, j + 1, fp);
    }
  }
  for (j = 0, omdpp = omp->datalist; j < num && omdpp != NULL; j++, omdpp++) {
    omdp = *omdpp;
    if (omdp->parentptr != NULL) {
      ReportOnEntity (omdp, omp, FALSE, 0, 0, j + 1, fp);
    }
  }
  FileClose (fp);
}


NLM_EXTERN void LIBCALL
ObjMgrAddIndexOnEntityID(ObjMgrPtr omp,Uint2 entityID,ObjMgrDataPtr omdp)
{
	Uint1   h,l;

	h=entityID >> 8;
	l=entityID & 0xff;
	if(omp==NULL) omp=ObjMgrGet();
	if(omp){
		if(!omp->entityID_index){
			omp->entityID_index=MemNew(256*sizeof(*omp->entityID_index));
		}
		if(!omp->entityID_index[h]){
			omp->entityID_index[h]=MemNew(256*sizeof(**omp->entityID_index));
		}
		omp->entityID_index[h][l]=omdp;
	}
}


NLM_EXTERN void LIBCALL
ObjMgrDeleteIndexOnEntityID(ObjMgrPtr omp,Uint2 entityID)
{
	Uint1   h,l;

        h=entityID >> 8;
        l=entityID & 0xff;
	if(omp==NULL) omp=ObjMgrGet();
	if(omp && omp->entityID_index && omp->entityID_index[h]){
		omp->entityID_index[h][l]=NULL;
	}

}


NLM_EXTERN ObjMgrDataPtr LIBCALL
ObjMgrLookupIndexOnEntityID(ObjMgrPtr omp,Uint2 entityID)
{
	Uint1   h,l;

        h=entityID >> 8;
        l=entityID & 0xff;
	if(omp==NULL) omp=ObjMgrGet();
	if(omp && omp->entityID_index && omp->entityID_index[h]){
		return omp->entityID_index[h][l];
	} else {
		return NULL;
	}
}