File: maputil.c

package info (click to toggle)
ncbi-tools6 6.1.20170106%2Bdfsg1-0%2Bdeb10u2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 468,492 kB
  • sloc: ansic: 1,474,204; pascal: 6,740; cpp: 6,248; xml: 3,390; sh: 2,137; perl: 1,084; csh: 508; makefile: 427; ruby: 93; lisp: 81
file content (2802 lines) | stat: -rw-r--r-- 59,862 bytes parent folder | download | duplicates (13)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
#include <maputil.h>
#include <objsub.h>

/**************************************************
*
*	free_enzyme_list(enp)
*	Free a list of EnzDataPtr
*
**************************************************/
NLM_EXTERN EnzPtr free_enzyme_list (EnzPtr enp)
{
	EnzDataPtr edp;
	EnzPtr next;
 
	while(enp != NULL)
	{
		next = enp->next;
		edp = enp->data.ptrvalue;
		MemFree(edp->name);
		MemFree(edp->pattern);
		MemFree(edp);
 
		MemFree(enp);
		enp = next;
	}
 
	return enp;
 
}

/****************************************************
*
*	make_enzyme_list(file_name)
*	build a ValNodeList of EnzDataPtr from teh 
*	input file
*
****************************************************/
NLM_EXTERN EnzPtr make_enzyme_list(CharPtr file_name)
{
  Char buff[100];
  Char name[100];
  Char pattern[100];
  long cut_pos;
  EnzPtr head = NULL, e_new;
  EnzDataPtr data;
  Uint1 order =0;
  FILE *ifp;

	if(file_name == NULL)
	   return NULL;
	if((ifp = FileOpen(file_name, "r")) == NULL){
	  Message(MSG_ERROR, "fail to open Enzyme file %s", file_name);
	  return NULL;
	}

	while(FileGets(buff, 99, ifp) != NULL){
	      sscanf(buff, "%s\t%s\t%ld\n", name, pattern, &cut_pos);
	      ++order;
	      data = (EnzDataPtr)MemNew(sizeof(EnzData));
	      data->name = StringSave(name);
	      data->pattern = StringSave(pattern);
	      data->cut_pos = 1;
	      /**data->cut_pos = cut_pos;**/

	      e_new = ValNodeNew(head);
	      e_new->choice = order;
	      e_new->data.ptrvalue = data;
	      if(head == NULL)
		 head = e_new;
	}/**end of while**/

	FileClose(ifp);
	return head;
}


/**********************************************************************
*
*	FreeEquivAlign(ealign_list)
*	Free a list of Seq-annot that is of type Seq-align
*	mostly, those are the externally loaded Seq-align for showing
*	the Equiv map
*
***********************************************************************/
NLM_EXTERN ValNodePtr FreeEquivAlign(ValNodePtr ealign_list)
{
	SeqAnnotPtr annot;
	ValNodePtr next;

	while(ealign_list)
	{
		if(ealign_list->choice == 1)
		{
			annot = (SeqAnnotPtr)(ealign_list->data.ptrvalue);
			SeqAnnotFree(annot);
		}
		next = ealign_list->next;
		MemFree(ealign_list);
		ealign_list = next;
	}

	return NULL;
}
		

/*******************************************************************
*
*	GetEquivAlignType(annot)
*	annot stores the alignments of markers mapped by more than 
*	one groups. if return 1, the markers are the consistent markers
*	if return 2, the markers are inconsistent markers
*	if return 0, the alignment simply records the mapping to 
*	the sequence map
*	if return -1, unknown status. Will be treated the same as 1
*
*******************************************************************/
NLM_EXTERN Int2 GetEquivAlignType(SeqAnnotPtr annot)
{
	ValNodePtr vnp;
	UserObjectPtr uop;
	UserFieldPtr ufp;
	ObjectIdPtr oip;

	if(annot == NULL)
		return -1;
	for(vnp = annot->desc; vnp != NULL; vnp = vnp->next)
	{
		if(vnp->choice == Annot_descr_user)
		{
			uop = vnp->data.ptrvalue;
			if(uop != NULL)
			{
				oip = uop->type;
				if(oip->str && StringCmp(oip->str, 
					"Equiv Alignment") == 0)
				{
					ufp = uop->data;
					if(ufp->choice == 2)
						return (Int2)(ufp->data.intvalue);
				}
			}
		}
	}
	return -1;
}


/***********************************************************************
*
*	FreeMuskSep(sep_list)
*	Free the manually loaded Seq-entries
*	sep_list: a list of MuskSepPtr
*
***********************************************************************/
NLM_EXTERN ValNodePtr FreeMuskSep(ValNodePtr sep_list)
{
	ValNodePtr next;
	MuskSepPtr msp;

	while(sep_list)
	{
		next = sep_list->next;
		msp = (MuskSepPtr)(sep_list->data.ptrvalue);
		switch(msp->datatype)
		{
			case OBJ_SEQENTRY:
				SeqEntryFree((SeqEntryPtr)(msp->dataptr));
				break;
			case OBJ_SEQSUB :
				SeqSubmitFree(msp->dataptr);
				break;
			case OBJ_BIOSEQ :
				BioseqFree((BioseqPtr)(msp->dataptr));
				break;
			case OBJ_BIOSEQSET:
				BioseqSetFree((BioseqSetPtr)(msp->dataptr));
				break;
			default:
				break;
		}

		MemFree(msp);
		MemFree(sep_list);
		sep_list = next;
	}
	return NULL;
}


/**********************************************************************
*
*	get_Bioseq_type(bsp)
*	return the type of Bioseq, such as the genetic or physical map
*	depending on its bsp->repr type and bsp->seq_ext type.
*
**********************************************************************/
NLM_EXTERN Uint1 get_Bioseq_type(BioseqPtr bsp)
{
	SeqFeatPtr sfp;
	SeqAnnotPtr annot;

	switch (bsp->repr)
	{
		case Seq_repr_map:
			sfp = bsp->seq_ext;
			if(sfp == NULL)
			{
				annot = bsp->annot;
				while(annot)
				{
					if(annot->type == 1)
						sfp = annot->data;
					if(sfp != NULL)
						break;
				}
			}
			if(sfp == NULL)
				return PHYSICAL_MAP; 
			if(sfp->data.choice == 1)
				return GENETIC_MAP;
			if(sfp->data.choice == 13)
				return RESTRICTION_MAP;
			if(sfp->data.choice == 14)
				return CYTO_MAP;
			return PHYSICAL_MAP;

		case Seq_repr_virtual:
			return PHYSICAL_MAP;
		case Seq_repr_seg:
		case Seq_repr_ref:
		case Seq_repr_delta:
			return SEG_SEQ;
		default:
			return RAW_SEQ;
	}
}


/********************************************************************
*
*	MapLayoutFree(head)
*	Free the list of MapPosPtr
*
********************************************************************/
NLM_EXTERN MapLayoutPtr MapLayoutFree(MapLayoutPtr head)
{
	ValNodeFreeData(head);
	return NULL;
}


/***************************************************************************
*
*       getBioseqNumbering(bsp)
*       get the numbering object from Seq_descr. If no numbering, return NULL
*
****************************************************************************/
NLM_EXTERN NumberingPtr getBioseqNumbering (BioseqPtr bsp)
{
	NumberingPtr np = NULL;
	ValNodePtr anp;

                anp = BioseqGetSeqDescr(bsp, Seq_descr_num, NULL);
                if(anp != NULL)
                        np = (NumberingPtr)anp->data.ptrvalue;
		if(np != NULL)
		{
			if(np->choice != Numbering_real)
				return NULL;
			if(np->data.ptrvalue == NULL)
				return NULL;
		}
			

		return np;
}

/**********************************************************************
*
*   IS_NUM_GENE(gene_label): kludge function
*	determine if the gene_label is used as a map unit, such 
*	as the case for C.elegans physical map
*
**********************************************************************/
NLM_EXTERN Boolean IS_NUM_GENE(CharPtr gene_label)	
{
	return (gene_label[0]=='0' || atol(gene_label) != 0 );
}

/***********************************************************************
*
*       map_unit_label(): create a label for the map unit
*
***********************************************************************/
NLM_EXTERN Boolean map_unit_label(Int4 pos, NumberingPtr np, CharPtr label, Boolean use_kb)
{
  DataVal num_val;
  FloatHi m_val;

                if(np == NULL)
                {
		  if(use_kb)
                  	pos = pos/1000;
		  if(use_kb && pos != 0)
                  	sprintf(label, "%ldK", (long) pos);
		  else
			sprintf(label, "%ld", (long) pos);
                  return FALSE;
                }
                else
                {
                   NumberingValue(np, pos, &num_val);  /**Add the last line**/
                   m_val = num_val.realvalue;
		   sprintf(label, "%2.2Lf", (long double) m_val);
                   return TRUE;
                }
}


NLM_EXTERN Boolean start_new_stack(Int4 pre_pos, Int4 pos, Int4 scale, Int2Ptr label_width, Int2 c_width)
{
	Int2 max_width;
	Int4 space;

	max_width = MAX(c_width, *label_width);
	if(pre_pos != -1 &&  (*label_width > 0))  /*not the first mark*/
	{
		space = (ABS(pre_pos - pos))/scale;
		if(space < (max_width/2 +2))
			return FALSE;
	}

	*label_width = c_width;
	return TRUE;
}

/*************************************************************************
*
*	is_label_match(obj_id, label)
*	return TRUE if obj_id->str matches with label
*
**************************************************************************/

NLM_EXTERN Boolean is_label_match(ObjectIdPtr obj_id, CharPtr label)
{
        if(obj_id !=NULL && obj_id->str !=NULL)
                return (StringCmp(obj_id->str, label) == 0);
        return FALSE;
}


