File: salpstat.c

package info (click to toggle)
ncbi-tools6 6.1.20090809-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 222,952 kB
  • ctags: 92,767
  • sloc: ansic: 1,297,253; cpp: 6,248; xml: 3,390; sh: 2,981; csh: 488; makefile: 455; perl: 391; lisp: 81
file content (2722 lines) | stat: -rw-r--r-- 90,551 bytes parent folder | download | duplicates (12)
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
/* ===========================================================================
 *
 *                            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 x1have 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.
 *
 * ===========================================================================
*/

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

Author: Hugues Sicotte
        Original Source code was coded (and can be found) while I was 
        working on "whale" program and "refseq" projects.
        Code was consolidated and polished for the dbSNP project.

*/
#include <ncbi.h>
#include <ncbimisc.h> /* For HeapSort */
#include <objseq.h>
#include <objloc.h>
#include <objalign.h>
#include <objgen.h>
#include <salpacc.h>
#include <sequtil.h>
#include <stdio.h>
#include <limits.h>
#include <salpstat.h>
#include <seqport.h>
#include <salpedit.h> /* For SeqAlignSortByStart */

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

#ifdef THIS_MODULE
#undef THIS_MODULE
#endif
#ifdef THIS_FILE
#undef THIS_FILE
#endif
static char *this_module = "salpstat";
#define THIS_MODULE this_module
static char *this_file = __FILE__;
#define THIS_FILE this_file


/* For nucleotides, Lambda, Kappa, H anre rather insensitive to
   parameters since alphabet is small.. b we are restricted to 
   rather close homology.
   */

#define Lambda 1.37
#define Kappa  0.711
#define logK -0.341082849178896
#define H 1.31

/* 
   Make a Blastn Style ScorePtr Chain for SeqAligns who have lost
   or have an invalid ScorePtr chain.
   User provide score and search-space size.
   */

NLM_EXTERN ScorePtr LIBCALL MakeBlastnStyleScore(Int4 score, FloatHi N,Int4 reward) {
  ObjectIdPtr obid;
  ScorePtr scrp,scrp_head;
  FloatHi evalue,bit_score;
  scrp = scrp_head = (ScorePtr) MemNew(sizeof(Score));
  scrp->choice = 2;
  scrp->id = ObjectIdNew();
  obid = scrp->id;
  obid->str = StringSave("score");
  scrp->value.intvalue = score;
  scrp->next = (ScorePtr) MemNew(sizeof(Score));
  scrp=scrp->next;
  scrp->choice = 3;
  scrp->id = ObjectIdNew();
  obid = scrp->id;
  obid->str = StringSave("e_value");
  bit_score = ((((FloatHi)score/((FloatHi)reward))*Lambda) - logK)/NCBIMATH_LN2;
  if(bit_score<0.0) bit_score=0.0;
  if(bit_score>0.0001) {
    evalue = N/pow((FloatHi)2.0,bit_score);
  } else {
    evalue=N;
  }
  scrp->value.realvalue = evalue;
  scrp->next = (ScorePtr) MemNew(sizeof(Score));
  scrp=scrp->next;
  scrp->choice = 3;
  scrp->id = ObjectIdNew();
  obid = scrp->id;
  obid->str = StringSave("bit_score");
  scrp->value.realvalue = bit_score;
  scrp->next = NULL;

  return scrp_head;
}

/* 
   To fix and Make Blastn-Compatible the score 
   User supplies a defaults score if score is not found.
   Invalid ScorePtr's should be removed prior to calling this function.
   */

NLM_EXTERN SeqAlignPtr LIBCALL SeqAlignScoreFix(SeqAlignPtr seqalign,FloatHi score, FloatHi N,Int4 reward) {
  ScorePtr sp=NULL,sp_last;
  ObjectIdPtr obid;
  FloatHi evalue,bit_score;
  Boolean score_set=FALSE, evalue_set=FALSE,bit_score_set=FALSE;
  Int4 int_score= (Int4) score;

  if(seqalign!=NULL) {
    if(seqalign->score==NULL) {
      seqalign->score=MakeBlastnStyleScore(int_score,N,reward);
      score_set  = evalue_set = bit_score_set = TRUE;
    } else {
      for(sp=seqalign->score;sp!=NULL;sp=sp->next) {
	if(sp->id==NULL) {
	  sp->id = ObjectIdNew();
	  sp->id->str = StringSave("unknown");
	  /* sp->id NOT set to anything */
	} else {
	  if (StringCmp(sp->id->str,"e_value")==0) {
	    evalue_set=TRUE;
	  } else if (StringCmp(sp->id->str,"sum_e")==0) {
	    evalue_set=TRUE;
	  } else if (StringCmp(sp->id->str,"score")==0) {
	    score_set=TRUE;
	    score=sp->value.intvalue;
	  } else if (StringCmp(sp->id->str,"bit_score")==0) {
	    bit_score_set=TRUE;
	  }
	}
      }
      bit_score = ((((FloatHi)score/((FloatHi)reward))*Lambda) - logK)/NCBIMATH_LN2;
      if(bit_score<0.0) bit_score=0.0;
      if(bit_score>0.00001) {
	evalue = N/pow((FloatHi)2.0,bit_score);
      } else {
	evalue= N;
      }
      if(evalue_set == FALSE || score_set ==FALSE || bit_score_set==FALSE) {
	for(sp=seqalign->score;sp!=NULL;sp=sp->next) {sp_last=sp;}
	if(evalue_set == FALSE || score_set ==FALSE || bit_score_set==FALSE) {
	  for(sp=seqalign->score;sp!=NULL;sp=sp->next) {sp_last=sp;}
	  if (score_set == FALSE) {
	    sp_last->next = (ScorePtr) MemNew(sizeof(Score));
	    sp_last = sp_last->next;
	    sp_last->choice = 2;
	    sp_last->id = ObjectIdNew();
	    obid = sp_last->id;
	    obid->str = StringSave("score");
	    sp_last->value.intvalue = (Int4) score;
	    sp_last->next=NULL;
	  }
	  if (evalue_set == FALSE) {
	    sp_last->next = (ScorePtr) MemNew(sizeof(Score));
	    sp_last = sp_last->next;
	    sp_last->choice = 3;
	    sp_last->id = ObjectIdNew();
	    obid = sp_last->id;
	    obid->str = StringSave("e_value");
	    sp_last->value.realvalue = evalue;
	    sp_last->next=NULL;
	  }
	  if (evalue_set == FALSE) {
	    sp_last->next = (ScorePtr) MemNew(sizeof(Score));
	    sp_last = sp_last->next;
	    sp_last->choice = 3;
	    sp_last->id = ObjectIdNew();
	    obid = sp_last->id;
	    obid->str = StringSave("sum_e");
	    sp_last->value.realvalue = evalue;
	    sp_last->next=NULL;
	  }
	  if (bit_score_set == FALSE) {
	    sp_last->next = (ScorePtr) MemNew(sizeof(Score));
	    sp_last = sp_last->next;
	    sp_last->choice = 3;
	    sp_last->id = ObjectIdNew();
	    obid = sp_last->id;
	    obid->str = StringSave("bit_score");
	    sp_last->value.realvalue = bit_score;
	    sp_last->next=NULL;
	  }
	}
      }
    }
  }
  return seqalign;
}
/*
  Creates a DNA Scoring Matrix: For the alphabet size =16 (alsize==16), 
  assumes that the alphabet is 
  ncbi4na, and fills scoring matric for  ambiguity codes
  to free matrix, just use Free(matrix).
 */

NLM_EXTERN Int4Ptr PNTR   DNAScoringMatrix(Int4 mismatch, Int4 reward,Int4 alsize){
  Int4Ptr PNTR alignMatrix;
  Int4 i,j,k;
  Int4 nbase1,nbase2;
  Int4 base1[4],base2[4];
  Int4 nmatches;
  /* alsize = alphabet size.. should be a 4 or 16. */
  /* If "ncbi'ized" the codes.. could make matrix this way,
     then use the ncbi translation tools 
     */
  /*  if(alsize !=4 && alsize!=16) {
    ErrPostEx(SEV_WARNING,0,0,"DNAScoringMatrix: No ambiguity codes for alphabet size=%ld\n",alsize);
    } */
  alignMatrix= (Int4Ptr PNTR) Calloc(alsize*(alsize+1),
                                     MAX(sizeof(Int4),sizeof(Int4Ptr)));
  for(i=0;i<alsize;i++) {
    *(alignMatrix+i)=(Int4Ptr) (alignMatrix+(i+1)*alsize);
  }

  for(i=0;i<alsize;i++) {
    for(j=0;j<alsize;j++) {
      alignMatrix[i][j]=mismatch;
    }
  }
  for(i=0;i<alsize;i++)
      alignMatrix[i][i]=reward;
  if(alsize!=16) 
      return alignMatrix;

  /* For ncbi4na. "presence: of bases is Bit-encoded A=1,C=2,G=4,T=8"*/
  /* Score gaps as mismatches... should not be there */
  /*   for(i=0;i<alsize;i++) alignMatrix[0][i]=alignMatrix[i][0]=mismatch; */

  for(i=0;i<alsize;i++) {
    base1[0] = i&1;
    base1[1] = (i>>1)&1;
    base1[2] = (i>>2)&1;
    base1[3] = (i>>3)&1;
    nbase1 = base1[0]+base1[1]+base1[2]+base1[3];
    for(j=0;j<alsize;j++) {
      base2[0] = j&1;
      base2[1] = (j>>1)&1;
      base2[2] = (j>>2)&1;
      base2[3] = (j>>3)&1;
      nbase2 = base2[0]+base2[1]+base2[2]+base2[3];
      nmatches=0;
      for(k=0;k<4;k++) nmatches += (base1[k]&base2[k]);  /* matches */
      if(nbase1==0 || nbase2==0) {
        alignMatrix[i][j]=mismatch; /*gaps */
      } else {
        alignMatrix[i][j] =(reward*nmatches+(nbase1*nbase2-nmatches)*mismatch)/(nbase1*nbase2);
      }
    }
  }
  return alignMatrix;
}

/* 
   NA
   */

NLM_EXTERN Boolean LIBCALL DenseDiagStats(DenseDiagPtr ddp, BioseqPtr bsp_1, BioseqPtr bsp_2, Int4Ptr a_len, Int4Ptr mmatches, Int4Ptr mmismatches, Int4Ptr pmismatches, Int4Ptr mgap_num,FloatHiPtr gap, FloatHiPtr no_gap) {
    ErrPostEx(SEV_WARNING,0,0,"DenseDiagStats not yet implemented for DenseDiag SeqAlign\n");
    return FALSE;
}
/* 
   NA
   */

NLM_EXTERN Boolean LIBCALL StdSegStats(StdSegPtr ssp, BioseqPtr bsp_1, BioseqPtr bsp_2, Int4Ptr a_len, Int4Ptr mmatches, Int4Ptr mmismatches, Int4Ptr pmismatches, Int4Ptr mgap_num,FloatHiPtr gap, FloatHiPtr no_gap) {
        /* e.g. for Translating searched */
    ErrPostEx(SEV_WARNING,0,0,"StdSegStats not yet implemented for StdSeg SeqAlign\n");
    return FALSE;
}
/* 
   NA
   */

NLM_EXTERN Boolean LIBCALL PackSegStats(PackSegPtr psp, BioseqPtr bsp_1, BioseqPtr bsp_2, Int4Ptr a_len, Int4Ptr mmatches, Int4Ptr mmismatches,Int4Ptr pmismatches, Int4Ptr mgap_num,FloatHiPtr gap, FloatHiPtr no_gap) {
    ErrPostEx(SEV_WARNING,0,0,"PackSegStats not yet implemented for PackSeg SeqAlign\n");
    return FALSE;
}
/* 
   Compute Statistics for a single DenseDiag
 */