/*************************************************************************
*
*       get_band_type, get_band_name(): kludge functions associated with
*       the cytogenetic map, i.e., the band pattern and the name of the
*       cytogenetic map
*
**************************************************************************/
static Uint1 get_uop_type(UserObjectPtr uop)
{
	ObjectIdPtr obj_id;

	obj_id = uop->type;
        if(is_label_match(obj_id, "BND"))
                return BND;
        if(is_label_match(obj_id, "HET"))
                return HET;
        if(is_label_match(obj_id, "TEL"))
                return TEL;
        if(is_label_match(obj_id, "CEN"))
                return CEN;
        return 0;
}

NLM_EXTERN Uint1 get_band_type(UserObjectPtr uop)
{
   	UserFieldPtr ufp;
	Uint1 type;

	type = get_uop_type(uop);
	if(type !=0)
		return type;

        while(uop)
        {
           if(uop->data)
           {
               ufp = uop->data;
               while(ufp)
               { 
                   if(is_label_match(ufp->label, "BandType"))
		   {
                       if(StringCmp(ufp->data.ptrvalue, "GiemsaPos") ==0)
                                return GIEMSA_POS;
                       if(StringCmp(ufp->data.ptrvalue, "GiemsaNeg") ==0)
                                return GIEMSA_NEG;
                       if(StringCmp(ufp->data.ptrvalue, "Acrocentric") ==0)
                                return ACRO_CENTRIC;
                       if(StringCmp(ufp->data.ptrvalue, "Point") ==0)
                                return BAND_POINT;
                       if(StringCmp(ufp->data.ptrvalue, "VariableReg") ==0)
                                return VARIABLE_REG;
                       return 0;
                   }
                   ufp = ufp->next;
                }   
             }
 
             uop = uop->next;
        }
        return 0;
}



/*********************************************************************
*
*	get_band_name(uop)
*	parse the band name from a cytogenetic map
*
*********************************************************************/
NLM_EXTERN CharPtr get_band_name(UserObjectPtr uop)
{
	UserFieldPtr ufp;

        while(uop)
        {
		for(ufp = uop->data; ufp!=NULL; ufp=ufp->next)
		{
			if(is_label_match(ufp->label, "BandName"))
				return (CharPtr)(ufp->data.ptrvalue);
		}
		uop = uop->next;
	}
	return NULL;
}


/************************************************************************
*
*	is_map_segment(slp) 
*	return TRUE if slp is a Seq-loc from a amp
*	return FALSE if it is not a map or the Bioseq is not loaded to 
*	the memory yet
*
************************************************************************/
NLM_EXTERN Boolean is_map_segment(SeqLocPtr slp)
{
	BioseqPtr bsp=NULL;
	SeqLocPtr loc;
	SeqIdPtr sip;
	ObjectIdPtr oip;

	if(slp->choice == SEQLOC_NULL || slp->choice == SEQLOC_EMPTY)
		return TRUE;
	sip = SeqLocId(slp);
	if(sip == NULL)
		return TRUE;
	if(sip->choice == SEQID_LOCAL)
	{
		oip = sip->data.ptrvalue;
		if(oip && oip->str)
		{
			if(StringNCmp(oip->str, "virtual", 7) == 0)
				return TRUE;
			if(StringNCmp(oip->str, "virtural", 7) == 0)
				return TRUE;
		}
	}
	bsp = BioseqFindCore(sip);
	if(bsp !=NULL)
	{
		if(bsp->repr == Seq_repr_map)
			return TRUE;
		if(bsp->repr == Seq_repr_virtual)
			return TRUE;
		if(bsp->repr == Seq_repr_seg)
		{
			loc = bsp->seq_ext;
			return is_map_segment(loc);
		}
				
	}

	return FALSE;
}

/***************************************************************
*
*	figure_map_seqid(ext_loc)
*	a very unreliable way to figure out the if there is a 
*	Seq-id for the map. It is dependent on the frequency of 
*	the Seq-id in a  segmented sequence
*
****************************************************************/
typedef struct mapseqid_count{
	SeqIdPtr sip;
	Int4 count;
}MapSeqIdCount, PNTR MapSeqIdCountPtr;
#define COUNT_NUM 20

NLM_EXTERN SeqIdPtr figure_map_seqid(SeqLocPtr ext_loc)
{
	MapSeqIdCount id_count[COUNT_NUM];
	Int4 i, j, maxcount, total, c_total;
	Int4 n_maxcount;
	SeqIdPtr sip;
	BioseqPtr bsp;

	MemSet((Pointer)id_count, 0, (size_t)COUNT_NUM * sizeof(MapSeqIdCount));
	i =0; j= 0;
	while(ext_loc)
	{
		++i;
		sip = SeqLocId(ext_loc);
		for(j =0; j<COUNT_NUM; ++j)
		{
			if(id_count[j].sip == NULL)
			{
				id_count[j].sip = sip;
				id_count[j].count = 1;
				break;
			}
			else
			{
				if(SeqIdMatch(id_count[j].sip, sip))
				{
					++(id_count[j].count);
					break;
				}
			}
		}
		ext_loc = ext_loc->next;
	}
	total = i;

	/* if(total < COUNT_NUM)
		return NULL; */
	c_total = MIN(total, COUNT_NUM);
	maxcount = 0;
	n_maxcount = 0;
	j = 0;
	for(i = 0; i<c_total; ++i)
	{
		if(id_count[i].count > maxcount)
		{
			j = i;
			n_maxcount = maxcount;
			maxcount = id_count[i].count;
		}
	}
	sip = id_count[j].sip;
	if(sip == NULL)
		return NULL;
	if(sip->choice != SEQID_LOCAL && sip->choice != SEQID_GENERAL)
		return NULL;
	bsp = BioseqFind(sip);
	if(bsp != NULL)
	{
		if(bsp->repr == Seq_repr_raw || bsp->repr == Seq_repr_const)
			return NULL;
		if(bsp->repr == Seq_repr_map || bsp->repr == Seq_repr_virtual)
			return sip;
	}

	
	if((FloatHi)maxcount/(FloatHi)total > 0.3) 
		return (id_count[j].sip); 
	if(maxcount>n_maxcount) 
	{
		if(sip->choice == SEQID_LOCAL || sip->choice == SEQID_GENERAL)
			return sip;
		else
			return NULL;
	}
		
	return NULL;
}


NLM_EXTERN Uint1 ck_cyto_type(SeqFeatPtr sfp)
{
	UserObjectPtr uop;
	Uint1 band;

	if(sfp->data.choice == 14)
	{
		uop = sfp->data.value.ptrvalue;
		band = get_band_type(uop);
		if(band >= BND && band <= CEN)
			return FLY_CYTO;
		if(band >= BAND_POINT && band <= VARIABLE_REG)
			return HUMAN_CYTO;
	}

	return 0;
}
		
	

/********************************************************************
*
*	SortAlignPosition(app, dim)
*	Sort out the order of a multiple alignment in the vertical 
*	display mode. It is sorted to the descending order of 
*	app->top. one app correspond to one aligned segment. It can 
*	be of multiple dimensions
*	app: alignment position
*	dim: dimention of alignment
*
*********************************************************************/
NLM_EXTERN void SortAlignPosition(AlignPosPtr app, Int2 dim)
{
	Int4 tmp_left, tmp_right, tmp_top, tmp_bottom;
	Boolean s_witch = TRUE;
	Int2 i, j;

	for(i =0; i<dim-1 && s_witch; ++i)	/*sort the order*/
	{
		s_witch = FALSE;
		for(j = 0; j<dim-i-1; ++j)
		{
			if(app->top[j] > app->top[j+1])
			{
				s_witch = TRUE;
				tmp_left = app->left[j];
				tmp_right = app->right[j];
				tmp_top = app->top[j];
				tmp_bottom = app->bottom[j];

				app->left[j] = app->left[j+1];
				app->right[j] = app->right[j+1];
				app->top[j] = app->top[j+1];
				app->bottom[j] = app->bottom[j+1];
			
				app->left[j+1] = tmp_left;
				app->right[j+1] = tmp_right;
				app->top[j+1] = tmp_top;
				app->bottom[j+1] = tmp_bottom;
			}
		}
	}
}

NLM_EXTERN ValNodePtr free_slp_list(ValNodePtr slp_list)
{
	ValNodePtr next;
	SeqLocPtr slp;
	
	while(slp_list)
	{
		next = slp_list->next;
		slp = (SeqLocPtr)(slp_list->data.ptrvalue);
		if(slp != NULL)
			SeqLocSetFree(slp);
		slp_list->next = NULL;
		MemFree(slp_list);
		slp_list = next;
	}
	
	return NULL;
}

static void load_one_label(CharPtr label, ValNodePtr PNTR list, ValNodePtr PNTR prev)
{
	ValNodePtr n_vnp;

	if(label != NULL && label[0] != '\0')
	{
		n_vnp = ValNodeNew(NULL);
		n_vnp->data.ptrvalue = StringSave(label);
		if(*prev == NULL)
			*list = n_vnp;
		else
			(*prev)->next = n_vnp;
		*prev = n_vnp;
	}
}