NLM_EXTERN Boolean LIBCALL DenseSegStats(DenseSegPtr dsp, BioseqPtr bsp_1, BioseqPtr bsp_2, Int4Ptr a_len, Int4Ptr mmatches, Int4Ptr mmismatches, Int4Ptr pmismatches_ptr, Int4Ptr mgap_num,FloatHiPtr gap, FloatHiPtr no_gap) {
  Int4 i,j,k;
  Int4 start_1, start_2,len;
  Int4 matches = 0, mismatches = 0,pmismatches=0;
  Int4 gap_num = 0;
  Uint1 res_1 = 0, res_2 = 0;
  Uint1 strand0,strand1;
  SeqPortPtr spp_1, spp_2;
  Uint1 code;
  Boolean status = TRUE;
  if(dsp && (((mmatches || mmismatches) && bsp_1 && bsp_2)) || !(mmatches || mmismatches)) {
      Boolean is_gap,seek_1=TRUE,seek_2=TRUE;
      if(dsp->strands != NULL) {
          strand0 = dsp->strands[0];
          strand1 = dsp->strands[1];
      } else {
          strand0 = strand1 = 0;
      }
      if(bsp_1->mol == Seq_mol_aa)
          code = Seq_code_ncbieaa;
      else
          code = Seq_code_ncbi4na;
      if(mmatches || mmismatches) {
          spp_1 = SeqPortNew(bsp_1, 0, -1, strand0, code);
          spp_2 = SeqPortNew(bsp_2, 0, -1, strand1, code);
          SeqPortSeek(spp_1, 0, SEEK_SET);
          SeqPortSeek(spp_2, 0, SEEK_SET);
      }
      if(a_len)
          *a_len = 0;
      for(i =0,k=0; i<dsp->numseg; ++i,k+=2) {
          start_1 = dsp->starts[k];
          start_2 = dsp->starts[k+1];
          len = dsp->lens[i];
          if(a_len)
              *a_len += len;
          is_gap = ((start_1 == -1 ) || (start_2 == -1));
          if(is_gap)
              gap_num+=len;
          if(mmatches || mmismatches) {
              if(seek_1 && start_1!=-1) {
                  /* Scan the first time we encounter a real segment */
                  if(strand0 == Seq_strand_minus) 
                      SeqPortSeek(spp_1,(bsp_1->length - start_1-len),SEEK_SET);
                  else
                      SeqPortSeek(spp_1,start_1,SEEK_SET);
                  seek_1 = FALSE;
              }
              if (seek_2 && start_2!=-1) {
                  if(strand1 == Seq_strand_minus) 
                      SeqPortSeek(spp_2,bsp_2->length - (start_2+len),SEEK_SET);
                  else
                      SeqPortSeek(spp_2,start_2,SEEK_SET);
                  seek_2 = FALSE;
              }
              if(is_gap) {
                  /* scan forward */
                  if (start_2 !=-1) {
                      for(j =0; j < len; ++j) {
                          res_2 =  SeqPortGetResidue(spp_2);
                      }
                  } else if(start_1!=-1) {
                      for(j =0; j<len; ++j) {
                          res_1 =  SeqPortGetResidue(spp_1);
                      }
                  }
              } else {
                  for(j =0; j<len; ++j) {
                      res_1 = SeqPortGetResidue(spp_1);
                      res_2 = SeqPortGetResidue(spp_2);
                      if(res_1 == res_2) {
                          ++matches;
                      } else {
                          ++mismatches;
                          if((code == Seq_code_ncbi4na && (res_1&res_2)) || code == Seq_code_ncbieaa)
                              pmismatches++;
                      }
                  }
              }
          }
      }
      SeqPortFree(spp_1);
      SeqPortFree(spp_2);
  } else {
      status = FALSE;
  }
  if(pmismatches_ptr)
      *pmismatches_ptr = pmismatches;
  if(mmatches)
      *mmatches = matches;
  if(mmismatches)
      *mmismatches = mismatches;
  if (no_gap || gap) {
      FloatHi tmp_1,tmp_2;
      tmp_1 = (FloatHi)(matches);
      tmp_2 = (FloatHi)(matches + mismatches);
      if(no_gap) {
          if(tmp_2>0.0)
              *no_gap = 100.0 * (tmp_1/tmp_2);
          else
              *no_gap = 100.0;
      }
      tmp_2 += (FloatHi)gap_num;
      if(gap) {
          if(tmp_2>0.0) 
              *gap = (100.0) * tmp_1/tmp_2;
          else
              *gap = 100.0;
      }
  }
  if(mgap_num)
      *mgap_num=gap_num;
  return status;
}

/*
  Compute Pairwise Statistics for a Single SeqAlign (part of a chain or not)
 */

NLM_EXTERN Boolean LIBCALL SeqAlignSimpleStats(SeqAlignPtr align, BioseqPtr bsp_1, BioseqPtr bsp_2, FloatHiPtr no_gap_ptr, FloatHiPtr gap_ptr, Int4Ptr a_len_ptr, Int4Ptr mmatches_ptr, Int4Ptr mmismatches_ptr, Int4Ptr pmismatches_ptr_in,Int4Ptr mgap_num_ptr) {
  Int4 matches = 0, mismatches = 0, gap_num = 0,pmismatches=0,a_len;
  Int4Ptr matches_ptr, mismatches_ptr, gap_num_ptr,pmismatches_ptr;
  
  if(align && align->segs) {
      if(mmatches_ptr || no_gap_ptr || gap_ptr)
          matches_ptr = &matches;
      else
          matches_ptr = NULL;
      if(mmismatches_ptr || no_gap_ptr || gap_ptr)
          mismatches_ptr = &mismatches;
      else
          mismatches_ptr = NULL;

      if(pmismatches_ptr_in )
          pmismatches_ptr = &pmismatches;
      else
          pmismatches_ptr = NULL;

      if(mgap_num_ptr || gap_ptr)
          gap_num_ptr = &gap_num;
      else
          gap_num_ptr = NULL;
      if(align->segtype==1) {
          DenseDiagPtr ddp;
          ddp = (DenseDiagPtr) align->segs;
          DenseDiagStats(ddp, bsp_1, bsp_2,a_len_ptr,matches_ptr,mismatches_ptr,pmismatches_ptr,gap_num_ptr,gap_ptr, no_gap_ptr);
      } else if (align->segtype==2) {
          DenseSegPtr dsp;
          dsp = (DenseSegPtr) align->segs;
          DenseSegStats(dsp, bsp_1, bsp_2,a_len_ptr,matches_ptr,mismatches_ptr,pmismatches_ptr,gap_num_ptr,gap_ptr, no_gap_ptr);
      } else if (align->segtype==3) {
        /* e.g. for Translating searched */
          StdSegPtr ssp;
          ssp = (StdSegPtr) align->segs;
          StdSegStats(ssp, bsp_1, bsp_2,a_len_ptr,matches_ptr,mismatches_ptr,pmismatches_ptr,gap_num_ptr,gap_ptr, no_gap_ptr);
      } else if (align->segtype==4) {
          PackSegPtr psp;
          psp = (PackSegPtr) align->segs;
          PackSegStats(psp, bsp_1, bsp_2 ,a_len_ptr,matches_ptr,mismatches_ptr,pmismatches_ptr,gap_num_ptr,gap_ptr, no_gap_ptr);
      } else if (align->segtype==5) {
          SeqAlignPtr salp;
          Int4 lcl_a_len,lcl_matches,lcl_mismatches,lcl_pmismatches,lcl_gap_num;
          salp = (SeqAlignPtr) align->segs;
          a_len=matches = mismatches=pmismatches = gap_num=0;
          while(salp!=NULL) {
              SeqAlignSimpleStats(salp,bsp_1, bsp_2, NULL,NULL, &lcl_a_len, &lcl_matches, &lcl_mismatches, &lcl_pmismatches,&lcl_gap_num);
              a_len += lcl_a_len;
              matches +=lcl_matches;
              mismatches += lcl_mismatches;
              pmismatches += lcl_pmismatches;
              gap_num += lcl_gap_num;
              salp=salp->next;
          }
          if(a_len_ptr)
              *a_len_ptr = a_len;
          if(gap_num_ptr)
              *gap_num_ptr = gap_num;
      }
  }
  if(mmatches_ptr)
      *mmatches_ptr = matches;
  if(mmismatches_ptr)
      *mmismatches_ptr = mismatches;
  if(pmismatches_ptr_in)
      *pmismatches_ptr_in = pmismatches;
  if(mgap_num_ptr)
    *mgap_num_ptr = gap_num;
  if (no_gap_ptr || gap_ptr) {
      FloatHi tmp_1,tmp_2;
      tmp_1 = (FloatHi)(matches);
      tmp_2 = (FloatHi)(matches + mismatches);
      if(no_gap_ptr) {
          if(tmp_2>0.0)
              *no_gap_ptr = 100.0 * (tmp_1/tmp_2);
          else
              *no_gap_ptr = 100.0;
      }
      tmp_2 += (FloatHi)gap_num;
      if(gap_ptr) {
          if(tmp_2>0.0) 
              *gap_ptr = (100.0) * tmp_1/tmp_2;
          else
              *gap_ptr = 100.0;
      } 
  }
  return TRUE;
}

/* 
   returns an ordered list of the length of gaps
   for a DenseSeg SeqAlign
   */
NLM_EXTERN Int4Ptr LIBCALL DenseSegGapList(DenseSegPtr dsp,Int4Ptr gap_num) {
    Int4 start_1,start_2;
    Int4 gapnum=0;
    Int4Ptr gap_list=NULL;
    if(dsp){
      Boolean is_gap;
      Int4 i,k;
      for(i =0,k=0; i<dsp->numseg; ++i,k+=2) {
          start_1 = dsp->starts[k];
          start_2 = dsp->starts[k+1];
          is_gap = ((start_1 == -1 ) || (start_2 == -1));
          if(is_gap) 
              ++gapnum;
      }
      if(gapnum) {
          Int4 len;
          gap_list = Malloc(gapnum*sizeof(Int4));
          gapnum=0;
          for(i =0,k=0; i<dsp->numseg; ++i,k+=2) {
              start_1 = dsp->starts[k];
              start_2 = dsp->starts[k+1];
              len = dsp->lens[i];
              is_gap = ((start_1 == -1 ) || (start_2 == -1));
              if(is_gap) {
                  gap_list[gapnum++]=len;
              }
          }
      } else {
          gap_list=NULL;
      }
    }
    if(gap_num)
        *gap_num = gapnum;
    return gap_list;
}

/* 
   NA
   */
NLM_EXTERN Int4Ptr LIBCALL DenseDiagGapList(DenseDiagPtr ddp,Int4Ptr gap_num) {
    ErrPostEx(SEV_WARNING,0,0,"SeqAlignGapList not implemented for DenseSeg SeqAlign\n");
    return NULL;
}
/* 
   NA
   */

NLM_EXTERN Int4Ptr LIBCALL StdSegGapList(StdSegPtr ssp,Int4Ptr gap_num) {
    ErrPostEx(SEV_WARNING,0,0,"SeqAlignGapList not implemented for StdSeg SeqAlign\n");
    return NULL;
}
/* 
   NA
   */

NLM_EXTERN Int4Ptr LIBCALL PackSegGapList(PackSegPtr psp,Int4Ptr gap_num) {
    ErrPostEx(SEV_WARNING,0,0,"SeqAlignGapList not implemented for PackSeg SeqAlign\n");
    return NULL;
}
/*
  Returns a List of the lengths of the Segments with gaps for a single SeqAlign
  limited to pairwise for now.
 */

NLM_EXTERN Int4Ptr LIBCALL SeqAlignGapList(SeqAlignPtr align, Int4Ptr gap_num) {
    if(gap_num)
        *gap_num=0;
    if(align && align->segs) {
        if(align->segtype==1) {
            DenseDiagPtr ddp;
            ddp = (DenseDiagPtr) align->segs;
            return DenseDiagGapList(ddp,gap_num);
        } else if (align->segtype==2) {
            DenseSegPtr dsp;
            dsp = (DenseSegPtr) align->segs;
            return DenseSegGapList(dsp, gap_num);
        } else if (align->segtype==3) {
            /* e.g. for Translating searched */
            StdSegPtr ssp;
            ssp = (StdSegPtr) align->segs;
            return StdSegGapList(ssp, gap_num);
        } else if (align->segtype==4) {
            PackSegPtr psp;
            psp = (PackSegPtr) align->segs;
            return PackSegGapList(psp, gap_num);
        }
    }
    return NULL;
}
/*
  Returns a List of the lengths of the Segments with gaps for a
  linked list of SeqAlign
  limited to pairwise for now.
 */


NLM_EXTERN Int4Ptr LIBCALL SeqAlignListGapList(SeqAlignPtr sap,Int4Ptr gap_num){
  SeqAlignPtr c_align;
  Int4Ptr gap_list=NULL;
  Int4Ptr lcl_gap_list;
  Int4 this_gap_num;
  if(gap_num)
      *gap_num=0;
  if(!sap || !gap_num)
      return NULL;
  for(c_align = sap; c_align != NULL; c_align = c_align->next) {
      lcl_gap_list = SeqAlignGapList(c_align, &this_gap_num);
      if(lcl_gap_list) { 
           gap_list = Realloc(gap_list,
					sizeof(Int4)*(*gap_num+this_gap_num));
           MemCopy(gap_list+*gap_num,lcl_gap_list,sizeof(Int4)*this_gap_num);
           *gap_num+=this_gap_num;
           Free(lcl_gap_list);
           lcl_gap_list=NULL;
      }
  }
  return gap_list;
}


  /* Utility subroutine for SeqAlignWindowStats */