static void load_gene_list(SeqFeatPtr sfp, ValNodePtr PNTR list, ValNodePtr PNTR prev)
{
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	Char label[21];
	GeneRefPtr grp;
	ValNodePtr syn;
	CharPtr str;
	Uint2 subtype;
	Uint1 val;
	ValNodePtr vnp;
	DbtagPtr db_tag;
	ObjectIdPtr oip;
	
	
	omp = ObjMgrGet();
	omtp = ObjMgrTypeFind (omp, OBJ_SEQFEAT, NULL, NULL);
	if(omp == NULL || omtp->labelfunc == NULL)
		return;
	if(omtp->subtypefunc == NULL)
		return;
		

	while(sfp)
	{
		subtype =  (*(omtp->subtypefunc)) (sfp);
		if(subtype == FEATDEF_GENE || subtype == FEATDEF_tRNA || subtype == FEATDEF_rep_origin || subtype == FEATDEF_CDS)
		{
			if(subtype == FEATDEF_CDS)
				val = CDS_MARK;
			else
				val = GENE_MARK;
			(*(omtp->labelfunc)) (sfp, label, 20, OM_LABEL_CONTENT);
			if(label[0] != '\0')
				load_one_label(label, list, prev);
				
			/*add synonym for the Gene-ref*/
			if(sfp->data.choice == 1)
			{
				grp = sfp->data.value.ptrvalue;
				if(grp != NULL)
				{
					for(syn = grp->syn; syn != NULL; syn = syn->next)
					{
						str = syn->data.ptrvalue;
						if(str != NULL)
							load_one_label(str, list, prev);
					}
					for(vnp = grp->db; vnp != NULL; vnp = vnp->next)
					{
						db_tag = vnp->data.ptrvalue;
						if(db_tag->db == NULL || StringICmp(db_tag->db, "GenBank"))
						{
							oip = db_tag->tag;
							if(oip != NULL && oip->str)
								load_one_label(oip->str, list, prev);
						}
					}
				}
			}
		}
		sfp = sfp->next;
	}
	
}


NLM_EXTERN Int2 get_seg_num(SeqLocPtr slp)
{
	Int2 i =0;
	
	while(slp)
	{
		++i;
		slp = slp->next;
	}
	
	return i;
}

#define MAX_SEG_NUM	4	/*maximum segment number to search for features in  segments*/
typedef struct findgene {    /* used by FindGeneCallback */
	SeqEntryPtr top;         /* top seqentry for explore.. used to prevent recursion */
	ValNodePtr PNTR list;    /* the list of feature labels */
	ValNodePtr PNTR prev;
} FindGeneStruct, PNTR FindGeneStructPtr;
			
static void FindGeneCallback(SeqEntryPtr sep, Pointer data, Int4 index, Int2 indent)
{
	ValNodePtr PNTR list, PNTR prev;
	BioseqPtr bsp;
	BioseqSetPtr bssp;
	Int2 segnum;
	Boolean check_seg = FALSE;
	SeqEntryPtr s_sep;
	BioseqPtr s_bsp;
	SeqLocPtr slp;
	SeqIdPtr sip;
	SeqFeatPtr sfp;
	SeqAnnotPtr annot = NULL;
	FindGeneStructPtr fgsp;
	FindGeneStruct fgs;
	SeqEntryPtr last = NULL;

	fgsp = (FindGeneStructPtr)data;
	list = fgsp->list;
	prev = fgsp->prev;
	if(sep == NULL || fgsp == NULL || list == NULL || prev == NULL)
		return;

	if(sep->choice == 1)
	{
		bsp = (BioseqPtr)(sep->data.ptrvalue);
		if(bsp == NULL)
			return;
		if(bsp->repr == Seq_repr_seg)
		{
			segnum = get_seg_num((SeqLocPtr)(bsp->seq_ext));
			if(segnum <= MAX_SEG_NUM || !BioseqHasFeature(bsp))
			{
				check_seg = TRUE;
				for(slp = bsp->seq_ext; slp != NULL; slp = slp->next)
				{
					sip = SeqLocId(slp);
					if(sip != NULL)
					{
						s_bsp = BioseqLockById(sip);
						if(s_bsp != NULL)
						{
							s_sep = SeqEntryFind(s_bsp->id);
							if((s_sep != NULL) && (s_sep != fgsp->top) && (s_sep != last))
							{
								fgs.top = s_sep;
								fgs.list = list;
								fgs.prev = prev;
								last = s_sep;
								SeqEntryExplore(s_sep, (Pointer) (&fgs), FindGeneCallback);
							}
							BioseqUnlock(s_bsp);
						}
					}
				}
			}
		}
		if(bsp->repr == Seq_repr_map)
		{
			sfp = bsp->seq_ext;
			load_gene_list(sfp, list, prev);
		}
		if(check_seg == FALSE)
			annot = bsp->annot;
	}
		
	else
	{
		bssp = (BioseqSetPtr)(sep->data.ptrvalue);
		if(bssp == NULL)
			return;
		annot = bssp->annot;
	}
	
	while(annot)
	{
		if(annot->type == 1)
		{
			sfp = (SeqFeatPtr)(annot->data);
			load_gene_list(sfp, list, prev);
		}
		annot = annot->next;
	}

}


/*****************************************************************
*
*	Build a list of gene symbols to supply the Find Gene option in 
*   the global view
*
******************************************************************/
NLM_EXTERN ValNodePtr BuildGeneList(SeqEntryPtr sep)
{
	ValNodePtr list = NULL;
	ValNodePtr prev = NULL;
	FindGeneStruct fgs;
	
	if(sep == NULL)
		return FALSE;

	fgs.top = sep;
	fgs.list = &list;
	fgs.prev = &prev;
		
	SeqEntryExplore(sep, (Pointer) (&fgs), FindGeneCallback);
	
	return list;
	
}



typedef struct querydata {
	ValNodePtr query_list;
	GeneDataPtr gdp;
	SeqLocPtr target;
	
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	Char label[21];	
}QueryData, PNTR QueryDataPtr;

/***************************************************************
*
*	all the landmark genes need to be found ONLY ONCE. The user 
*	input data need to be found multiple times
*
****************************************************************/
static Boolean gene_is_loaded(GeneDataPtr gdp, CharPtr symbol)
{	
	if(symbol == NULL || gdp == NULL)
		return FALSE;
	
	while(gdp)
	{
		if(gdp->symbol)
			if(StringCmp(gdp->symbol, symbol) == 0)
				return TRUE;
		gdp = gdp->next;
	}
	
	return FALSE;
}

static SeqLocPtr dup_seq_loc(SeqLocPtr slp)
{
	Int4 start, stop;
	Uint1 strand;

	if(slp == NULL)
		return NULL;

	start = SeqLocStart(slp);
	stop = SeqLocStop(slp);
	strand = SeqLocStrand(slp);

	return SeqLocIntNew(start, stop, strand, SeqLocId(slp));
}

	

/***************************************************************** 
*
*       if sfp is a Gene-ref and contains the gene in g_list,   
*       return the string in g_list
*       else return NULL 
* 
*****************************************************************/ 
NLM_EXTERN Boolean check_landmark(SeqFeatPtr sfp, CharPtr mark)
{
	GeneRefPtr grp;
	ValNodePtr curr;
	DbtagPtr db_tag;
	ObjectIdPtr oip;

	if(sfp == NULL || sfp->data.choice != 1)
		return FALSE;
	grp = sfp->data.value.ptrvalue;
	if(grp != NULL)
	{
		if(grp->locus)
		{
			if(StringICmp(grp->locus, mark) == 0)
				return TRUE;
		}
		if(grp->syn)
		{
			if(check_syn(grp->syn, mark))
				return TRUE;
		}
		for(curr = grp->db; curr != NULL; curr = curr->next)
		{
			db_tag = curr->data.ptrvalue;
			if(db_tag)
			{
				oip = db_tag->tag;
				if(oip && oip->str)
				{
					if(StringICmp(oip->str, mark) == 0)
						return TRUE;
				}
			}
		}
	}

	return FALSE;
}
	
static Boolean gmarkfunc(GatherContextPtr gcp)
{
	QueryDataPtr qdp;
	
	GeneDataPtr gdp;
	GeneRefPtr grp;
	SeqFeatPtr sfp;
	ValNodePtr syn = NULL;
	Uint2 subtype;
	ValNodePtr curr;
	Boolean is_landmark;
	CharPtr match_str, str;
	Int4 start, stop;
	Uint1 strand;

	if(gcp == NULL)
		return FALSE;
	qdp = (QueryDataPtr)(gcp->userdata);
	if(qdp == NULL)
		return FALSE;
		
	if(gcp->thistype != OBJ_SEQFEAT && gcp->thistype != OBJ_BIOSEQ_MAPFEAT)
		return TRUE;
		
	sfp = (SeqFeatPtr)(gcp->thisitem);
	if(sfp == NULL)
		return TRUE;

	qdp->label[0] = '\0';		
	subtype =  (*(qdp->omtp->subtypefunc)) (sfp);
	if(subtype == FEATDEF_GENE || subtype == FEATDEF_tRNA || subtype == FEATDEF_rep_origin || subtype == FEATDEF_CDS)
	{
		if(subtype == FEATDEF_GENE)	/*load the synonom info*/
		{
			grp = sfp->data.value.ptrvalue;
			if(grp != NULL)
				syn = grp->syn;
		}
		
		(*(qdp->omtp->labelfunc)) (sfp, qdp->label, 20, OM_LABEL_CONTENT);
		for(curr = qdp->query_list; curr != NULL; curr = curr->next)
		{
			str = curr->data.ptrvalue;
			match_str = NULL;
			if(StringICmp(qdp->label, str) == 0)
				match_str = str;
			else if(check_landmark(sfp, str))
				match_str = str;
			if(match_str)
			{
				is_landmark = (curr->choice != 0);
				if(!is_landmark || !gene_is_loaded(qdp->gdp, match_str))
				{
					gdp = MemNew(sizeof (GeneData));
					gdp->landmark = is_landmark;
					gdp->symbol = StringSave(match_str);
					gdp->entityID = gcp->entityID;
					gdp->itemID = gcp->itemID;
					gdp->itemType = gcp->thistype;
					gdp->subtype = subtype;
					gdp->sfp = sfp;
					if(qdp->target == NULL)
						gdp->location = dup_seq_loc(sfp->location);
					else
					{
						start = gcp->extremes.left;
						stop = gcp->extremes.right;
						strand = gcp->extremes.strand;
						gdp->location = SeqLocIntNew(start, stop, strand, SeqLocId(qdp->target));
					}
					LinkGeneData(&(qdp->gdp), gdp);
				}
			}
		}
	}
	
	return TRUE;
	
}
		