static void LIBCALL UpdateWindowStats(Int4 win_size,Int4 cur_pos,Uint1Ptr win_buf1,Uint1Ptr win_buf2,Uint1 res_1,Uint1 res_2,Uint1 code,Int4Ptr win_gap,Int4Ptr win_gapmismatch,Int4Ptr win_mismatch,Int4Ptr win_match,Boolean N_are_not_mismatches){ 
  Uint1 exit_char1,exit_char2;
  Int4 loc;
  if(win_size<=0) return; /* For case where user didn't care about window */
  loc = cur_pos % win_size;
  exit_char1=win_buf1[loc];
  win_buf1[loc] = res_1;
  exit_char2=win_buf2[loc];
  win_buf2[loc]=res_2;
  
  /* because of ambiguity codes.. a mismatch and a match are
     not the "converse" of each other */
  if(res_1=='-' || res_2=='-') {
    (*win_gap)+=1;
    (*win_gapmismatch)+=1;
  } else if (res_1==res_2 && res_1 !=0 && res_2 != 0) {
    if (code == Seq_code_iupacna) {
      if (res_1 == 'C' || res_1 == 'G' || res_1 =='A' || res_1 == 'T') {
	(*win_match)+=1;
      }
    } else {
      if (res_1 !='X' && res_1 !='*' && res_1 != 'Z') {
	(*win_match)+=1;
      }
    }
    
  } else if (res_1 != 0 && res_2 != 0){
    if (code == Seq_code_iupacna) {
      if (!N_are_not_mismatches || (res_1 != 'N' && res_2 != 'N')) {
	(*win_mismatch)+=1;
	(*win_gapmismatch)+=1;
      }
    } else {
      if (!N_are_not_mismatches || (res_1 != 'X' && res_2 != 'X')) {
	(*win_mismatch)+=1;
	(*win_gapmismatch)+=1;
      }
    }
    
  }
  
  if(exit_char1=='-' || exit_char2=='-') {
    (*win_gap)-=1;
    (*win_gapmismatch)-=1;
  } else if (exit_char1==exit_char2 && exit_char1 != 0 && exit_char2 != 0) {
    if (code == Seq_code_iupacna) {
      if (exit_char1 == 'C' || exit_char1 == 'G' || exit_char1 =='A' || exit_char1 == 'T') {
	(*win_match)-=1;
      }
    } else {
      if (exit_char1 !='X' && exit_char1 !='*' && exit_char1 != 'Z') {
	(*win_match)-=1;
      }
    }
  } else if (exit_char1 != 0 && exit_char2 != 0) {
    if (code == Seq_code_iupacna) {
      if (!N_are_not_mismatches || (exit_char1 != 'N' && exit_char2 != 'N')) {
	(*win_mismatch)-=1;
	(*win_gapmismatch)-=1;
      }
    } else {
      if (!N_are_not_mismatches || (exit_char1 != 'X' && exit_char2 != 'X')) {
	(*win_mismatch)-=1;
	(*win_gapmismatch)-=1;
      }
    }
  } 
}

/* Utility subroutine for SeqAlignWindowStats */

static void LIBCALL CheckMinMax(Int4 win_size,Int4 cur_pos,Int4 win_gap,
			Int4 win_gapmismatch, Int4 win_mismatch,Int4 win_match,
			Int4 *min_mismatch,Int4 *max_mismatch,
			Int4 *min_gap,Int4 *max_gap,
			Int4 *min_gapmismatch,Int4 *max_gapmismatch,
			Int4 *min_match, Int4 *max_match){
  if (cur_pos>=win_size) {
    if (win_gap<*min_gap) *min_gap=win_gap;
    if (win_gapmismatch<*min_gapmismatch) *min_gapmismatch=win_gapmismatch;
    if (win_mismatch<*min_mismatch) *min_mismatch=win_mismatch;
    if (win_match<*min_match) *min_match=win_match;
  }
  if (win_gap>*max_gap) *max_gap=win_gap;
  if (win_gapmismatch>*max_gapmismatch) *max_gapmismatch=win_gapmismatch;
  if (win_mismatch>*max_mismatch) *max_mismatch=win_mismatch;
  if (win_match>*max_match) *max_match=win_match;
}

/* 
   returns the minimum scoring window contained in this seqalign 
   The Scoring system is a simple match/mismatch scheme for now.
*/

NLM_EXTERN Int4 LIBCALL SeqAlignWindowStats(SeqAlignPtr align, BioseqPtr bsp_1, BioseqPtr bsp_2, 
			Int4 blen, Int4 win_size,
			Int4Ptr a_len, Boolean N_are_not_mismatches,
			Int4Ptr mmin_mismatch,Int4Ptr mmax_mismatch,
			Int4Ptr mmin_gap,Int4Ptr mmax_gap,
			Int4Ptr mmin_gapmismatch,
			Int4Ptr mmax_gapmismatch, 
			Int4Ptr mmin_match, Int4Ptr mmax_match,
			Int4Ptr mmatches, Int4Ptr mmismatches, Int4Ptr mgap_num) {
  DenseSegPtr dsp;

  Int4 start_1, stop_1, start_2, stop_2, offset, offset_1, offset_2;
  Int4 astart=0,bstart=0;
  Int4 matches = 0, mismatches = 0, gap_num = 0;
  Boolean is_gap;
  Int4 win_mismatch=0,win_gap=0,win_gapmismatch=0,win_match=0;
  Int4 i, j,len,cur_pos;
  Uint1 res_1 = 0, res_2 = 0;

  Uint1 strand;
  Int4 a;
  SeqPortPtr spp_1, spp_2;
  Uint1 code;
  Uint1Ptr win_buf1;
  Uint1Ptr win_buf2;

  *mmin_mismatch=INT_MAX;
  *mmax_mismatch=0;
  *mmin_gap=INT_MAX;
  *mmax_gap=0;
  *mmin_gapmismatch=INT_MAX;
  *mmax_gapmismatch=0;
  *mmin_match=INT_MAX;
  *mmax_match=0;

  win_buf1=(Uint1Ptr) Calloc(win_size+1,sizeof(Uint1));
  win_buf2=(Uint1Ptr) Calloc(win_size+1,sizeof(Uint1));
  
  dsp = (DenseSegPtr)(align->segs);
  if(dsp->strands != NULL)
    strand = dsp->strands[1];
  else
    strand = 0;
  if(bsp_1->mol == Seq_mol_aa)
    code = Seq_code_ncbieaa;
  else
    code = Seq_code_iupacna;

  spp_1 = SeqPortNew(bsp_1, 0, -1, dsp->strands[0], code);
  spp_2 = SeqPortNew(bsp_2, 0, -1, dsp->strands[1], code);
  SeqPortSeek(spp_1, 0, SEEK_SET);
  SeqPortSeek(spp_2, 0, SEEK_SET);
  
  *a_len = 0;
  cur_pos=1;

  /* Assume that seq1 is on the plus strand */
  for(i =0; i<dsp->numseg; ++i)
    {
      start_1 = dsp->starts[i*2];
      start_2 = dsp->starts[i*2 +1];
      if(i == 0)
	{ 
	  offset_1 = start_1 - astart;
	  if(strand == Seq_strand_minus)
	    offset_2 = blen - (start_2+dsp->lens[0]-1);
	  else
	    offset_2 = start_2 - bstart;
	  
	  /* Advance to first common residue */
	  if(offset_1 != 0 || offset_2 != 0)
	    {
	      a = offset_1; 
	      while(a >0)
		{
		  res_1 =  SeqPortGetResidue(spp_1);
		  --a;
		}
	      a = offset_2;
	      while(a>0) 
		{
		  res_2 =  SeqPortGetResidue(spp_2);
		  --a;
		}
	    }
	  offset = 0;
	}
      *a_len += (dsp->lens[i]);
      is_gap = ((start_1 == -1 ) || (start_2 == -1));
      if (start_1==-1 && start_2==-1) 
	ErrPostEx(SEV_WARNING,0,0,"Illegal seqalign with gaps on both sequences \n!");
      if(is_gap)
	{
	  for(j =0; j<dsp->lens[i]; ++j)
	    {
	      if(start_1 == -1)
		{
		  res_1='-';
		  res_2 =  SeqPortGetResidue(spp_2);
		} else { /* if(start_2 == -1) */
		  res_1 =  SeqPortGetResidue(spp_1);
		  res_2= '-';
		}
	      UpdateWindowStats(win_size,cur_pos,win_buf1,win_buf2,res_1,res_2,code,&win_gap,&win_gapmismatch,&win_mismatch,&win_match,N_are_not_mismatches);
	      CheckMinMax(win_size,cur_pos,win_gap,
			  win_gapmismatch,win_mismatch,win_match,
			  mmin_mismatch,mmax_mismatch,
			  mmin_gap,mmax_gap,
			  mmin_gapmismatch,mmax_gapmismatch,
			  mmin_match,mmax_match);
	      cur_pos+=1;
	    }
	  ++gap_num;
	} else {
	  stop_1 = start_1 + dsp->lens[i] -1;
	  len = stop_1 - start_1 +1;
	  start_2 += offset;
	  stop_2 = start_2 + len -1;
	  if(dsp->strands[0] == Seq_strand_minus)
	    SeqPortSeek(spp_1, bsp_1->length -1 - stop_1, SEEK_SET);
	  else
	    SeqPortSeek(spp_1, start_1, SEEK_SET);
	  if(dsp->strands[1] == Seq_strand_minus)
	    SeqPortSeek(spp_2, bsp_2->length-1 - stop_2, SEEK_SET);
	  else
	    SeqPortSeek(spp_2, start_2, SEEK_SET);
	  for(j =0; j<len; ++j)
	    {
	      res_1 =  SeqPortGetResidue(spp_1);
	      res_2 = SeqPortGetResidue(spp_2);
	      if(res_1 == res_2 && 
		 (N_are_not_mismatches || 
		  (code == Seq_code_ncbieaa && res_1 != (Uint1) 'X') ||
		  (code == Seq_code_iupacna && res_1 != (Uint1) 'N')))
		{
		  ++matches;
		}
	      else
		++mismatches;
	      UpdateWindowStats(win_size,cur_pos,win_buf1,win_buf2,res_1,res_2,code,&win_gap,&win_gapmismatch,&win_mismatch,&win_match,N_are_not_mismatches);
	      CheckMinMax(win_size,cur_pos,win_gap,
			  win_gapmismatch,win_mismatch,win_match,
			  mmin_mismatch,mmax_mismatch,
			  mmin_gap,mmax_gap,
			  mmin_gapmismatch,mmax_gapmismatch,
			  mmin_match,mmax_match);
	      cur_pos+=1;
	    }
	}
    }
  SeqPortFree(spp_1);
  SeqPortFree(spp_2);

  Free(win_buf1);
  Free(win_buf2);
  
  *mmatches = matches;
  *mmismatches = mismatches;
  *mgap_num=gap_num;
  if (cur_pos <=win_size) {
    /* When don't have full window. force minimum values to be 
       that of this maximum available window */
    CheckMinMax(win_size,win_size,win_gap,
		win_gapmismatch,win_mismatch,win_match,
		mmin_mismatch,mmax_mismatch,
		mmin_gap,mmax_gap,
		mmin_gapmismatch,mmax_gapmismatch,
		mmin_match,mmax_match);
    
  } 
  return MIN(cur_pos-1,win_size);
}


/*
  For Pairwise SeqAlign: 
  Compute SeqAlign Statistics for SeqAlign that covers the most bases of the
  second sequence.
 */

NLM_EXTERN void LIBCALL BestSeqAlignStats(SeqAlignPtr seqalign, BioseqPtr query_bsp, 
                       BioseqPtr subject_bsp, FloatHi *no_gap, 
                       FloatHi * gap,
                       Int4Ptr a_length, Int4Ptr mmatches, 
                       Int4Ptr mmismatches, Int4Ptr pmismatches,Int4Ptr gap_num){
    SeqAlignPtr c_align, align=NULL;
    Int4 max_len=0;
    Int4 astart,astop,bstart,bstop;
    
    for(c_align = seqalign; c_align != NULL; c_align = c_align->next) {
        if(!SeqAlignStartStop(&astart, &astop, &bstart, &bstop, c_align, query_bsp, subject_bsp)) {
            ErrPostEx(SEV_WARNING,0,0,"BestSeqAlignStats: Alignment is only gaps\n");
        } else {
            if((bstop - bstart + 1) > max_len)
                {
                    max_len = bstop - bstart;
                    align = c_align;
                }
	}
    }


    if(align != NULL)
        {
            if(!SeqAlignSimpleStats(align, query_bsp, subject_bsp, no_gap, gap, 
                                    a_length, mmatches, mmismatches,pmismatches, gap_num)) {
                ErrPostEx(SEV_WARNING,0,0,"problems computing alignment statistics\n");
            }
        } else
            ErrPostEx(SEV_WARNING,0,0,"BestSeqAlignStats: No good SeqAlign\n");
    
}

/*
  Returns the first Longest SeqAlign in a SeqAlign Linked list.
  all other SeqAligns are freed.
  
 */

NLM_EXTERN SeqAlignPtr LIBCALL SelectLongestSeqAlign (SeqAlignPtr salp)
{
  SeqAlignPtr salptmp,
              tmp,
              select;
  Int4        lens=0,
              lmax=-1;
  Int4        j=0;

  if (salp == NULL)
     return NULL;
  for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next)
     j++;
  if (j<=1)
     return salp;
  for (salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
     lens = SeqAlignLength (salptmp);
     if (lens > lmax)
        lmax = lens;
  }
  select = salp;
  salptmp= salp;
  while (salptmp!=NULL) {
      lens = SeqAlignLength (salptmp);
      if (lens == lmax) {
          select = salptmp;
          salptmp = salptmp->next;
          select->next = NULL;
          salptmp = SeqAlignListFree (salptmp);
      } else {
          tmp = salptmp;
          salptmp = salptmp->next; 
          tmp->next = NULL;
          SeqAlignFree (tmp);
      }
  }
  return select;
}
/*
  CallBack for Sorting by SeqAlign by Length
 */

NLM_EXTERN int LIBCALLBACK SeqAlignLongestFN(VoidPtr a, VoidPtr b){
  SeqAlignPtr sa;
  SeqAlignPtr sb;
  Int4 lena,lenb;
  sa = (SeqAlignPtr) *((SeqAlignPtr PNTR) a);
  sb = (SeqAlignPtr) *((SeqAlignPtr PNTR) b);
  if(sa==NULL|| sb==NULL) {
    if (sa==NULL && sb == NULL) 
      return 0; /* that would be a bug in qsort */
    if(sa==NULL) {
      return 1;
    } else if (sb==NULL) {
      return -1;
    } else {
      return 0;
    }
  }

  lena = SeqAlignLength(sa);
  lenb = SeqAlignLength(sb);
  if(lena > lenb) {
    return (int)-1;
  } else if (lena < lenb ) {
    return (int)1;
  } else {
    return (int)0;
  }
}




/* restrict overlapping of seqaligns up to 1 bases per positions,
   for Denseseg(blast2) only keep the hits on same strand as longest hit
   The result is resorted so that earlier segments are first.
   Also, Do not allow a query segment to be used twice.(e.g. repeats)
   Keep the query sub-alignment that is part of the longest segment.
   This is only valid for pairwise alignments.
   returns the rejected SeqAligns as salp_leftover

   */