/******************************************************************
*
*	load_gdata_marks(slp, gene_list, seglevels, sep, gdp)
*	Gather the current Seq-entry to create the corresponding list of 
*	GeneDataPtr for the list of gene symbols
*	slp: the target Seq-local. can be set to NULL
*	gene_list: a list of query symbols
*	seglevels: levels of gather
*	sep: the Seq-entry
*	gdp: the header of GeneDataPtr
*
********************************************************************/	
NLM_EXTERN Boolean load_gdata_marks(SeqLocPtr slp, ValNodePtr gene_list, Int2 seglevels, SeqEntryPtr sep, GeneDataPtr PNTR pgdp)
{
	GatherScope gs;
	QueryData qd;
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	
	if(gene_list == NULL || sep == NULL || pgdp == NULL)
		return FALSE;
		
	omp = ObjMgrGet();
	if(omp == NULL)
		return FALSE;
	omtp = ObjMgrTypeFind(omp, OBJ_SEQFEAT, NULL, NULL);
	if(omtp == NULL)
		return FALSE;
		
	qd.omp = omp;
	qd.omtp = omtp;
	qd.label[0] = '\0';
	qd.query_list = gene_list;
	qd.gdp = *pgdp;
	qd.target = slp;

	
	MemSet((Pointer)(&gs), 0, sizeof(GatherScope));
	MemSet((Pointer)(gs.ignore), (int)(TRUE), (size_t)OBJ_MAX * sizeof(Boolean));
	gs.ignore[OBJ_SEQFEAT] = FALSE;
	gs.ignore[OBJ_SEQANNOT] = FALSE;
	gs.ignore[OBJ_BIOSEQ_MAPFEAT] = FALSE;
	gs.nointervals = TRUE;
	gs.target = slp;
	if(slp != NULL)
		gs.get_feats_location = TRUE;
	gs.seglevels = seglevels;

	GatherSeqEntry(sep, (Pointer)(&qd), gmarkfunc, &gs);
	
	if(*pgdp == NULL)
		*pgdp = qd.gdp;
	return TRUE;
}

typedef struct bsp_order {
	SeqIdPtr sip;
	Int4 order;
	Boolean found;
}BspOrder, PNTR BspOrderPtr;

static void FindBspOrder(SeqEntryPtr sep, Pointer data, Int4 index, Int2 indent)
{
	BspOrderPtr bop;
	BioseqPtr bsp;

	if(sep->choice != 1)
		return;
	if(data == NULL)
		return;

	bop = (BspOrderPtr)data;
	if(bop->found)
		return ;

	bsp = sep->data.ptrvalue;
	++(bop->order);
	bop->found = BioseqMatch(bsp, bop->sip);

}


static Boolean get_current_priority(SeqIdPtr sip, SeqEntryPtr sep, Int4Ptr order)
{
	BspOrder bo;

	bo.sip = sip;
	bo.order = 0;
	bo.found = FALSE;


	if(sep != NULL && sip != NULL)
		BioseqExplore(sep, (Pointer)&bo, FindBspOrder);
	*order = bo.order;

	return bo.found;

}

NLM_EXTERN Int2 get_seglevels (BioseqPtr bsp)
{
	SeqLocPtr slp;
	

	if(bsp && bsp->repr == Seq_repr_seg)
	{
		if(!BioseqHasFeature(bsp))
			return 1;
		slp = (SeqLocPtr)(bsp->seq_ext);
		if(get_seg_num(slp) <= 4)	/*4 is the cut off for searching at the second level*/
			return 1;
	}
	
	return 0;
}

/*************************************************************************
*
*	return the best location of the gene from sep.
*	best is defined as the Bioseq with the highest searching prioirity
*	e_start, e_stop record the extremes of the all the presence of 
*	the gene
*
*************************************************************************/
NLM_EXTERN SeqLocPtr get_location_for_query(SeqEntryPtr sep, CharPtr gene, Int4Ptr e_start, Int4Ptr e_stop)
{
	ValNode vn;
	GeneDataPtr gdp = NULL, cgdp, best;
	Int2 seglevels;
	BioseqPtr bsp;
	SeqLocPtr slp;
	SeqLoc sl;
	Int4Ptr priority_list;
	Int4 num;
	Int4 left = -1, right = -1;
	Int4 order;

	if(sep == NULL || gene == NULL)
		return NULL;

	bsp = find_big_bioseq(sep);
	if(bsp == NULL)
		return NULL;
	seglevels = get_seglevels(bsp);

	vn.choice = 0;
	vn.data.ptrvalue = gene;
	vn.next = NULL;


	if(seglevels == 1)
	{
		sl.choice = SEQLOC_WHOLE;
		sl.data.ptrvalue = bsp->id;
		sl.next = NULL;
		slp = &sl;
	}
	else
		slp = NULL;

	if(!load_gdata_marks(slp, &vn, seglevels, sep, &gdp))
		return NULL;

	priority_list = get_priority_order(sep, &num);
	best = NULL;
	for(cgdp = gdp; cgdp != NULL; cgdp = cgdp->next)
	{
		cgdp->priority = 10000;
		if(cgdp->location != NULL)
		{
			if(left == -1)
				left = SeqLocStart(cgdp->location);
			else
				left = MIN(left, SeqLocStart(cgdp->location));
			if(right == -1)
				right = SeqLocStop(cgdp->location);
			else
				right = MAX(right, SeqLocStop(cgdp->location));
		}

		if(num > 0 && priority_list != NULL)
		{
			if(get_current_priority(SeqLocId(cgdp->location), sep, &order))
			{
				if(order >=0 && order <= num)
					cgdp->priority = (Uint2)(priority_list[order-1]);
			}
		}
		if(best == NULL)
			best = cgdp;
		else
		{
			if(cgdp->priority < best->priority)
				best = cgdp;
		}
	}

	if(best != NULL)
	{
		slp = best->location;
		best->location = NULL;
	}
	*e_start = left;
	*e_stop = right;
	GeneDataFree(gdp);
	return slp;
}	

				
	

typedef struct ra_store{
	ValNodePtr rrp_list;	/*a collected list for repeats*/
	ValNodePtr arp_list;	/*a collected list for alignment*/
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	Char annotDB[21];	/*for storing the Seq-annot info*/
	Boolean load_align;
	Uint1 displayOrder;
}RAStore, PNTR RAStorePtr;

static void add_repeats_to_list(RepeatRegionPtr r_new, ValNodePtr PNTR list)
{
	Uint1 max_order = 0;
	ValNodePtr curr, prev = NULL;
	RepeatRegionPtr rrp;
	Boolean found = FALSE;
	ValNodePtr vnp;
	
	
	if(*list == NULL)
		ValNodeAddPointer(list, 1, r_new);
	else
	{
		curr = *list;
		while(curr)
		{
			rrp = curr->data.ptrvalue;
			if(rrp->rep_name[0] == '\0' && r_new->rep_name[0] == '\0')
				found = TRUE;
			if(StringICmp(rrp->rep_name, r_new->rep_name) == 0)
				found = TRUE;
			if(found)
			{
				vnp = ValNodeNew(NULL);
				vnp->choice = curr->choice;
				vnp->data.ptrvalue = r_new;
				vnp->next = curr->next;
				curr->next = vnp;
				return;
			}
			else
			{
				max_order = MAX(max_order, curr->choice);
				prev = curr;
			}
			curr = curr->next;
		}
		vnp = ValNodeNew(prev);
		vnp->choice = max_order + 1;
		vnp->data.ptrvalue = r_new;
	}
}

/*trying to parse the descriptor in Seq-annot for the alignment display*/
NLM_EXTERN Uint1 get_align_annot_qual(SeqAnnotPtr annot, CharPtr annotDB, Int4 buf_size, Uint1Ptr annot_type)
{
	UserObjectPtr uop;
	ValNodePtr desc;
	ObjectIdPtr oip;
	UserFieldPtr ufp;
	Boolean match;

	if(annot == NULL || annot->type !=2)
		return 0;
	desc = annot->desc;
	match = FALSE;
	*annot_type = 0;
	while(desc)
	{
		if(desc->choice == Annot_descr_user)
		{
			uop = desc->data.ptrvalue;
			while(uop)
			{
				if(uop->type)
				{
					oip = uop->type;
					if(StringCmp(oip->str, "Align Consist?") == 0)
					{
						*annot_type = ANNOT_CONSIST;
						match = TRUE;
					}
					else if(StringCmp(oip->str, "Blast Type") == 0)
					{
						match = TRUE;
						*annot_type = ANNOT_BLAST;
					}
					else if(StringCmp(oip->str, "FISH Align") == 0)
						*annot_type = ANNOT_FISH;
					if(match)
					{
						ufp = uop->data;
						if(ufp && ufp->choice == 2)
						{
							oip = ufp->label;
							if(oip->str && annotDB != NULL)
							{
								StringNCpy_0(annotDB, oip->str, buf_size);
							}
							return (Uint1)(ufp->data.intvalue);
						}
					}	
				}	
				uop = uop->next;
			}
		}
		desc = desc->next;
	}


	desc = annot->desc;
	while(desc)
	{
		if(desc->choice == Annot_descr_user)
		{
			uop = desc->data.ptrvalue;
			while(uop)
			{
				if(uop->type)
				{
					oip = uop->type;
					if(StringCmp(oip->str, "Hist Seqalign") == 0)
					{
						ufp = uop->data;
						if(ufp->choice == 4 && ufp->data.boolvalue)
						{
							oip = ufp->label;
							if(oip && oip->str && annotDB)
							{
								StringNCpy_0(annotDB, oip->str, buf_size);
								return 0;
							}
						}
					}
				}
				uop = uop->next;
			}
		}
		desc = desc->next;
	}
	return 0;
}


static void load_new_interval(ValNodePtr PNTR intervals, Int4 left, Int4 right)
{
	GatherRangePtr grp, t_grp;
	ValNodePtr curr, prev, next, vnp;
	Int4 p_right;

	prev = NULL;
	/*overlaps the existing segment*/
	curr = *intervals;
	while(curr)
	{
		grp = curr->data.ptrvalue;
		if(!(left > (grp->right+1) || right < (grp->left -1)))
		{
			grp->left = MIN(left, grp->left);
			grp->right = MAX(right, grp->right);
			vnp = curr;
			/*check for the following segment*/
			curr = curr->next;
			while(curr)
			{
				next = curr->next;
				t_grp = curr->data.ptrvalue;
				if(t_grp->left <= grp->right +1)
				{
					grp->right = t_grp->right;
					vnp->next = next;
					curr->next = NULL;
					ValNodeFreeData(curr);
					curr = next;
				}
				else
					break;
			}
			return;
		}
		curr = curr->next;
	}
	
	/*No overlap*/
	grp = MemNew(sizeof(GatherRange));
	grp->left = left;
	grp->right = right;
	vnp = ValNodeNew(NULL);
	vnp->choice =  1;
	vnp->data.ptrvalue = grp;
	if(*intervals == NULL)
	{
		*intervals = vnp;
		return;
	}

	curr = *intervals;
	p_right = -1;
	prev = NULL;
	while(curr)
	{
		grp = curr->data.ptrvalue;
		if(p_right == -1)	/*it is the first segment*/
		{
			if(right < grp->left)
			{
				*intervals = vnp;
				vnp->next = curr;
				return;
			}
		}
		else if(left >= p_right+1 && right <= grp->left -1)
		{
			prev->next = vnp;
			vnp->next = curr;
			return;
		}

		p_right = grp->right;
		prev = curr;
		curr = curr->next;
	}

	prev->next = vnp;
}
		
static Boolean add_alignment_to_list(AlignRegionPtr a_new, ValNodePtr PNTR list)
{
	ValNodePtr curr;
	AlignRegionPtr arp;
	ValNodePtr vnp, prev;
	
	
	curr = *list;
	prev = NULL;
	while(curr)
	{
		arp = curr->data.ptrvalue;
		if(arp->displayOrder == a_new->displayOrder && 
			StringCmp(arp->seq_name, a_new->seq_name) == 0)
		{
			curr->choice += 1;
			arp->gr.left = MIN(arp->gr.left, a_new->gr.left);
			arp->gr.right = MAX(arp->gr.right, a_new->gr.right);
			load_new_interval(&(arp->intervals), a_new->gr.left, a_new->gr.right);
			if(a_new->score > arp->score)
			{
				arp->score = a_new->score;
				arp->p_val = a_new->p_val;
				arp->e_val = a_new->e_val;
			}
			MemFree(a_new);
			return FALSE;
		}
		prev = curr;
		curr = curr->next;
	}
	
	vnp = ValNodeNew(prev);
	vnp->choice = 1;
	vnp->data.ptrvalue = a_new;
	if(prev == NULL)
		*list = vnp;
	load_new_interval(&(a_new->intervals), a_new->gr.left, a_new->gr.right);
	return TRUE;
}
		
			
/*determine the status as absolute values*/
static Uint1 get_alignment_status(FloatHi score)
{
	if(score < 40.0)
		return 0;
	if(score <50.0)
		return 1;
	if(score < 80.0)
		return 2;
	if(score < 200)
		return 3;
	return 4;
}

static int LIBCALLBACK ArpNodeCompProc (VoidPtr ptr1, VoidPtr ptr2)
{
	AlignRegionPtr arp1, arp2;
	ValNodePtr   vnp1;
	ValNodePtr   vnp2;
	GatherRange   gr1, gr2;

	if (ptr1 != NULL && ptr2 != NULL)
	{
		vnp1 = *((ValNodePtr PNTR) ptr1);
		vnp2 = *((ValNodePtr PNTR) ptr2);
		if (vnp1 != NULL && vnp2 != NULL)
		{
			arp1 = (AlignRegionPtr) vnp1->data.ptrvalue;
			arp2 = (AlignRegionPtr) vnp2->data.ptrvalue;
			if (arp1 != NULL && arp2 != NULL)
			{
				if(arp2->score > arp1->score)
					return 1;
				if(arp1->score > arp2->score)
					return -1;
				
				gr1 = arp1->gr;
				gr2 = arp2->gr;
				if (gr1.left > gr2.left)
					 return 1;
				else if (gr1.left < gr2.left)
					return -1;
				else if (gr1.right < gr2.right)
					return 1;
				else if (gr1.right > gr2.right)
					return -1;
				return 0;
			}
		}
	}
	return 0;
}

static ValNodePtr sort_arp_list(ValNodePtr arp_list)
{
	return SortValNode(arp_list, ArpNodeCompProc);
}

static Boolean racollfunc (GatherContextPtr gcp)
{
	RAStorePtr rasp;
	Uint2 subtype;
	RepeatRegionPtr rrp;
	AlignRegionPtr arp;
	AlignDataPtr adp;
	SeqAnnotPtr annot;
	Uint1 annot_type;
	Int4 score, number;
	
	
	rasp = (RAStorePtr)(gcp->userdata);
	if(rasp == NULL)
		return FALSE;
		
	switch(gcp->thistype)
	{
		case OBJ_SEQANNOT:
			annot = (SeqAnnotPtr)(gcp->thisitem);
			if(annot->type == 2)	/*it is a Seq-annot for alignment*/
			{
				rasp->load_align = is_annot_for_hist_alignment(annot);
				if(rasp->load_align)
				{
					rasp->annotDB[0] = '\0';
					get_align_annot_qual(annot, rasp->annotDB, 20, &annot_type); 
					++(rasp->displayOrder);
				}
			}
			return TRUE;

		case OBJ_SEQFEAT:
			if(rasp->omtp == NULL)
				return TRUE;
			if (rasp->omtp->subtypefunc != NULL)
			{
				subtype = (*(rasp->omtp->subtypefunc)) (gcp->thisitem);
				if(subtype == FEATDEF_repeat_region || subtype == FEATDEF_repeat_unit)
				{
					rrp = MemNew(sizeof(RepeatRegion));
					MemCopy(&(rrp->gr), &(gcp->extremes), sizeof(GatherRange));
					(*(rasp->omtp->labelfunc)) (gcp->thisitem, rrp->rep_name, 19, OM_LABEL_CONTENT);
					add_repeats_to_list(rrp, &(rasp->rrp_list));
				}
			}
			return TRUE;
			
		case OBJ_SEQALIGN:
		case OBJ_SEQHIST_ALIGN:
			if(gcp->thistype == OBJ_SEQALIGN)
			{
				if(gcp->parenttype == OBJ_SEQANNOT)
				{
					if(rasp->load_align == FALSE)
						return TRUE;
				}
			}

			for(adp = gcp->adp; adp != NULL; adp = adp->next)
			{
				arp = MemNew(sizeof(AlignRegion));
				arp->annotDB[0] = '\0';
				arp->displayOrder = 0;
				score = 0;
				arp->score = -1.0;
				GetScoreAndEvalue((SeqAlignPtr)gcp->thisitem, &score, &(arp->score), &(arp->e_val), &number);
				if(arp->score <=0 && score > 0)
				{
					arp->score = (FloatHi)score;
				}

				if(gcp->thistype == OBJ_SEQALIGN)
				{
					if(gcp->parenttype == OBJ_SEQANNOT)
					{
						arp->displayOrder = rasp->displayOrder;
						StringCpy(arp->annotDB, rasp->annotDB);
					}
				}
				MuskSeqIdWrite(adp->sip, arp->seq_name, 19, PRINTID_TEXTID_ACCESSION, FALSE, FALSE); 
				MemCopy(&(arp->gr), &(adp->extremes), sizeof(GatherRange));
				add_alignment_to_list(arp, &(rasp->arp_list));
			}

			return TRUE;
		default:
			return TRUE;
	}
}

/* static Uint1 get_alignment_status(FloatHi score, FloatHi min_score, FloatHi max_score)
{
	FloatHi val;

	if(min_score == max_score)
		return 0;
	else
	{
		if(score == max_score)
			return 4;

		val = (score - min_score)/(max_score - min_score);
		return (Uint1)(val * 5.0);
	}
} */