NLM_EXTERN SeqAlignPtr LIBCALL SeqAlignNonOverlap(SeqAlignPtr salp,BioseqPtr query_bsp,BioseqPtr subject_bsp,SeqAlignPtr PNTR salp_leftover_ptr,Int4 Coverage) {
    SeqAlignPtr salptmp;
    Uint1Ptr HitsPerQBase;
    Uint1Ptr HitsPerSBase;
    Uint1Ptr AcceptList;
    Int4 i,j,k,l;
    Int4 qpos,spos,qend_pos,send_pos;
    Int4 a_start,b_start,a_stop,b_stop;
    DenseSegPtr dsp;
    DenseDiagPtr ddp;
    SeqAlignPtr align,new_salp,salp_leftover=NULL;
    SeqAlignPtr salp_left_tmp=NULL;
    SeqAlignPtr PNTR salp_list;

    Int4 a_order,b_order;

    Int4 ipos,jpos,n_sap;
    Int2 best_qstrand=-1,best_sstrand=-1;

    if (salp == NULL)
        return NULL;
  
    /* Count Seq-aligns */
    for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
        j++;
    }
    if (j<=1)
        return salp;
    n_sap=j;
    
    a_start = INT4_MAX;
    b_start = INT4_MAX;
    a_stop=-1;
    b_stop=-1;
    for (salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
        Int4 lcl_a_start,lcl_a_stop,lcl_b_start,lcl_b_stop;
        if(SeqAlignStartStop(&lcl_a_start, &lcl_a_stop, &lcl_b_start, &lcl_b_stop,
                             salptmp, query_bsp, subject_bsp)) {
            if(lcl_a_start!=-1 && lcl_a_start<a_start)
                a_start=lcl_a_start;
            if(lcl_b_start!=-1 && lcl_b_start<b_start)
                b_start=lcl_b_start;
            if(lcl_a_stop>a_stop)
                a_stop=lcl_a_stop;
            if(lcl_b_stop>b_stop)
                b_stop=lcl_b_stop;
        }
    }
    salp_list=(SeqAlignPtr PNTR) Malloc((size_t)((n_sap+1)*(sizeof(salp_list[0]))));
    for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next,j++) {
        salp_list[j]=salptmp;
    }
    for (j=0; j<n_sap; j++) {
        salp_list[j]->next=NULL;
    }
    HeapSort((void *)salp_list,(size_t)n_sap,(size_t)sizeof(salp_list[0]),SeqAlignLongestFN);    
    
    HitsPerQBase = (Uint1Ptr) Calloc(a_stop+1,sizeof(Uint1));
    HitsPerSBase = (Uint1Ptr) Calloc(b_stop+1,sizeof(Uint1));
    AcceptList = (Uint1Ptr) Calloc(n_sap+1,sizeof(Uint1));

    /* Loop over length-ordered Alignments: Keep Best Non-overlappping regions*/
    for(i=0;i<n_sap;i++) {
        align=salp_list[i];
        if(align!=NULL) {
            SeqAlignBioseqsOrder(align,query_bsp,subject_bsp,&a_order,&b_order);
            /* Check if any bases were not already covered. */
            /* bases on the "non-gapped sequence" of gapped segments
               are considered covered. */
            if(align->segtype==1) {
                ddp = (DenseDiagPtr) (align->segs);
                if(ddp) {
                    AcceptList[i]=1;
                }
                while(ddp!=NULL && AcceptList[i]!=0) {
                    if(best_qstrand ==-1) best_qstrand = (Int2)ddp->strands[a_order];
                    if(best_sstrand ==-1) best_sstrand = (Int2)ddp->strands[b_order];
                    qpos=ddp->starts[a_order];
                    if(qpos>=0) {
                        if(best_qstrand != (Int2)ddp->strands[a_order]) {
                            AcceptList[i]=0;
                            break;
                        }
                    }
                    spos=ddp->starts[b_order];
                    if(spos>=0) {
                        if(best_sstrand != (Int2)ddp->strands[b_order]) {
                            AcceptList[i]=0;
                            break;
                        }
                    }
                    qend_pos=qpos+ddp->len;
                    send_pos=spos+ddp->len;
                    for(k=qpos,l=spos;k<qend_pos && l<send_pos;k++,l++) {
                        if((qpos!=-1 && HitsPerQBase[k]>=Coverage)  || (spos!=-1 && HitsPerSBase[l]>=Coverage)) {
                            AcceptList[i]=0;
                            qpos+=qend_pos;
                        }
                    }
                    ddp = ddp->next;
                } 
            } else if(align->segtype==2) {
                dsp = (DenseSegPtr) align->segs;
                if(dsp!=NULL) {
                    AcceptList[i]=1;
                    if(best_qstrand ==-1) {
                        if(dsp->strands!=NULL)
                            best_qstrand = (Int2)dsp->strands[a_order];
                        else
                            best_qstrand = 0;
                    }
                    if(best_sstrand ==-1) {
                        if(dsp->strands!=NULL) 
                            best_sstrand = (Int2)dsp->strands[b_order];
                        else
                            best_sstrand = 0;
                    }
                    for(j = 0; j<dsp->numseg; ++j) {
                        ipos = 2*j + a_order;
                        qpos=dsp->starts[ipos];
                        if(qpos>=0) {
                            if(dsp->strands!=NULL && best_qstrand != (Int2)dsp->strands[ipos]) {
                                AcceptList[i]=0;
                                break;
                            }
                        }
                        jpos = 2*j + b_order;
                        spos=dsp->starts[jpos];
                        if(spos>=0) {
                            if(dsp->strands!=NULL && best_sstrand != (Int2)dsp->strands[jpos]) {
                                AcceptList[i]=0;
                                break;
                            }
                        }
                        qend_pos=qpos+dsp->lens[j];
                        send_pos=spos+dsp->lens[j];
                        {
                            for(k=qpos,l=spos;k<qend_pos &&l<send_pos;k++,l++) {
                                if((qpos!=-1 && HitsPerQBase[k]>=Coverage)  || (spos!=-1 && HitsPerSBase[l]>=Coverage)) {
                                    AcceptList[i]=0;
                                    k+=qend_pos; 
                                    j+=dsp->numseg;
                                }
                            }
                        }
                    }
                }
            }
            /* If we've accepted the new segment(s), 
               .. and there is room to accep them.. increment counters */
            if(AcceptList[i]==1) {/* increment B-value counter for bases */
                if(align->segtype==1) {
                    ddp=(DenseDiagPtr)align->segs;
                    while(ddp!=NULL) {
                        qpos=ddp->starts[a_order];
                        spos=ddp->starts[b_order];
                        if(qpos!=-1 && spos!=-1) {
                            qend_pos=qpos+ddp->len;
                            send_pos=spos+ddp->len;
                            for(k=qpos,l=spos;k<qend_pos && l<send_pos;k++,l++) {
                                if(qpos!=-1) 
                                    HitsPerQBase[k]+=1;
                                if(spos!=-1) 
                                    HitsPerSBase[l]+=1;
                                if((qpos!=-1 && HitsPerQBase[k]>Coverage)  || (spos!=-1 && HitsPerSBase[l]>Coverage)) {
                                    AcceptList[i]=0;
                                    k+=qend_pos;
                                    j+=dsp->numseg;
                                }
                            }
                        }
                        ddp = ddp->next;
                    } 
                } else if(align->segtype==2) {
                    dsp = (DenseSegPtr) align->segs;
                    if(dsp!=NULL) {
                        for(j = 0; j<dsp->numseg; ++j) {
                            ipos = 2*j + a_order;
                            jpos = 2*j + b_order;
                            qpos=dsp->starts[ipos];
                            spos=dsp->starts[jpos];
                            qend_pos=qpos+dsp->lens[j];
                            send_pos=spos+dsp->lens[j];
                            for(k=qpos,l=spos;k<qend_pos && l<send_pos;k++,l++) {
                                if(qpos!=-1) 
                                    HitsPerQBase[k]+=1;
                                if(spos!=-1) 
                                    HitsPerSBase[l]+=1;
                                if((qpos!=-1 && HitsPerQBase[k]>Coverage)  || (spos!=-1 && HitsPerSBase[l]>Coverage)) {
                                    ErrPostEx(SEV_WARNING,0,0,"SeqAlign maps more than once bases in the subject\n");
                                    AcceptList[i]=0;
                                    k+=qend_pos;
                                    j+=dsp->numseg;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /* Shift down list */
    salp=new_salp=salp_list[0]; /* Keep at least first one */
    for(i=1;i<n_sap;i++) {
        salptmp=salp_list[i];
        if (salptmp==NULL)
            break;
        if(AcceptList[i]==0) {
            if(salp_leftover_ptr) {
                if(salp_leftover) {
                    salp_left_tmp->next=salptmp;
                } else {
                    salp_leftover=salptmp;
                }
                salp_left_tmp=salptmp;
            } else {
                salptmp->next=NULL;
                salp_list[i] = SeqAlignFree (salptmp);
            }
        } else {
            salp->next=salptmp;
            salp=salptmp;
        }
    }
    salp->next=NULL;
    if(salp_left_tmp) 
        salp_left_tmp->next=NULL;
    if(salp_leftover_ptr)
        *salp_leftover_ptr=salp_leftover;
    Free(AcceptList);
    Free(HitsPerQBase);
    Free(HitsPerSBase);
    
    Free(salp_list);
    return SeqAlignSortByStart(new_salp,(Int2)0);
}

NLM_EXTERN Boolean LIBCALL SeqAlignConsistentOverlap(SeqAlignPtr salptmp2, SeqAlignPtr salptmp) {
    ErrPostEx(SEV_WARNING,0,0,"One Alignment may be truncated due to repeats\n");
    return FALSE;
}

/*
  Take Two sets of Starts and Stops and returns the Overlap.
 */
NLM_EXTERN Int4 LIBCALL SeqAlignStartStopOverlap(Int4 a_start1, Int4 a_stop1, Int4 b_start1, Int4 b_stop1,Int4 a_start2, Int4 a_stop2, Int4 b_start2, Int4 b_stop2,Int4Ptr Overlap_lena, Int4Ptr Overlap_lenb) {
    Int4 overlap_lena=0,overlap_lenb=0;
    Boolean overlapa=FALSE,overlapb=FALSE;

    if(a_start1>=a_start2 && a_stop2>=a_start1) {
        overlapa=TRUE;
        overlap_lena=a_stop2-a_start1+1;
    } else if (a_start2>=a_start1 && a_stop1>=a_stop2) {
        overlapa=TRUE;
        overlap_lena=a_stop1-a_start2+1;
    }
    if(b_start1>=b_start2 && b_stop2>=b_stop1) {
        overlapb=TRUE;
        overlap_lenb=b_stop2-b_start1+1;
    } else if(b_start2>=b_start1 && b_stop1>=b_stop2) {
        overlapb=TRUE;
        overlap_lenb=b_stop1-b_start2+1;
    }
    if(Overlap_lena)
        *Overlap_lena=overlap_lena;
    if(Overlap_lenb)
        *Overlap_lenb=overlap_lenb;
    return (overlapa || overlapb);
}

/* 
   Takes a linked list of blast SeqAligns for a pair of sequences and
   make a non-redundant SeqAlign.
   
   */

NLM_EXTERN SeqAlignPtr LIBCALL SeqAlignNonRedundant(SeqAlignPtr salp,BioseqPtr query_bsp,BioseqPtr subject_bsp,SeqAlignPtr PNTR salp_leftover_ptr) {
    SeqAlignPtr salptmp,salptmp2,salpprev2,salptmp2next;
    SeqAlignPtr salptmplast;
    Int4 i,j;
    
    SeqAlignPtr salp_leftover=NULL;
    Boolean NeedsMerging,OverlapOK;

    if (salp == NULL)
        return NULL;
  
    /* Count Seq-aligns */
    for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
        j++;
    }
    if (j<=1)
        return salp;
    
    salp = SeqAlignNonOverlap(salp,query_bsp,subject_bsp,&salp_leftover,1);
    if(!salp_leftover)
        return salp;

    /* Count Seq-aligns */
    for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
        j++;
    }

    /* Count Seq-aligns */
    for (j=0,salptmp=salp_leftover; salptmp!=NULL; salptmp=salptmp->next) {
        j++;
    }
    salpprev2=NULL;
    for(salptmp2=salp_leftover,i=0;salptmp2!=NULL;salptmp2=salptmp2next,i++) {
        Int4 left_a_start,left_a_stop,left_b_start,left_b_stop;
        salptmp2next=salptmp2->next;
        if(SeqAlignStartStop(&left_a_start, &left_a_stop, &left_b_start, &left_b_stop,salptmp2, query_bsp, subject_bsp)) {
            OverlapOK = TRUE; /* Set to TRUE if it is OK to add to list. */
            NeedsMerging = FALSE; /* Set to TRUE if need to Merge SeqAligns before adding */
            salptmplast=NULL;
            /* Loop over all the alignment already accepted.. and
               make sure that no overlap is inconsistent */
            for (salptmp=salp,j=0; salptmp!=NULL && OverlapOK; salptmp=salptmp->next,j++) {
                Int4 lcl_a_start,lcl_a_stop,lcl_b_start,lcl_b_stop;
                Int4 olap_a,olap_b;
                SeqAlignStartStop(&lcl_a_start, &lcl_a_stop, &lcl_b_start, &lcl_b_stop, salptmp, query_bsp, subject_bsp);
                /* Simple Check to see if the two SeqAlign overlap in coverage.
                 */
                if(SeqAlignStartStopOverlap(left_a_start, left_a_stop, left_b_start, left_b_stop, lcl_a_start, lcl_a_stop, lcl_b_start, lcl_b_stop,&olap_a,&olap_b)) {
                    NeedsMerging = TRUE;
                    if(olap_a==olap_b && SeqAlignConsistentOverlap(salptmp2,salptmp)) {
                        /* XXXX Overlapping region of alignment is the
                           same.. => Remember that this one must
                           be truncated
                           */
                    } else {
                        OverlapOK=FALSE;
                    }
                }
                salptmplast=salptmp;
            }
            if(OverlapOK) {
                    if(NeedsMerging) {
                        /* delete from salp2 */
                        for (salptmp=salp,j=0; salptmp!=NULL && OverlapOK; salptmp=salptmp->next,j++) {
                            Int4 lcl_a_start,lcl_a_stop,lcl_b_start,lcl_b_stop;
                            SeqAlignStartStop(&lcl_a_start, &lcl_a_stop, &lcl_b_start, &lcl_b_stop, salptmp, query_bsp, subject_bsp);
                            if(SeqAlignStartStopOverlap(left_a_start, left_a_stop, left_b_start, left_b_stop, lcl_a_start, lcl_a_stop, lcl_b_start, lcl_b_stop,NULL,NULL)) {
                                /* SeqAlignDeleteSeqLocs(); */
                            }
                        }
                    }
                    if(salptmplast)
                        salptmplast->next=salptmp2;
                    else
                        salp = salptmp2;
                    salptmp2->next=NULL;
                    if(salpprev2) {
                        salpprev2->next=salptmp2next;
                    } else {
                        salp_leftover = salptmp2next;
                    }
            }else
                salpprev2=salptmp2;
        } else
            salpprev2=salptmp2;
    }
    if(salp_leftover_ptr)
        *salp_leftover_ptr = salp_leftover;
    return salp;
}







/*
   restrict overlapping of seqaligns up to Cov(Coverage) bases per positions,
   for Denseseg(blast2) only keep the hits on same strand as longest hit
   The result is resorted so that earlier segments are first.
   Also, Do not allow a query segment to be used twice.(e.g. repeats)
   Keep the query sub-alignment that is part of the longest segment.
   This is only valid for pairwise alignments.

   Should change the algorithm to assume that there is an overlapping
   region.. and to thus look for that.. e.g. 
   Sort SeqAligns by query-start.
   look for overlapping using start/stops 
   .. if it finds it.. it then uses that to merge the alignments.

   Merge overlapping alignments.. (also deals with non-identical alignments
   by )

   Second Pass Sort by alignment length,
   and keep non-overlapping ones.
   */







/*
  Function to count the number of mismatches in alignments
   Independent of mol type, works for both types of
   alignments.
   */

NLM_EXTERN Int4 LIBCALL SeqAlignListCountMismatches(SeqAlignPtr sap,BioseqPtr query_bsp, 
		     BioseqPtr subject_bsp,
		     Int4Ptr a_length, Int4Ptr mmatches, 
		     Int4Ptr mmismatches, Int4Ptr pmismatches_ptr,Int4Ptr gap_num){
  SeqAlignPtr align;
  FloatHi no_gap, gap;
  Int4 mismatches=0;

  if(a_length)
      *a_length=0;
  if(mmatches)
      *mmatches=0;
  if(mmismatches)
      *mmismatches=0;
  if(pmismatches_ptr)
      *pmismatches_ptr=0;
  if(gap_num)
      *gap_num=0;

  for(align = sap; align != NULL; align = align->next) {
      Int4 this_mismatch=0,this_match=0,this_alength=0,this_gap_num=0;
      Int4 this_pmismatches=0;
      Int4 astart=-1,astop=-1,bstart=-1,bstop=-1;
      if(!SeqAlignStartStop(&astart, &astop, &bstart, &bstop, align, query_bsp, subject_bsp)) {
	  ErrPostEx(SEV_WARNING,0,0,"problems computing alignment min/max for 1 sub-seqalign\n");
	  continue;
      } else if (!SeqAlignSimpleStats(align, query_bsp, subject_bsp, 
				&no_gap, &gap,
				&this_alength, 
				&this_match, &this_mismatch, &this_pmismatches,
				&this_gap_num)) {
	    ErrPostEx(SEV_WARNING,0,0,"problems computing alignment statistics\n");
	    continue;
      }
      if(a_length)
	  *a_length+=this_alength;
      if(mmatches) 
	  *mmatches+=this_match;
      mismatches+=this_mismatch;
      if(gap_num)
	  *gap_num+=this_gap_num;
      if(pmismatches_ptr)
          *pmismatches_ptr +=this_pmismatches;
  }
  if(mmismatches)
      *mmismatches = mismatches;
  return mismatches;
}

/*
  Function to count the number of mismatches in alignments
   Independent of mol type, works for both types of
   alignments.
   */

NLM_EXTERN Int4 LIBCALL SeqAlignCountMismatches(SeqAlignPtr sap,BioseqPtr query_bsp, 
		     BioseqPtr subject_bsp,
		     Int4Ptr a_length, Int4Ptr mmatches, 
		     Int4Ptr mmismatches, Int4Ptr pmismatches_ptr,Int4Ptr gap_num){
  FloatHi no_gap, gap;
  Int4 mismatches=0;
  if(a_length)
      *a_length=0;
  if(mmatches)
      *mmatches=0;
  if(mmismatches)
      *mmismatches=0;
  if(pmismatches_ptr)
      *pmismatches_ptr=0;
  if(gap_num)
      *gap_num=0;

  if (sap) {
      Int4 this_mismatch=0,this_match=0,this_alength=0,this_gap_num=0;
      Int4 this_pmismatches=0;
      Int4 astart=-1,astop=-1,bstart=-1,bstop=-1;
      if(!SeqAlignStartStop(&astart, &astop, &bstart, &bstop, sap, query_bsp, subject_bsp)) {
	  ErrPostEx(SEV_WARNING,0,0,"problems computing alignment min/max for 1 sub-seqalign\n");
      } else if (!SeqAlignSimpleStats(sap, query_bsp, subject_bsp, 
				&no_gap, &gap,
				&this_alength, 
				&this_match, &this_mismatch, &this_pmismatches,
				&this_gap_num)) {
	    ErrPostEx(SEV_WARNING,0,0,"problems computing alignment statistics\n");
      }
      if(a_length)
	  *a_length=this_alength;
      if(mmatches) 
	  *mmatches=this_match;
      mismatches=this_mismatch;
      if(gap_num)
	  *gap_num=this_gap_num;
      if(pmismatches_ptr)
          *pmismatches_ptr =this_pmismatches;
  }
  if(mmismatches)
      *mmismatches = mismatches;
  return mismatches;
}

/* Find length of Longest Segment for a pairwise SeqAlign */

NLM_EXTERN Int4 LIBCALL SeqAlignLongestSegment(SeqAlignPtr sap,Int4Ptr max_len,Int4Ptr max_qstart,Uint1Ptr max_qstrand,Int4Ptr max_sstart,Uint1Ptr max_sstrand) {
  Int4 j,a_order,b_order,ipos,jpos;
  Int4 qpos,spos,qposl=0,sposl=0;
  Int4 maxlen=-1;
  Uint1 sstrand=0,qstrand=0;
  if(sap==NULL)
    return 0;
  {
      BioseqPtr query_bsp=NULL,subject_bsp=NULL;
      SeqAlignBioseqsOrder(sap,query_bsp,subject_bsp,&a_order,&b_order);
      if(sap->segtype==1) {
          DenseDiagPtr ddp;
          ddp = (DenseDiagPtr) (sap->segs);
          while(ddp!=NULL) {
              qpos=ddp->starts[a_order];
              spos=ddp->starts[b_order];
              if(qpos!=-1 && spos!=-1 ) {
                  if(ddp->len>maxlen) { 
                      maxlen=ddp->len;
                      qposl=qpos;
                      sposl=spos;
                      qstrand=ddp->strands[a_order];
                      sstrand=ddp->strands[b_order];
                  }
              }
              ddp = ddp->next;
          }
      } else if(sap->segtype==2) {
          DenseSegPtr dsp;
          dsp = (DenseSegPtr) sap->segs;
          if(dsp!=NULL) {
              for(j = 0; j<dsp->numseg; ++j) {
                  ipos = 2*j + a_order;
                  qpos=dsp->starts[ipos];
                  jpos = 2*j + b_order;
                  spos=dsp->starts[jpos];
                  if(qpos!=-1 && spos!=-1 ) {
                      if(dsp->lens[j]>maxlen) {	      
                          maxlen=dsp->lens[j];
                          qposl=qpos;
                          sposl=spos;
                          qstrand=dsp->strands[ipos];
                          sstrand=dsp->strands[jpos];
                      }
                  }
              }
          }
      }
      sap=sap->next;
  }
  if(max_len)
      *max_len=maxlen;
  if(max_qstart)
      *max_qstart=qposl;
  if(max_sstart)
      *max_sstart=sposl;
  if(max_qstrand)
      *max_qstrand=qstrand;
  if(max_sstrand)
      *max_sstrand=sstrand;
 
  if(maxlen==-1)
      return -2;
  else
      return 0;

}

NLM_EXTERN Int4 LIBCALL SeqAlignListLongestSegment(SeqAlignPtr sap,Int4Ptr max_len,Int4Ptr max_qstart,Uint1Ptr max_qstrand,Int4Ptr max_sstart,Uint1Ptr max_sstrand) {
    Int4 maxlen;
    if(!sap)
        return -1;
    else {
        Int4 lcl_max_sstart,lcl_max_qstart;
        Int4 lcl_max_len;
        Uint1 lcl_max_qstrand,lcl_max_sstrand;
        maxlen=-1;
        while(sap) {
            if(SeqAlignLongestSegment(sap,&lcl_max_len,&lcl_max_qstart,&lcl_max_qstrand,&lcl_max_sstart,&lcl_max_sstrand)==0) {
                if(lcl_max_len >=maxlen) {
                    maxlen=lcl_max_len;
                    if(max_len)
                        *max_len = maxlen;
                    if(max_qstart)
                        *max_qstart = lcl_max_qstart;
                    if(max_sstart)
                        *max_sstart=lcl_max_sstart;
                    if(max_qstrand)
                        *max_qstrand=lcl_max_qstrand;
                    if(max_sstrand)
                        *max_sstrand=lcl_max_qstrand;
                }
            }
            sap=sap->next;
        }
    }
    if(maxlen==-1)
        return -1;
    else
        return 0;
}

/* 
   Returns the possible overlapping length between two sequences
   according to the "phase" of the longest (ungapped) alignment
   segment
   */

NLM_EXTERN Int4 LIBCALL SeqAlignOverlapLen(SeqAlignPtr sap,BioseqPtr query_bsp,BioseqPtr subject_bsp) {
  Int4 Overlap;
  Int4 qposl,sposl;
  Int4 maxlen=-1,lens,lenq;
  Int4 diag;
  Uint1 sstrand,qstrand;

  if(sap==NULL || query_bsp==NULL || subject_bsp==NULL) {
      return 0;
  }

  if(SeqAlignLongestSegment(sap,&maxlen,&qposl,&qstrand,&sposl,&sstrand)!=0)
      return 0;
  if(maxlen==-1)
      return 0;
  lenq=query_bsp->length;
  lens=subject_bsp->length;

  /* Find intersections using simple plane geometry and a
     few shortcuts
     */  
  if(qstrand==Seq_strand_minus) 
      qposl+=(maxlen-1);
  if(sstrand==Seq_strand_minus) 
      sposl+=(maxlen-1);

  if(qstrand==sstrand || (qstrand!=Seq_strand_minus && sstrand !=Seq_strand_minus)) {
      diag = qposl-sposl;
      if(diag>0) {
          Overlap = lenq-diag;
          if(Overlap>lens) 
              Overlap= lens;
      } else {
          Overlap = lens+diag;
          if(Overlap>lenq) 
              Overlap= lenq;
      }
  } else { /* Opposite strands */
      diag=qposl+sposl;
      /* posA+posB = diag = constant 
         
       */
      Overlap = diag+1;
      if(lenq<=diag)
          Overlap -= (diag-lenq+1);
      if(lens<=diag)
          Overlap -= (diag-lens+1);
  }
  if(Overlap<0 || Overlap>lenq || Overlap>lens) {
    ErrPostEx(SEV_ERROR,0,0,"Overlap may have bugs!\n");
    if (Overlap<0) {
      Overlap=0;
    }
    if (Overlap>lenq)
      Overlap=lenq;
    if (Overlap>lens)
      Overlap=lens;
  }
  return Overlap;
}


/* Find the SeqAlignOverlap for a SeqAlign obtained from aligning
   two sequence Intervals .. The Overlap is computed
   according to the query&subject positions
   of the longest ungapped block.
   */

NLM_EXTERN Int4 LIBCALL SeqAlignOverlapLenByLoc(SeqAlignPtr sap,SeqLocPtr query_slp,SeqLocPtr subject_slp) {
  Int4 Overlap;
  Int4 qposl,sposl;
  Int4 maxlen=-1;
  Int4 diag;
  Int4 qmax,smax,qmin,smin;

  Uint1 sstrand,qstrand;

  if(sap==NULL || query_slp==NULL || subject_slp==NULL) {
    return 0;
  }

  if(SeqAlignLongestSegment(sap,&maxlen,&qposl,&qstrand,&sposl,&sstrand)!=0)
      return 0;

  if(maxlen==-1) 
    return 0;
  
  /* Set Up Window Coordinated. */
  qmax = SeqLocStop(query_slp);
  qmin = SeqLocStart(query_slp);

  smax = SeqLocStop(subject_slp);
  smin = SeqLocStart(subject_slp);
  /*
    Correct Positions For Minus Strand:
    SeqAlign Starts are always lowest Coord of block, even on Minus strand 
    */
  if(qstrand==Seq_strand_minus) 
      qposl+=(maxlen-1);
  if(sstrand==Seq_strand_minus) 
      sposl+=(maxlen-1);

  if(qstrand==sstrand) {
    diag = qposl-sposl;
    if(diag>0) {
        Overlap = qmax-diag +1;
        if(Overlap>smax) 
            Overlap= smax;
        Overlap -= smin;
    } else {
        Overlap = smax+diag +1;
        if(Overlap>qmax) 
            Overlap= qmax;
        Overlap -=qmin;
    }
    Overlap+=1;
  } else { /* Opposite strands */
      Int4 Intercept,Interceptl;
    diag=qposl+sposl;
    /* posA+posB = diag = constant 
       
       */
    Intercept = diag-smin;
    if(Intercept>qmax)
        Intercept=qmax;
    Interceptl = diag-smax;
    if(qmin>Interceptl)
        Intercept-=qmin;
    else
        Intercept-=Interceptl;

    Overlap=Intercept;
  }
  if(Overlap<0)
      Overlap=0;

  return Overlap;
}



/* Returns the percentage of the sequence that matched (number of matches)
   divided by the length that could have aligned.
   Given the relative offset of the longest segment of the seqalign.
   It is maxed out at 100%.
   */

NLM_EXTERN FloatHi LIBCALL SeqAlignAlignability(SeqAlignPtr sap,BioseqPtr query_bsp, BioseqPtr subject_bsp, Int4Ptr Overlap_len,Int4Ptr aln_len,Int4Ptr virtual_mismatches,Int4Ptr mismatches,Int4Ptr gap_num,Int4Ptr matches) {
  FloatHi alignability=0.0;
  Int4 overlap,lcl_matches;
  if(sap!=NULL) {
      SeqAlignCountMismatches(sap,query_bsp, subject_bsp,
                      aln_len, &lcl_matches, 
                      mismatches, NULL,gap_num);
      overlap=SeqAlignOverlapLen(sap,query_bsp,subject_bsp);
      if(matches)
          *matches = lcl_matches;
      if(overlap!=0) {
          alignability= (FloatHi) 100.0*(lcl_matches)/overlap;
          if(alignability>100.0) 
              alignability=100.0;
      } else {
          alignability= (FloatHi) 0.0;
      }
      if(virtual_mismatches)
          *virtual_mismatches = overlap-lcl_matches;
      if(Overlap_len)
          *Overlap_len=overlap;
  } else {
      if(aln_len)
          *aln_len=0;
      if(mismatches)
          *mismatches=0;
      if(matches)
          *matches=0;
      if(gap_num)
          *gap_num=0;
      if(Overlap_len)
          *Overlap_len=0;
      if(virtual_mismatches)
          *virtual_mismatches =0;
  }
  return alignability;
}

/* Assumes that the SeqAlign was obtained by aligning the two SeqLocs..
no check is made to verify that.
*/

NLM_EXTERN FloatHi LIBCALL AlignabilityByLoc(SeqAlignPtr sap,SeqLocPtr query_slp, SeqLocPtr subject_slp, Int4Ptr Overlap_len,Int4Ptr aln_len,Int4Ptr virtual_mismatches,Int4Ptr mismatches,Int4Ptr gap_num,Int4Ptr matches) {
  FloatHi alignability=0.0;
  Int4 overlap=0,lcl_matches;
  if(sap!=NULL) {
      BioseqPtr query_bsp,subject_bsp;
      query_bsp = BioseqLockById(SeqLocId(query_slp));
      subject_bsp = BioseqLockById(SeqLocId(subject_slp));
      SeqAlignCountMismatches(sap,query_bsp, subject_bsp,
                              aln_len, &lcl_matches, 
                              mismatches, NULL,gap_num);
      BioseqUnlock(query_bsp);
      BioseqUnlock(subject_bsp);
      overlap=SeqAlignOverlapLenByLoc(sap,query_slp,subject_slp);
      if(overlap!=0) {
          alignability= (FloatHi) 100.0*(lcl_matches)/overlap;
          if(alignability>100.0) 
              alignability=100.0;
      } else {
          alignability= (FloatHi) 0.0;
      }
  } else {
      if(aln_len)
          *aln_len=0;
      if(mismatches)
          *mismatches=0;
      if(gap_num)
          *gap_num=0;
      lcl_matches=0;
  }
  if(matches)
      *matches=lcl_matches;
  if(virtual_mismatches)
      *virtual_mismatches = overlap-lcl_matches;
  if(Overlap_len)
      *Overlap_len=overlap;
  return alignability;
}



/* Function to return a vector of Blast-Style Score pointers.
   Windows of size win_size
   starting at offset win_offset   (usually 0)
   Each window shifted by win_step (minimum of 1)
   Match = Match score for aligned residues (e.g. 1)
   mismatch = mismatch score for aligned but mismatching residues (e.g. -3)

   As input it requires the sizeof the SearchSpace. This is
   simply (sizeof(bsp1)-word_size)*(sizeof(database)-word_size*NumberOfsequencesInDatabase)
where word_size is the blast word-size (e.g. 11)
sizeof(database) == Number of residues in database



   This program assumes that Each DenseSeg Seqalign is contigous
   and non-overlapping (e.g. that no seqalign is a concatenation of
   two local alignments). Consecutive Seqaligns in the Chain
   don't have to be contigous. This Subroutine does not try
   to resolve segments scores between two different seqaligns.

   Gaps on the edges of each window are not scored.

   if(matrix==NULL) ==> Only searches for longest segment of perfect matches;

   returns a vector of blast scores per window, and the number of windows.

   and the longest perfect segment and it's
   start position (in 0-offset)(perfect_len ==0 if there are perfect blocks)
*/

NLM_EXTERN FloatHi PNTR LIBCALL SeqAlignWindowScoreFN(SeqAlignPtr align, BioseqPtr bsp1, BioseqPtr bsp2,Int4 win_size, Int4 win_offset,Int4 win_step,Int4Ptr PNTR matrix,Int4 match, Int4 g_open, Int4 g_ext, Int4Ptr nwin,Int4Ptr perfect_length,Int4Ptr perfect_position) {
  DenseSegPtr dsp;
  Int4 lcl_nwin;
  Int4 start_1, start_2,offset_1, offset_2;
  SeqPortPtr spp_1,spp_2;
  Boolean is_gap,FirstBase;
  Int4 a_len,b_len;
  Int4 i, j,len,pos,last_pos,last_start,i_win,win_end;
  Int4 gap_num=0,N_prev_gaps;
  Int4 score,win_score,gap_score;
  FloatHiPtr score_vector=NULL;
  Int4Ptr residue_score=NULL,qgaps_score=NULL;
  Int4Ptr gbl_score;
  Int4 perfect_len, perfect_pos,perfect=0;

  Uint1Ptr strand;
  Int4 a_order,b_order;
  Uint1 code1,code2;
  Uint1 res_1, res_2;

  if(align==NULL || align->segs==NULL) {
      return NULL;
  }
  if(align->segtype !=2 ) {
      ErrPostEx(SEV_ERROR,0,0,"SeqAlignWindowScore: unsupported SeqAlign Type %d\n",align->segtype);
      return NULL;
  }
  if(g_open<0 || g_ext<0) { /* are positive "penalties" */
      ErrPostEx(SEV_WARNING,0,0,"SeqAlignWindowScore: Gap penalties must be positive\n");
      return NULL;
  }
  if(!bsp1 || !bsp2) {
      if(!bsp1)
          ErrPostEx(SEV_WARNING,0,0,"SeqAlignWindowFN: Query Bioseq is NULL! Not allowed\n");
      if(!bsp2)
          ErrPostEx(SEV_WARNING,0,0,"SeqAlignWindowFN: Subject Bioseq is NULL! Not allowed\n");
      return NULL;
  }
  
  if((bsp1->mol == Seq_mol_aa))
      code1 = Seq_code_ncbieaa;
  else
      code1 = Seq_code_ncbi4na;
  if((bsp2->mol == Seq_mol_aa))
      code2 = Seq_code_ncbieaa;
  else
      code2 = Seq_code_ncbi4na;

  if(win_step<=0)
      win_step=1;
  
  a_len = bsp1->length;
  b_len = bsp2->length;
  
  if(win_offset>=a_len)
      return NULL;
  lcl_nwin = (a_len-win_offset+1-win_size)/win_step;
  if(lcl_nwin*win_step+win_size-1<a_len)
      lcl_nwin++;
  /* Keep best Global scores for windows.. for separate SeqAligns */
  
  gbl_score = (Int4Ptr) Malloc((lcl_nwin+1)*sizeof(Int4));
  residue_score = (Int4Ptr) Malloc((a_len+1)*sizeof(Int4));
  /* To deal with gap_extensions in the subject sequence .. */
  qgaps_score = (Int4Ptr) Malloc((a_len+1)*sizeof(Int4)); 
  for(i=0;i<lcl_nwin;i++)
      gbl_score[i]=INT4_MIN;

  perfect_len=0;
  perfect_pos=-1;

  if (align!=NULL) {
      for(i=0;i<a_len;i++) {
          residue_score[i]=INT4_MIN;
          qgaps_score[i]=0;
      }
      SeqAlignBioseqsOrder(align,bsp1,bsp2 ,&a_order, &b_order);
      if(align->segtype==2) {
          dsp=(DenseSegPtr) align->segs;
          strand = dsp->strands;          
          spp_1 = SeqPortNew(bsp1, 0, -1, strand==NULL ? ((Uint1) 0) : strand[a_order], code1);
          spp_2 = SeqPortNew(bsp2, 0, -1, strand==NULL ? ((Uint1)0) : strand[b_order], code2);
          last_pos = 0;
          perfect=0;
          for(i =0; i<dsp->numseg; ++i) {
              Int4 ipos,jpos;
              ipos = 2*i+a_order;
              jpos = 2*i+b_order;
              start_1 = dsp->starts[ipos];
              start_2 = dsp->starts[jpos];
              is_gap = ((start_1 == -1 ) || (start_2 == -1));
              len = dsp->lens[i];
              if(start_1!=-1) {
                  if(strand && strand[ipos] == Seq_strand_minus) {
                      offset_1 = a_len - (start_1+len);
                  } else {
                      offset_1 = start_1;
                  }
                  SeqPortSeek(spp_1, offset_1, SEEK_SET);
              }
              if(start_2 !=-1) {
                  if(strand && strand[jpos] == Seq_strand_minus) {
                      offset_2 = b_len - (start_2+len);
                  } else {
                      offset_2 = start_2;
                  }
                  SeqPortSeek(spp_2, offset_2, SEEK_SET);
              }
              if(is_gap){
                  if(start_1 == -1) {
                      res_1='-';
                      for(j=0;j<len;j++) {
                          res_2 =  SeqPortGetResidue(spp_2);
                      }
                      qgaps_score[last_pos]=-(g_open+len*g_ext);
                  } else { /* if(start_2 == -1) */
                      res_2= '-';
                      for(j=0;j<len;j++) {
                          res_1 =  SeqPortGetResidue(spp_1);
                          pos = start_1+j;
                          residue_score[pos] = INT4_MIN/2;
                      }
                  }
                  ++gap_num;
              } else { /* no gaps */
                  perfect=0;
                  for(j =0,pos=start_1; j<len; ++j,pos++) {
                      res_1 = SeqPortGetResidue(spp_1);
                      res_2 = SeqPortGetResidue(spp_2);
                      if(matrix)
                          score = matrix[res_1][res_2];
                      if(residue_score[pos]==INT4_MIN) {
                          residue_score[pos]=score;
                      } else {
                          ErrPostEx(SEV_ERROR,0,0,"Invalid non-local Seq-Align cannot be used with this routine\n");
                          Free(qgaps_score);
                          Free(residue_score);
                          Free(gbl_score);
                          return NULL;
                      }
                      if(res_1==res_2) {
                          perfect++;
                      } else {
                          if(perfect && perfect>perfect_len) {
                              perfect_len = perfect;
                              perfect_pos = start_1+j-perfect;
                          }
                          perfect=0;
                      }
                  }
                  pos=start_1+len-1;
                  if(perfect && perfect>perfect_len) {
                      perfect_len = perfect;
                      perfect_pos = pos-perfect+1;
                  }
              }
              last_pos = pos;
          }
          if(matrix) {
              last_start = a_len-win_size+win_step;
              /* Allow last window to be partial to allow complete coverage of query */
              for(i=win_offset;i<last_start ;i+=win_step) {
                  i_win = (i-win_offset)/win_step;
                  win_end = i+win_size;
                  if(win_end>a_len)
                      win_end=a_len;
                  FirstBase = FALSE;
                  N_prev_gaps = 0;
                  win_score =0;
                  for(j=i;j<win_end;j++) {
                      score = residue_score[j];
                      if(score==(INT4_MIN/2)) { /* gaps */
                          if(FirstBase) {
                              if(N_prev_gaps==0) /* Internal gap */
                                  win_score-=g_open;
                              win_score-=g_ext;
                              N_prev_gaps++;
                          }
                      } else if(score==INT4_MIN){ /* no Hit on that base */
                          /***commented out by UP
                            if(N_prev_gaps>0)  Internal Hole 
                            win_score += (g_open+N_prev_gaps*g_ext); 
                            ***/
                          N_prev_gaps=0;
                          FirstBase=FALSE;
                      } else {
                          N_prev_gaps=0;
                          FirstBase=TRUE;
                          win_score+=score;
                          /* gaps in query .. not allowed on ends. */
                          if((j<(win_end-1)) && residue_score[j+1]>INT4_MIN/2) {
                              gap_score = qgaps_score[j];
                              win_score += gap_score;
                          }
                      }
                  }
                  if(N_prev_gaps>0) /* reject end gaps */
                      win_score +=(g_open+N_prev_gaps*g_ext);
                  
                  if(win_score>gbl_score[i_win]) /* Keep Best Score */
                      gbl_score[i_win]=win_score;
              }
          }
          SeqPortFree(spp_1);
          SeqPortFree(spp_2);
      }
      /*       align = align->next; */
  }
  if(nwin)
      *nwin = lcl_nwin;
  if(perfect_position)
      *perfect_position = perfect_pos;
  if(perfect_length)
      *perfect_length = perfect_len;
  Free(qgaps_score);
  Free(residue_score);
  if(matrix) {
      score_vector = (FloatHiPtr) Malloc(lcl_nwin*sizeof(FloatHi));
      for(i=0;i<lcl_nwin;i++) {
          score_vector[i]=gbl_score[i];
      }
  }
  Free(gbl_score);
  return score_vector;
}

/* Returns a vector of FloatHi scores
   corresponding to windows on the sequences.
   The Scores are a match/mismatch system 
   also returns the length and the position of the first longest block
   of perfect identity
*/
NLM_EXTERN FloatHi PNTR LIBCALL SeqAlignWindowScore(SeqAlignPtr align, BioseqPtr bsp1, BioseqPtr bsp2,Int4 win_size, Int4 win_offset,Int4 win_step, Int4Ptr PNTR matrix, Int4 match, Int4 mismatch, Int4 g_open, Int4 g_ext, Int4Ptr nwin,Int4Ptr perfect_length,Int4Ptr perfect_position) {
    Boolean na1,na2;
    BioseqPtr bsp_1,bsp_2;
    Int4Ptr PNTR this_matrix=NULL;
    FloatHiPtr scoreptr;
    
    if(align==NULL)
        return NULL;
    if(bsp1) {
        bsp_1 = bsp1;
    } else {
        SeqIdPtr sip ;
        sip = SeqIdPtrFromSeqAlign(align);
        if(sip) {
            bsp_1 = BioseqLockById(sip);
        } else {
            ErrPostEx(SEV_WARNING,0,0,"Could not lock query Bioseq by ID from SeqAlign\n");
            return NULL;
        }
    }
    if(bsp_1) {
        na1 = ISA_na(bsp_1->mol);
    } else {
        ErrPostEx(SEV_WARNING,0,0,"NULL Bioseq\n");
        return NULL;
    }
    if(bsp2) {
        bsp_2 = bsp2;
    } else {
        SeqIdPtr sip ;
        sip = SeqIdPtrFromSeqAlign(align);
        if(sip && sip->next) {
            bsp_2 = BioseqLockById(sip);
        } else {
            ErrPostEx(SEV_WARNING,0,0,"Could not lock subject Bioseq by ID from SeqAlign\n");
            return NULL;
        }
    }
    if(bsp_2) {
        na2 = ISA_na(bsp_2->mol);
    } else {
        ErrPostEx(SEV_WARNING,0,0,"NULL Bioseq\n");
        return NULL;
    }
    if(na1 && na2) {/* blastn or tblastx*/
        /* XXX I'm not sure how to score tblastx alignments.. for
           for now assume it's the same as dna alignments */
        if(matrix==NULL)
            this_matrix = DNAScoringMatrix(mismatch, match,16);
        else
            this_matrix=matrix;
    } else if (!na1 && !na2) {/* blastp */
        if(matrix==NULL) {
            ErrPostEx(SEV_WARNING,0,0,"SeqAlignWindowScore: Protein Alignment Stats requires Matrix for Seq_code_ncbieaa\n");
        } else
            this_matrix=matrix;
    } else if (na1 && !na2) { /* blastx */
        if(matrix==NULL) {
            ErrPostEx(SEV_WARNING,0,0,"blastx Matrix Creation not implemented\n");
        } else
            this_matrix=matrix;
    } else { /* tblastn */
        if(matrix==NULL) {
            ErrPostEx(SEV_WARNING,0,0,"tblastn Matrix Creation not implemented\n");
        } else
            this_matrix=matrix;
    }
    if(this_matrix!=NULL) {
        scoreptr = SeqAlignWindowScoreFN(align, bsp_1, bsp_2, win_size,win_offset,win_step,this_matrix,match,g_open, g_ext, nwin,perfect_length,perfect_position);
        if(matrix==NULL)
            Free(this_matrix);
    }
    if(!bsp1)
        BioseqUnlock(bsp_1);
    if(!bsp2)
        BioseqUnlock(bsp_2);
    return scoreptr;
}



/* Take a blast-style Linked list of SeqAlign and Make a Linked
   list of SeqAlignSets(type 5) .. where each Node is the start of an
   "orthogonal" SeqAlign Linked list of seqaligns referring to the same
   SeqId pairs.
   */

NLM_EXTERN SeqAlignPtr LIBCALL SeqAlignSameIdMerge(SeqAlignPtr salp) {
    SeqAlignPtr seqalign=NULL;
    SeqAlignPtr salpnext,salp_prev;
    SeqIdPtr sip,sipnext;
    Int4 n_salp;
    Uint1 sameq,sames;
    if(!salp)
        return NULL;
    salpnext= salp->next;
    salp->next=NULL;
    if(salpnext==NULL)
        return salp;
    while(salpnext!=NULL) {
        n_salp=0;
        sip =SeqIdPtrFromSeqAlign(salp);
        sipnext = SeqIdPtrFromSeqAlign(salpnext);
        sameq = SeqIdComp(sip,sipnext);

        while(sameq==SIC_YES && salp!=NULL) {
            SeqAlignPtr head=salp;
            SeqAlignPtr prev=salp;

            sames = SeqIdComp(sip->next,sipnext->next);
            while(sameq==SIC_YES && sames==SIC_YES && salpnext!=NULL) {
                n_salp++;
                prev->next = salpnext;
                prev = salpnext;
                salpnext=salpnext->next;
                prev->next=NULL;
                if(salpnext!=NULL) {
                    sipnext = SeqIdPtrFromSeqAlign(salpnext);
                    sameq = SeqIdComp(sip,sipnext);
                    sames = SeqIdComp(sip->next,sipnext->next);
                } else {
                    sameq=SIC_DIFF; 
                    sames=SIC_DIFF;
                }
            }
            if(seqalign==NULL) {
                    seqalign=SeqAlignNew();
                    seqalign->segtype = 5;
                    seqalign->segs = head;
                salp_prev = seqalign;
            } else {
                    salp_prev->next = SeqAlignNew();
                    salp_prev->next->segtype=5;
                    salp_prev->next->segs = head;
                salp_prev = salp_prev->next;
            }
            salp=salpnext;
            if(salp) {
                salpnext=salp->next;
                salp->next=NULL;
            } else {
                salpnext=NULL;
            }
            sip =SeqIdPtrFromSeqAlign(salp);
            sipnext = SeqIdPtrFromSeqAlign(salpnext);
            sameq = SeqIdComp(sip,sipnext);
        }
        if(n_salp==0) {
            if(seqalign==NULL) {
                seqalign=SeqAlignNew();
                seqalign->segtype = 5;
                seqalign->segs = salp;
            } else {
                salp_prev->next = SeqAlignNew();
                salp_prev->next->segtype=5;
                salp_prev->next->segs = salp;
            }
        }
    }
    return seqalign;
}

NLM_EXTERN SalpStatsInputBlockPtr LIBCALL SalpStatsInputBlockNew(void) {
    return (SalpStatsInputBlockPtr) MemNew(sizeof(SalpStatsInputBlock));
}
NLM_EXTERN SalpStatsInputBlockPtr LIBCALL SalpStatsInputBlockFree(SalpStatsInputBlockPtr param) {
    return (SalpStatsInputBlockPtr) MemFree(param);
}

NLM_EXTERN SalpStatsResultsPtr LIBCALL SalpStatsResultsNew(void) {
    return (SalpStatsResultsPtr) MemNew(sizeof(SalpStatsResults));
}
NLM_EXTERN SalpStatsResultsPtr LIBCALL SalpStatsResultsFree(SalpStatsResultsPtr results) {
    if(!results)
        return NULL;
    if(results->gaplengths)
        Free(results->gaplengths);
    if(results->query_sip)
	SeqIdFree(results->query_sip);
    if(results->subject_sip)
        SeqIdFree(results->subject_sip);
    Free(results);
    return (SalpStatsResultsPtr) NULL;
}


NLM_EXTERN SalpStatsResultsPtr LIBCALL SeqAlignStats(SeqAlignPtr salp_in, SalpStatsInputBlockPtr param,BioseqPtr query_bsp,BioseqPtr subject_bsp) {
    Boolean Duplicated=FALSE;
    SeqAlignPtr salp=NULL,sapnext=NULL;
    SalpStatsResultsPtr results;
    SeqIdPtr sip;
    Int4 a_length;
    Boolean lock_qbsp=FALSE,lock_sbsp=FALSE;

    if(!salp_in || !param)
        return NULL;
    if(salp_in->segtype == 5) {
        salp_in=(SeqAlignPtr) (salp_in->segs);
	 } else {
        sapnext=salp_in->next;
	     salp_in->next=NULL;
    }
    salp = salp_in;
    results = SalpStatsResultsNew();
    sip =SeqIdPtrFromSeqAlign(salp);
    results->query_sip = SeqIdDup(sip);
    if(results->query_sip)
        results->query_sip->next=NULL;
    if(sip && sip->next){
        results->subject_sip = SeqIdDup(sip->next);
        if(results->subject_sip)
	    results->subject_sip->next=NULL;
    }
    if(!query_bsp && results->query_sip) {
        lock_qbsp=TRUE;
        query_bsp = BioseqLockById(sip);
    }
    if(query_bsp==NULL) {
        ErrPostEx(SEV_WARNING,0,0,"Could not Lock query Bioseq\n");
         
	 } else {
        results->inputqlength=query_bsp->length;
    }
        
    if(!subject_bsp && results->subject_sip) {
        lock_sbsp=TRUE;
        subject_bsp = BioseqLockById(results->subject_sip);
    }
    if(subject_bsp==NULL) {
        ErrPostEx(SEV_WARNING,0,0,"Could not Lock query Bioseq\n");
    } else {
        results->inputslength=subject_bsp->length;
    }
    SeqAlignListStartStop(&(results->qbegmatch),&(results->qendmatch),&(results->sbegmatch),&(results->sendmatch),salp, query_bsp,subject_bsp);
    
    if(param->Mismatch) {
        SeqAlignListCountMismatches(salp,query_bsp, 
		     subject_bsp,
		     &(a_length), &(results->identities),
		     &(results->mismatches), &(results->partial_matches),&(results->gapcount));
    }
    if(param->GapList) {
        results->gaplengths = SeqAlignListGapList(salp,&(results->gapcount));
    }
    if(param->LongestPerfect || param->WorstWindow) {
        FloatHiPtr windows;
        FloatHi worst;
        Int4 nwin,i;
        windows= SeqAlignWindowScore(salp, query_bsp,subject_bsp,param->window_size,0,1, NULL, 1,/* match */
				-3,/* mismatch */
				  5,2 /* gap opening, gap extension penalties */
					, &nwin,param->LongestPerfect ? &(results->longest_perfect) : NULL,NULL);
        if(param->WorstWindow) {
            if(windows && nwin) {
                worst=windows[0];
                for(i=1;i<nwin;i++) {
                    if(worst>windows[i])
                        worst = windows[i];
                }
                results->worst_window = (Int4)worst;
            } else {
                results->worst_window = INT_MIN;
            }
        }
        Free(windows);
    }
    if(param->BlastScores) {
        SeqAlignScoreRead(salp,&(results->score),&(results->bit_score),&(results->E_value));
    }
    
    results->q_possibleOverlap = SeqAlignOverlapLen(salp,query_bsp,subject_bsp);
    results->s_possibleOverlap =    results->q_possibleOverlap;
    if(query_bsp->mol ==Seq_mol_aa)
            results->sub_reversed_strand = FALSE;
    else {
        Uint1 strand1,strand2;
        strand1 = SeqAlignStrand(salp,0);
        strand2 = SeqAlignStrand(salp,1);
        results->sub_reversed_strand = ((strand1==Seq_strand_minus && strand2!=strand1) || (strand2==Seq_strand_minus && strand2!=strand1));
    }

    if(lock_qbsp)
        BioseqUnlock(query_bsp);
    if(lock_sbsp)
        BioseqUnlock(subject_bsp);
    if(Duplicated)
        salp=SeqAlignSetFree(salp);
    if(sapnext) {/* Relink */
       salp_in->next = sapnext;
    }
    return results;
}

/*
  Find Pairwise Statistics for a linked list of SeqAlign.
  Consider that the linked list represents a Global Alignment..
  and choose the best set of segments that is consistent
  with this. See SeqAlignStats for options.
 */

NLM_EXTERN SalpStatsResultsPtr LIBCALL SeqAlignListGlobalStats(SeqAlignPtr salp_in, SalpStatsInputBlockPtr param,BioseqPtr query_bsp,BioseqPtr subject_bsp) {
    SalpStatsResultsPtr ssrp;
    SeqAlignPtr salp;
    Boolean Duplicated=FALSE;
    if(!salp_in)
        return NULL;
    salp=salp_in;
    if(salp->next!=NULL) {
        SeqAlignPtr salp_leftover;
        Duplicated=TRUE;
        salp = SeqAlignDup(salp_in);
        if(param->MergeConsistentAlign) {
            salp = SeqAlignNonRedundant(salp,query_bsp,subject_bsp,&salp_leftover);
        } else {
            salp = SeqAlignNonOverlap(salp,query_bsp,subject_bsp,&salp_leftover,1);
        }
        SeqAlignSetFree(salp_leftover);
    }
    ssrp = SeqAlignStats(salp, param,query_bsp,subject_bsp);
    if(Duplicated)
        salp=SeqAlignSetFree(salp);
    return ssrp;
}

/* 
   SeqAlignGapCount: Count Gaps in a SeqAlign
 */
NLM_EXTERN Int4 LIBCALL SeqAlignGapCount (SeqAlignPtr salp)
{
  DenseSegPtr   dsp;
  Int4          sum,
                j;
  Int2          k;

  if (salp == NULL)
     return 0;
  if (salp->segtype != 2)
     return 0;
  sum=0;
  if (salp->segtype == 2)
  {
     dsp = (DenseSegPtr) salp->segs;
     if (dsp!=NULL)
     {
        for (j=0; j<dsp->numseg; j++)
           for (k=0; k<dsp->dim; k++)
           {
              if (dsp->starts[(dsp->dim*j)+k] < 0)
                 sum+= dsp->lens[j];
           }
     }
  }
  return sum;
}


/*
  Keep All SeqAligns that provide some new coverage
  new coverage is defined as.. contributing to the coverage of the
    first "Coverage" covering of the SeqAlign.

    Coverage==1: Means any alignment that contributes at least one new base coverage.

  when the SeqAligns are considered in the input Order. 
  (might want to sort by score or length before input)

  The rejected SeqAligns are returned.

  Consider that a Gap aligned to the query is "informative"
  
  If HitsPerBase !=NULL, 
  it returns the cumulative coverage upon exit.
  if *HitsPerBase !=NULL it takesthis as input for the already existing
  coverage.. So can call the routine with Different list of SeqAligns.

  if passing pointer last_a_start and last_a_stop.. first time around they
  must be initialized to *last_a_start == INT4_MAX and *last_a_stop =-1

   */

NLM_EXTERN SeqAlignPtr LIBCALL SeqAlignFilterByCoverage(SeqAlignPtr salp,BioseqPtr query_bsp,SeqAlignPtr PNTR salp_leftover_ptr,Int4 Coverage,Uint2Ptr PNTR HitsPerBase,Int4Ptr last_a_start,Int4Ptr last_a_stop) {
    SeqAlignPtr salptmp;
    Uint2Ptr HitsPerQBase;
    Uint1Ptr AcceptList;
    Int4 i,j,k,l;
    Int4 qpos,spos,qend_pos,send_pos;
    Int4 a_start,a_stop;
    DenseSegPtr dsp;
    DenseDiagPtr ddp;
    SeqAlignPtr align,new_salp,salp_leftover=NULL;
    SeqAlignPtr salp_left_tmp=NULL;
    SeqAlignPtr PNTR salp_list;

    Int4 a_order,b_order;

    Int4 ipos,n_sap;

    if (salp == NULL)
        return salp;
    if(Coverage>65535)
        Coverage = 65535;
    
    if(last_a_start!=NULL && *last_a_start != INT4_MAX)
        a_start = *last_a_start;
    else
        a_start = INT4_MAX;
    if(last_a_stop!=NULL && *last_a_stop >=0)
        a_stop = *last_a_stop;
    else
        a_stop=-1;
    for (n_sap=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next) {
        Int4 lcl_a_start,lcl_a_stop,lcl_b_start,lcl_b_stop;
        n_sap++;
        if(SeqAlignStartStop(&lcl_a_start, &lcl_a_stop, &lcl_b_start, &lcl_b_stop,
                             salptmp, query_bsp, NULL)) {
            if(lcl_a_start!=-1 && lcl_a_start<a_start)
                a_start=lcl_a_start;
            if(lcl_a_stop>a_stop)
                a_stop=lcl_a_stop;
        }
    }

    salp_list=(SeqAlignPtr PNTR) Malloc((size_t)((n_sap+1)*(sizeof(salp_list[0]))));
    for (j=0,salptmp=salp; salptmp!=NULL; salptmp=salptmp->next,j++) {
        salp_list[j]=salptmp;
    }
    for (j=0; j<n_sap; j++) {
        salp_list[j]->next=NULL;
    }
    
    if(HitsPerBase!=NULL && *HitsPerBase!=NULL) {
        HitsPerQBase = *HitsPerBase;
        if(last_a_start!=NULL || last_a_stop!=NULL) {
            Int4 start_extra=0,stop_extra=0,extra=0;
            if(last_a_start!=NULL && *last_a_start>a_start)
                start_extra = *last_a_start-a_start;
            if(last_a_stop!=NULL && *last_a_stop<a_stop)
                stop_extra = a_stop-*last_a_stop;
            extra = start_extra+stop_extra;
            if(extra) {
                HitsPerQBase = Realloc(HitsPerQBase,(a_stop-a_start+2)*sizeof(Uint2));
                memmove(HitsPerQBase+start_extra,HitsPerQBase,(a_stop-a_start-extra+1)*sizeof(Uint2));
                memset(HitsPerQBase,0,start_extra*sizeof(Uint2));
                memset(HitsPerQBase+a_stop-a_start-stop_extra+1,0,(stop_extra+1)*sizeof(Uint2));
                *HitsPerBase = HitsPerQBase;
                if(last_a_start!=NULL)
                    *last_a_start = a_start;
                if(last_a_stop!=NULL)
                    *last_a_stop = a_stop;
            }
        }
    } else {
        HitsPerQBase = (Uint2Ptr) Calloc(a_stop-a_start+2,sizeof(Uint2));
        if(HitsPerBase)
            *HitsPerBase = HitsPerQBase;
        if(last_a_start!=NULL)
            *last_a_start=a_start;

        if(last_a_stop!=NULL)
            *last_a_stop=a_stop;
    }
    AcceptList = (Uint1Ptr) Calloc(n_sap+1,sizeof(Uint1));

    /* Loop over length-ordered Alignments: Keep Best Non-overlappping regions
       
     */
    for(i=0;i<n_sap;i++) {
        align=salp_list[i];
        if(align!=NULL) {
            SeqAlignBioseqsOrder(align,query_bsp,NULL,&a_order,&b_order);
            if(align->segtype==1) {
                ddp = (DenseDiagPtr) (align->segs);
                AcceptList[i]=0;
                while(ddp!=NULL && AcceptList[i]==0) {
                    qpos=ddp->starts[a_order];
                    spos=ddp->starts[b_order];
                    qend_pos=qpos+ddp->len;
                    send_pos=spos+ddp->len;
                    if(qpos!=-1) {
                        for(k=qpos,l=spos;k<qend_pos && l<send_pos;k++,l++) {
                            if(HitsPerQBase[k-a_start]<Coverage) {
                                AcceptList[i]=1;
                                qpos+=qend_pos;
                            }
                        }
                    }
                    ddp = ddp->next;
                }
            } else if(align->segtype==2) {
                dsp = (DenseSegPtr) align->segs;
                if(dsp!=NULL) {
                    AcceptList[i]=0;
                    for(j = 0; j<dsp->numseg; ++j) {
                        ipos = 2*j + a_order;
                        qpos=dsp->starts[ipos];
                        qend_pos=qpos+dsp->lens[j];
                        {
                            if(qpos!=-1) {
                                for(k=qpos;k<qend_pos;k++) {
                                    if((HitsPerQBase[k-a_start]<Coverage)) {
                                        AcceptList[i]=1;
                                        k+=qend_pos; 
                                        j+=dsp->numseg;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            /* If we've accepted the new segment(s), 
            */
            if(AcceptList[i]==1) {/* increment B-value counter for bases */
                if(align->segtype==1) {
                    ddp=(DenseDiagPtr)align->segs;
                    while(ddp!=NULL) {
                        qpos=ddp->starts[a_order];
                        qend_pos=qpos+ddp->len;
                        if(qpos!=-1) {
                            for(k=qpos;k<qend_pos;k++) {
                                if(HitsPerQBase[k-a_start]<65535)
                                    HitsPerQBase[k-a_start]+=1;
                            }
                        }
                        ddp = ddp->next;
                    }
                } else if(align->segtype==2) {
                    dsp = (DenseSegPtr) align->segs;
                    if(dsp!=NULL) {
                        for(j = 0; j<dsp->numseg; ++j) {
                            ipos = 2*j + a_order;
                            qpos=dsp->starts[ipos];
                            qend_pos=qpos+dsp->lens[j];
                            if(qpos!=-1) {
                                for(k=qpos;k<qend_pos;k++) {
                                    if(HitsPerQBase[k-a_start]<65535)
                                       HitsPerQBase[k-a_start]+=1;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /* Shift down list */
    salp=new_salp=NULL;
    for(i=0;i<n_sap;i++) {
        salptmp=salp_list[i];
        if (salptmp==NULL)
            break;
        if(AcceptList[i]==0) {
            if(salp_leftover_ptr) {
                if(salp_leftover) {
                    salp_left_tmp->next=salptmp;
                } else {
                    salp_leftover=salptmp;
                }
                salp_left_tmp=salptmp;
            } else {
                salptmp->next=NULL;
                salp_list[i] = SeqAlignFree (salptmp);
            }
        } else {
            if(salp)
                salp->next=salptmp;
            else {
                salp=salptmp;
                new_salp=salp;
            }
            salp=salptmp;
        }
    }
    if(salp)
        salp->next=NULL;
    if(salp_left_tmp) 
        salp_left_tmp->next=NULL;
    if(salp_leftover_ptr)
        *salp_leftover_ptr=salp_leftover;
    Free(AcceptList);
    if(!HitsPerBase)
        Free(HitsPerQBase);
    Free(salp_list);
    return new_salp;
}