/**************************************************************************
*
*	collect_repeats_and_align(slp, rrp_list, arp_list, seglevels, sep)
*
*	collect repeat features and alignment for global display
*	rrp_list: the list of the repeat features
*	arp_list: the list of the alignments
*
***************************************************************************/				
NLM_EXTERN Boolean collect_repeats_and_align(SeqLocPtr slp, ValNodePtr PNTR rrp_list, ValNodePtr PNTR arp_list, Int2 seglevels, SeqEntryPtr sep, Uint1Ptr align_has_status)
{
	GatherScope gs;
	RAStore ras;
	ObjMgrPtr omp;
	ObjMgrTypePtr omtp;
	AlignRegionPtr arp, n_arp;
	ValNodePtr prev, next, curr, p_last;
	
	*align_has_status = FALSE;
	if(slp == NULL || sep == NULL || (rrp_list == NULL && arp_list == NULL))
		return FALSE;
		
	omp = ObjMgrGet();
	if(omp == NULL)
		return FALSE;
	omtp = ObjMgrTypeFind(omp, OBJ_SEQFEAT, NULL, NULL);
	ras.omp = omp;
	ras.omtp = omtp;
	ras.rrp_list = NULL;
	ras.arp_list = NULL;
	ras.annotDB[0] = '\0';
	ras.displayOrder = 0;
	ras.load_align = TRUE;
		
	
	MemSet((Pointer)(&gs), 0, sizeof(GatherScope));
	MemSet((Pointer)(gs.ignore), (int)(TRUE), (size_t)OBJ_MAX * sizeof(Boolean));
	if(rrp_list != NULL)
		gs.ignore[OBJ_SEQFEAT] = FALSE;
	if(arp_list != NULL)
		gs.ignore[OBJ_SEQHIST_ALIGN] = FALSE;
	gs.ignore[OBJ_SEQHIST] = FALSE;
	gs.ignore[OBJ_SEQANNOT] = FALSE;
	gs.ignore[OBJ_SEQALIGN] = FALSE;

	gs.nointervals = TRUE;
	gs.target = slp;
	gs.get_feats_location = TRUE;
	gs.seglevels = seglevels;
	gs.mapinsert = TRUE;

	GatherSeqEntry(sep, (Pointer)(&ras), racollfunc, &gs);
	if(rrp_list != NULL)
		*rrp_list = ras.rrp_list;
	if(arp_list != NULL)
	{
		*arp_list = ras.arp_list;
		if(*arp_list != NULL)
		{
			/*sort arp_list in groups according to the displayOrder*/
			curr = *arp_list;
			p_last = NULL;
			while(curr)
			{
				arp = curr->data.ptrvalue;
				next = curr->next;
				prev = curr;
				while(next)
				{
					n_arp = next->data.ptrvalue;
					if(n_arp->displayOrder == arp->displayOrder)
					{
						prev = next;
						next = next->next;
					}
					else
						break;
				}
				prev->next = NULL;
				curr = sort_arp_list(curr);
				if(p_last == NULL)
					*arp_list = curr;
				else
					p_last->next = curr;

				while(curr->next != NULL)
					curr = curr->next;
				p_last = curr;
				curr = next;
			}


			for(curr = *arp_list; curr != NULL; curr = curr->next)
			{
				arp = curr->data.ptrvalue;
				arp->status = get_alignment_status(arp->score);
				if(arp->status > 0)
					*align_has_status = TRUE;
			}
		}
	}
	/* *max_displayOrder = ras.displayOrder; */
	return TRUE;
}




/*###################################################################
#
#	functions related to make_Bioseq_list
#
####################################################################*/

static void FindBspCallback(SeqEntryPtr sep, Pointer data, Int4 index, Int2 indent)
{
	ValNodePtr PNTR bsp_list;
	BioseqPtr bsp;
	Uint1 choice;

	if(sep->choice == 1)
	{
		bsp_list = (ValNodePtr PNTR)data;
		bsp = sep->data.ptrvalue;
		choice = 0;
		if(IsSeqIndexMap(bsp))
			choice = SEQINDEX_VAL;
		ValNodeAddPointer(bsp_list, choice, (Pointer)bsp);
	}
}

static Boolean is_EQUIV(SeqEntryPtr sep)
{
	BioseqSetPtr bssp;

	if(sep->choice == 2)
	{
		bssp = (BioseqSetPtr)(sep->data.ptrvalue);
			return (bssp->_class == 10);
	}
	return FALSE;
}

NLM_EXTERN Int4Ptr get_priority_order(SeqEntryPtr sep, Int4Ptr num)
{
	BioseqSetPtr bssp;
	SeqDescrPtr desc;
	UserObjectPtr uop;
	UserFieldPtr ufp;
	ObjectIdPtr oip;

	if(sep == NULL || sep->choice !=2)
		return NULL;
	bssp = sep->data.ptrvalue;
	if(bssp == NULL || bssp->_class != 10)
		return NULL;

	for(desc = bssp->descr; desc != NULL; desc = desc->next)
	{
		if(desc->choice == Seq_descr_user)
		{
			uop = desc->data.ptrvalue;
			oip = uop->type;
			if(oip != NULL && oip->str != NULL)
			{
				if(StringCmp(oip->str, "Equiv Search Priority") == 0)
				{
					ufp = uop->data;
					if(ufp->choice == 8)	
					{
						if(num != NULL)
							*num = ufp->num;
						return (Int4Ptr)(ufp->data.ptrvalue);
					}
				}
			}
		}
	}

	return NULL;
}
 

	
	


/*************************************************************
*
*	check the Seq-annot to see if it is designed to be displayed 
*	as a sequence history or not
*
**************************************************************/
NLM_EXTERN Boolean is_annot_for_hist_alignment(SeqAnnotPtr annot)
{
	UserObjectPtr uop;
	ValNodePtr desc;
	ObjectIdPtr oip;
	UserFieldPtr ufp;

	if(annot == NULL || annot->type !=2)
		return FALSE;
	desc = annot->desc;
	while(desc)
	{
		if(desc->choice == Annot_descr_user)
		{
			uop = desc->data.ptrvalue;
			while(uop)
			{
				if(uop->type)
				{
					oip = uop->type;
					if(StringCmp(oip->str, "Hist Seqalign") == 0)
					{
						ufp = uop->data;
						if(ufp && ufp->choice == 4)
							return (ufp->data.boolvalue);
					}	
				}	
				uop = uop->next;
			}
		}
		desc = desc->next;
	}

	return FALSE;
}


NLM_EXTERN ValNodePtr get_equiv_align(SeqEntryPtr sep)
{
	BioseqSetPtr bssp;
	SeqAnnotPtr annot;
	ValNodePtr ealign_list = NULL;
	SeqAlignPtr align;

	if(is_EQUIV(sep))
	{
		bssp = sep->data.ptrvalue;
		annot = bssp->annot;
		while(annot)
		{
			if(annot->type == 2)
			{
				align = annot->data;
				if(align && align->segtype == 3)
				{	/*has to be Std-seg */
				if(!is_annot_for_hist_alignment(annot))	/*protection for cases that might include the alignment shown as history*/
					ValNodeAddPointer(&ealign_list, 0, annot);
				}
			}
			annot = annot->next;
		}
	}

	return ealign_list;
}




NLM_EXTERN Boolean make_Bioseq_list(SeqEntryPtr sep, ValNodePtr PNTR bsp_list, ValNodePtr PNTR equiv_align)
{
	BioseqPtr bsp;
	ValNodePtr sep_align_list;
	ValNodePtr this_list;
	Int4Ptr priority_order;
	Int4 num, i;
	ValNodePtr curr;

	if(sep == NULL || bsp_list == NULL)
		return FALSE;
		
	if(is_EQUIV(sep))	/*is it an Equiv-seg of Bioseqs*/
	{
		priority_order = get_priority_order(sep, &num);
		this_list = NULL;
		SeqEntryExplore(sep, (Pointer) (&this_list), FindBspCallback);
		for(i= 0, curr = this_list; curr != NULL && i<num; curr = curr->next)
		{
			if(curr->choice != SEQINDEX_VAL)
			{	/*the sequence index map is excluded from 
				  search priority */
				if(priority_order != NULL)
					curr->choice = (Uint1)(priority_order[i++]);
				else
					curr->choice = SEQINDEX_VAL-1;
			}
		}
		ValNodeLink(bsp_list, this_list);

		if(equiv_align != NULL)
		{
			sep_align_list = get_equiv_align(sep);
			ValNodeLink(equiv_align, sep_align_list);
		}
	}
	else
	{
		bsp = find_big_bioseq(sep);
		if(bsp != NULL)
			ValNodeAddPointer(bsp_list, 1, (Pointer)bsp);
	}
	return TRUE;
}

#define MINDIST         100             /*for drawing the dynamic scaler*/

NLM_EXTERN Int4 calculate_ruler(Int4 scaleX)
{
  FloatHi logDist;
  FloatHi minDist;
  FloatHi nextPower;
  Int4 ruler;


	  minDist = (double) (MINDIST * scaleX);
	  logDist = log10 (minDist);
	  nextPower = (exp(ceil(logDist) * NCBIMATH_LN10));
	  if(minDist < nextPower /5.0)
	     ruler = (Int4)( (nextPower + 0.5)/5.0 );
	  else if (minDist <nextPower/4){
	     ruler = (Int4)( (nextPower + 0.5)/4.0 );
	   }
	   else if(minDist <nextPower/2){
	      ruler = (Int4)( (nextPower+0.5)/2.0 );
	   }
	   else {
	     ruler = (Int4) (nextPower+0.5);
	  }
	  return ruler;
}


NLM_EXTERN GeneDataPtr LinkGeneData(GeneDataPtr PNTR head, GeneDataPtr g_new)
{
	GeneDataPtr curr;

	if(*head == NULL)
		*head = g_new;
	else
	{
		curr = *head;
		while(curr->next != NULL)
			curr = curr->next;
		curr->next = g_new;
	}

	return (*head);
}


/****************************************************************
*
*	LoadLandMarkGene(sep)
*	get the landmark gene from the User-object in the descriptor
*	all the genes are linked to a ValNode and vnp->choice is set 
*	to 1 to indicate it is a landmark gene
*
******************************************************************/
NLM_EXTERN ValNodePtr LoadLandMarkGene(SeqEntryPtr sep)
{
	BioseqPtr bsp;
	BioseqSetPtr bssp;
	SeqDescrPtr descr = NULL;
	UserObjectPtr uop;
	UserFieldPtr ufp;
	CharPtr symbol;
	ValNodePtr list = NULL;

	if(sep == NULL)
		return NULL;

	if(sep->choice == 1)
	{
		bsp = sep->data.ptrvalue;
		descr = bsp->descr;
	}
	else
	{
		bssp = sep->data.ptrvalue;
		descr = bssp->descr;
	}

	while(descr)
	{
		if(descr->choice == Seq_descr_user)
		{
			uop = descr->data.ptrvalue;
			while(uop)
			{
				if(uop->type != NULL)
				{
					if(is_label_match(uop->type, "LandMark"))
					{
						ufp = uop->data;
						while(ufp)
						{
							if(ufp->choice == 1)
							{
								symbol = (CharPtr)(ufp->data.ptrvalue);
								if(symbol != NULL)
									ValNodeCopyStr(&list, 1, symbol);
									/*set choice =1 to indicate it is a landmark gene*/
							}
							ufp = ufp->next;
						}
					}
				}
				uop = uop->next;
			}
		}
		descr = descr->next;
	}
	return list;

}

NLM_EXTERN Boolean BioseqHasLandMark(BioseqPtr bsp)
{
	ValNodePtr descr;
	UserObjectPtr uop;

	if(bsp == NULL)
		return FALSE;

	for(descr = bsp->descr; descr != NULL; descr = descr->next)
	{
		if(descr->choice == Seq_descr_user)
		{
			uop = descr->data.ptrvalue;
			if(uop->type != NULL)
			{
				if(is_label_match(uop->type, "LandMark"))
					return TRUE;
			}
		}
	}

	return FALSE;
}


NLM_EXTERN GeneDataPtr GeneDataFree(GeneDataPtr head)
{
	GeneDataPtr next;

	while(head != NULL)
	{
		next = head->next;
		MemFree(head->symbol);
		SeqLocFree(head->location);
		ValNodeFree(head->align_seg);
		MemFree(head);
		head = next;
	}
	return head;
}


/***********************************************************************
*
*	for each sequence in alignment stored in Seq-hist, if the aligned 
*	sequence itself contains alignment, it is temporarily loaded as 
*	a user-object in the descriptor of the bioseq. This function extract 
*	the information from the descripor and store it as a list of gi's 
*	plus the kludge offset value
*
************************************************************************/
NLM_EXTERN ValNodePtr get_seqids_with_alignment(BioseqPtr mbsp)
{
	ValNodePtr descr;
	UserObjectPtr uop;
	UserFieldPtr ufp;
	ValNodePtr align_id_list = NULL;
	ObjectIdPtr oip;
	Int4 gi;
	
	if(mbsp == NULL)
		return NULL;
		
	for (descr = mbsp->descr; descr != NULL; descr = descr->next)
	{
		if(descr->choice == Seq_descr_user)
		{
			uop = descr->data.ptrvalue;
			if(uop->type != NULL)
			{
				if(is_label_match(uop->type, "History"))
				/*temporary criteria for storing the seq-id with alignment*/
 				{
 					ufp = uop->data;
 					while(ufp)
 					{
 						if(ufp->choice ==2)	/*it is an integer*/
 						{
 							gi = ufp->data.intvalue;
 							oip = ufp->label;
 							/*oip->id is the kludge offset factor*/
 							ValNodeAddInt(&align_id_list, (Uint1)(oip->id), gi);
 						}
 						ufp = ufp->next;
 					}
 				}
 			}
 		}
 	}
 	return align_id_list;
}


/***********************************************************************
*
*	map the kludge offet factor for Unigene, RICE, MOUSE ,FlyBase, etc
*
************************************************************************/
NLM_EXTERN Int4 get_kludge_factor(SeqIdPtr sip, Int4Ptr gi)
{
	DbtagPtr db_tag;
	ObjectIdPtr oip;

	*gi = -1;
	
	if(sip == NULL) 
		return 0;
	if(sip->choice == SEQID_GI)
		*gi = sip->data.intvalue;
	if(sip->choice != SEQID_GENERAL)
		return 0;
				
	db_tag = sip->data.ptrvalue;
	if(db_tag == NULL || db_tag->db == NULL)
		return 0L;
	oip = db_tag->tag;
	*gi = oip->id;
		
	if(StringCmp(db_tag->db, "UNIGENE") == 0)
		return 1L;
		
	if(StringICmp(db_tag->db, "FlyBase") == 0)
		return 2L;
		
	if(StringCmp(db_tag->db, "JACKSON") == 0)
		return 3L;

	 if(StringCmp(db_tag->db, "JRGP") == 0)
		return 4L;
		
	return 0L;
}

NLM_EXTERN GeneDataPtr make_gene_data(ValNodePtr gene_list)
{
	GeneDataPtr head, g_new;
	CharPtr str;

	head = NULL;
	while(gene_list)
	{
		str = gene_list->data.ptrvalue;
		g_new = MemNew(sizeof(GeneData));
		g_new->symbol = StringSave(str);
		g_new->priority = 0;
		g_new->landmark = (gene_list->choice != 0);
		LinkGeneData(&head, g_new);
		gene_list = gene_list->next;
	}

	return head;
}


NLM_EXTERN void RefreshGeneData(GeneDataPtr gdp)
{
	while(gdp)
	{
		gdp->priority = 0;
		gdp = gdp->next;
	}
}


/**************************************************************
*
*	get the alignment for the FISH map
*	for the Human Cytogenetic map, if there is a 
*	Seq-annot stored as Hist-align and the intervals are 
*	aligned to the FISH map, it will return the Seq-align
*	of the alignment to the FISH map
*
***************************************************************/
NLM_EXTERN SeqAlignPtr get_FISH_align (BioseqPtr bsp)
{
	SeqAnnotPtr annot;
	AnnotDescrPtr descr;
	Boolean is_hist, is_fish;
	UserObjectPtr uop;
	UserFieldPtr ufp;
	ObjectIdPtr oip;

	for(annot = bsp->annot; annot != NULL; annot = annot->next)
	{
		if(annot->type == 2)
		{
			descr = annot->desc;
			is_hist = FALSE;
			is_fish = FALSE;
			while(descr)
			{
				if(descr->choice == Annot_descr_user)
				{
					uop = descr->data.ptrvalue;
					oip = uop->type;
					if(oip && oip->str && 
						StringCmp(oip->str, "Hist Seqalign") == 0)
					{
						ufp = uop->data;
						while(ufp)
						{
							oip = ufp->label;
							if(StringCmp(oip->str, "Hist Seqalign") == 0)
							{
								if(ufp->choice == 4)
									is_hist = ufp->data.boolvalue;
							}
							if(StringCmp(oip->str, "FISH Align") == 0)
							{
								if(ufp->choice == 4)
									is_fish = ufp->data.boolvalue;
							}
							ufp = ufp->next;
						}
					}	
				}
				descr = descr->next;
			}
			if(is_hist && is_fish)
				return (SeqAlignPtr)(annot->data);
		}
	}

	return NULL;
}
		
	
/*******************************************************
*
*	annot_is_user_defined(annot)
*
*	determine if the Seq-annot contains the features 
*	that were defined by the user. This is to 
*	distinguish the local data from the public data 
*	set
*
********************************************************/
NLM_EXTERN Boolean annot_is_user_defined (SeqAnnotPtr annot)
{
	UserObjectPtr uop;
	ValNodePtr desc;

	if(annot == NULL || annot->desc == NULL)
		return FALSE;

	for(desc = annot->desc; desc != NULL; desc = desc->next)
	{
		if(desc->choice == Annot_descr_user)
		{
			uop = desc->data.ptrvalue;
			if(is_label_match(uop->type, "User Feature"))
				return TRUE;
		}
	}

	return FALSE;
}


/*
*
*	functions related to the map legend of a Bioseq
*
*/
NLM_EXTERN UserObjectPtr BioseqHasMapLegend (BioseqPtr bsp)
{
	ValNodePtr vnp;
	UserObjectPtr uop;
	ObjectIdPtr oip;


	if(bsp == NULL)
		return NULL;
	for (vnp = bsp->descr; vnp != NULL; vnp = vnp->next)
	{
		if(vnp->choice == Seq_descr_user)
		{
			uop = vnp->data.ptrvalue;
			if(uop && uop->type != NULL)
			{
				oip = uop->type;
				if(oip->str && StringCmp(oip->str, "MapLegend") == 0)
					return uop;
			}
		}
	}


	return NULL;
}
		
	 						
NLM_EXTERN Boolean SeqLocListHasLegend (ValNodePtr slp_list)
{
	SeqLocPtr slp;
	BioseqPtr bsp;

	while(slp_list)
	{
		slp = slp_list->data.ptrvalue;
		if(slp != NULL)
		{
			bsp = BioseqFind(SeqLocId(slp));
			if(bsp != NULL)
			{
				if(BioseqHasMapLegend(bsp) != NULL)
					return TRUE;
			}
		}
		slp_list = slp_list->next;
	}

	return FALSE;
}


/*
*
*	Is it a Sequence Index Map
*
*/
NLM_EXTERN Boolean IsSeqIndexMap (BioseqPtr bsp)
{
	ValNodePtr vnp;

	if(bsp == NULL)
		return FALSE;

	for(vnp = bsp->descr; vnp != NULL; vnp = vnp->next)
	{
		if(vnp->choice == Seq_descr_comment)
		{
			if(vnp->data.ptrvalue != NULL)
			{
				if(StringCmp(vnp->data.ptrvalue, 
					"Sequence Index Map") == 0)
					return TRUE;
			}
		}
	}


	return FALSE;
}


/*find a list of the seqlocs on the contig that maps to the 
*current chromosome. For now, only the Whitehead map and the 
*Eric Green's map is considered. return a list of Seq-locs that 
*contains contigs within the region
*/
NLM_EXTERN Uint1 FindContigDB (SeqIdPtr sip)
{
	DbtagPtr db_tag;

	while(sip)
	{
		if(sip->choice == SEQID_GENERAL)
		{
			db_tag = sip->data.ptrvalue;
			if(db_tag->db)
			{
				if(StringCmp(db_tag->db, "MIT") == 0)
					return YAC_MIT;
				if(StringCmp(db_tag->db, "NHGRI") == 0)
					return YAC_NHGRI;
			}
		}
		sip = sip->next;
	}
	return 0;
}



/*
################################################################
#
#	functions related to mapping the location of the chromosome 
#	to a location on the YAC Contig
#
################################################################
*/


/*the positions on the contig sequence is calculated by the ratio*/
static FloatHi calculate_percent_pos(Int4 pos, Int4 start, Int4 len)
{
	return (FloatHi)(pos  - start)/(FloatHi)len;
}

static Int4 map_position_by_ratio(Int4 m_pos, SeqLocPtr m_loc, Int4 s_len)
{
	FloatHi ratio;
	FloatHi val;

	ratio = calculate_percent_pos(m_pos, SeqLocStart(m_loc), SeqLocLen(m_loc));
	val = ratio * (FloatHi)s_len;
	return MIN((Int4)val, s_len-1);
}


typedef struct contig_map {
	Int4 offset;	/*offset of the contig to the chromosome coordinates*/
	SeqLocPtr slp;	/*location of the contig*/
}ContigMap, PNTR ContigMapPtr;

static int LIBCALLBACK OffsetCompProc (VoidPtr ptr1, VoidPtr ptr2)
{
  ContigMapPtr  cmp1, cmp2;
  ValNodePtr   vnp1;
  ValNodePtr   vnp2;

  if (ptr1 != NULL && ptr2 != NULL) {
    vnp1 = *((ValNodePtr PNTR) ptr1);
    vnp2 = *((ValNodePtr PNTR) ptr2);
    if (vnp1 != NULL && vnp2 != NULL) {
      cmp1 = (ContigMapPtr) vnp1->data.ptrvalue;
      cmp2 = (ContigMapPtr) vnp2->data.ptrvalue;
      if (cmp1 != NULL && cmp2 != NULL) {
		  if(cmp1->offset > cmp2->offset)
			  return 1;
		  else
		  {
			  if(cmp1->offset < cmp2->offset)
				  return -1;
			  else
				  return 0;
		  }
	  }
	}
  }
  return 0;
}


/*
*
*	chr_slp is the position on the genome/chromosome. align is the alignment
*	between the contig and the chromosome. It will try to map the chromosome 
*	coordinates to the contig coordinates. Since more than one contig may be 
*	identified, the result will be chained to a list. The list of the contigs 
*	are sorted by their position on the chromosome
*/
static ValNodePtr MapContigPosition (SeqLocPtr chr_slp, SeqAlignPtr align)
{
	StdSegPtr ssp;
	SeqLocPtr slp;
	SeqLocPtr m_loc, s_loc;
	SeqIdPtr chr_sip;
	Int4 offset;
	Int4 start, stop;
	Int4 chr_start, chr_stop;
	Int4 ctg_start, ctg_stop;
	ContigMapPtr cmp;
	ValNodePtr list, curr, contig_list;
	BioseqPtr bsp;

	chr_start = SeqLocStart(chr_slp);
	chr_stop = SeqLocStop(chr_slp);
	chr_sip = SeqLocId(chr_slp);
	list = NULL;
	while(align)
	{
		if(align->segtype == 3)
		{
			ssp = align->segs;
			while(ssp)
			{
				m_loc = NULL;
				s_loc = NULL;
				for(slp = ssp->loc; slp != NULL; slp = slp->next)
				{
					if(SeqIdMatch(SeqLocId(slp), chr_sip))
					{
						if(SeqLocCompare(slp, chr_slp) != SLC_NO_MATCH)
							m_loc = slp;
					}
					else
						s_loc = slp;
				}
				if(m_loc != NULL && s_loc != NULL)
				{
					if(SeqLocStart(m_loc) > chr_start)
						offset = SeqLocStart(m_loc) - chr_start;
					else
						offset = 0;
					start = MAX(SeqLocStart(m_loc), chr_start);
					stop = MIN(SeqLocStop(m_loc), chr_stop);

					/*assuming the contig is mapped to the chromosome from 
					  head-to-toe. Use the original Bioseq to get the location 
					  on the contig
					 */
					bsp = BioseqLockById(SeqLocId(s_loc));
					if(bsp != NULL)
					{
						ctg_start = map_position_by_ratio(start, m_loc, bsp->length);
						ctg_stop = map_position_by_ratio(stop, m_loc, bsp->length);
						slp = SeqLocIntNew(ctg_start, ctg_stop, Seq_strand_plus, SeqLocId(s_loc));
						
						cmp = MemNew(sizeof(ContigMap));
						cmp->offset = offset;
						cmp->slp = slp;
						ValNodeAddPointer(&list, 0, cmp);
						BioseqUnlock(bsp);
					}
				}
				ssp = ssp->next;
			}
		}
		align = align->next;
	}

	if(list == NULL)
		return NULL;
	list = SortValNode(list, OffsetCompProc);
	/*extract the Seq-loc from cmp, and free the structure*/
	contig_list = NULL;
	for(curr = list; curr != NULL; curr = curr->next)
	{
		cmp = curr->data.ptrvalue;
		if(cmp && cmp->slp != NULL)
			ValNodeAddPointer(&contig_list, 0, cmp->slp);
		MemFree(cmp);
	}
	ValNodeFree(list);
	return contig_list;
}




/*return a list of Seq-locs which are the contigs mapped to 
*	the current location on the genome
*
*/
NLM_EXTERN ValNodePtr FindContigList (SeqLocPtr chr_slp)
{
	BioseqPtr bsp;
	SeqAlignPtr align;
	ValNodePtr list = NULL;
	SeqAnnotPtr annot;
	Uint1 type, annot_type;
	Char annotDB[21];


	bsp = BioseqLockById(SeqLocId(chr_slp));
	if(bsp == NULL)
		return NULL;

	if(FindContigDB (bsp->id) == 0)
	{
		BioseqUnlock(bsp);
		return NULL;
	}
	if(bsp->hist && bsp->hist->assembly)
	{
		align = bsp->hist->assembly;
		list = MapContigPosition (chr_slp, align);
	}
	if(list == NULL)
	{
		for(annot = bsp->annot; annot != NULL; annot = annot->next)
		{
			if(annot->type == 2)
			{
				if(is_annot_for_hist_alignment(annot))
				{
					type = get_align_annot_qual(annot, annotDB, 20, &annot_type);
					if(annot_type == ANNOT_CONSIST && type == 1)
						/*for anchored contigs only*/
					{
						align = annot->data;
						list = MapContigPosition(chr_slp, align);
						if(list != NULL)
							break;
					}
				}
			}
		}
	}

	BioseqUnlock(bsp);
	return list;
}

NLM_EXTERN Boolean is_lod_score_annot(SeqAnnotPtr annot)
{
	SeqFeatPtr sfp;
	ValNodePtr desc;

	if(annot == NULL || annot->type != 1)
		return FALSE;

	sfp = annot->data;
	if(sfp == NULL || sfp->data.choice != 14)
		return FALSE;
	for(desc = annot->desc; desc != NULL; desc = desc->next)
	{
		if(desc->choice == Annot_descr_name)
		{
			if(StringCmp(desc->data.ptrvalue, "LOD Score") == 0)
				return TRUE;
		}
	}

	return FALSE;
}

NLM_EXTERN CharPtr GetAnnotTitle(SeqAnnotPtr annot)
{
	ValNodePtr desc;

	if(annot == NULL)
		return NULL;

	for(desc = annot->desc; desc != NULL; desc = desc->next)
	{
		if(desc->choice == Annot_descr_title)
		{
			if(desc->data.ptrvalue != NULL)
				return (desc->data.ptrvalue);
		}
	}

	return NULL;
}


NLM_EXTERN Int2 GetLODScoreNumber (BioseqPtr bsp)
{
	Int2 num = 0;
	SeqAnnotPtr annot;

	if(bsp == NULL || bsp->annot == NULL)
		return 0;
	for(annot = bsp->annot; annot != NULL; annot = annot->next)
	{
		if(is_lod_score_annot(annot))
			++num;
	}

	return num;
}

NLM_EXTERN Uint1 GetLODScoreBitValue (SeqFeatPtr sfp)
{
	UserObjectPtr uop;
	ObjectIdPtr oip;
	UserFieldPtr ufp;

	if(sfp == NULL || sfp->data.choice != 14)
		return 0;

	uop = sfp->data.value.ptrvalue;
	if(uop != NULL)
	{
		oip = uop->type;
		if(oip && oip->str && StringCmp(oip->str, "LOD Score Value") == 0)
		{
			ufp = uop->data;
			while(ufp)
			{
				oip = ufp->label;
				if(oip->str && StringCmp(oip->str, "Bit Value") == 0)
				{
					if(ufp->choice == 2)
						return (Uint1)(ufp->data.intvalue);
				}
				ufp = ufp->next;
			}
		}
	}

	return 0;
}