File: embest.c

package info (click to toggle)
emboss 6.6.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 571,248 kB
  • ctags: 39,971
  • sloc: ansic: 460,578; java: 29,439; perl: 13,573; sh: 12,740; makefile: 3,275; csh: 706; asm: 351; xml: 239; pascal: 237; modula3: 8
file content (2496 lines) | stat: -rw-r--r-- 58,872 bytes parent folder | download | duplicates (7)
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
/* @source embest *************************************************************
**
** NUCLEUS EST alignment functions
**
** @author Copyright (C) 1996 Richard Mott
** @author Copyright (C) 1998 Peter Rice revised for EMBOSS
** @version $Revision: 1.32 $
** @@
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA  02110-1301,  USA.
**
******************************************************************************/

/* ==================================================================== */
/* ========================== include files =========================== */
/* ==================================================================== */

#include "ajlib.h"

#include "embest.h"
#include "ajsys.h"
#include "ajseq.h"

#include <time.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>


/* @datastatic EstPKeyValue ***************************************************
**
** Key value data structure
**
** @alias EstSKeyValue
** @alias EstOKeyValue
**
** @attr key [float] key score
** @attr value [ajint] value
** @@
******************************************************************************/

typedef struct EstSKeyValue
{
    float key;
    ajint value;
} EstOKeyValue;

#define EstPKeyValue EstOKeyValue*




/* @datastatic EstPCoord ******************************************************
**
** Coordinates data structure
**
** @alias EstSCoord
** @alias EstOCoord
**
** @attr left [ajint] left end
** @attr right [ajint] right end 
** @@
******************************************************************************/

typedef struct EstSCoord
{
    ajint left;
    ajint right;
} EstOCoord;

#define EstPCoord EstOCoord*




/* @datastatic EstPSavePair ***************************************************
**
** Save pairwise matches
**
** @alias EstSSavePair
** @alias EstOSavePair
**
** @attr col [ajint] Column number
** @attr row [ajint] Row number
** @@
******************************************************************************/

typedef struct EstSSavePair
{
    ajint col;
    ajint row;
} EstOSavePair;
#define EstPSavePair EstOSavePair*


static EstPSavePair rpair  = NULL;
static ajint rpairs        = 0;
static ajint rpair_size    = 0;
static ajint rpairs_sorted = 0;

static ajint lsimmat[256][256];
static AjBool verbose;
static AjBool debug;
static float estRand3(ajint *idum);
static ajint estPairRemember(ajint col, ajint row);
static ajint estSavePairCmp(const void *a, const void *b);
static void  estPairInit(ajint max_bytes);
static void  estPairFree(void);
static ajint estDoNotForget(ajint col, ajint row);
static ajint estAlignMidpt(const AjPSeq est, const AjPSeq genome,
			   ajint gap_penalty, ajint intron_penalty,
			    ajint splice_penalty,
			    const AjPSeq splice_sites,
			    ajint middle, ajint *gleft, ajint *gright);

static EmbPEstAlign estAlignRecursive(const AjPSeq est, const AjPSeq genome,
				      ajint match, ajint mismatch,
				      ajint gap_penalty, ajint intron_penalty,
				      ajint splice_penalty,
				      const AjPSeq splice_sites,
				      float max_area);

static void  estWriteMsp(AjPFile ofile, ajint *matches,
			 ajint *len, ajint *tsub,
			 const AjPSeq genome, ajint gsub, ajint gpos,
			 const AjPSeq est,
			 ajint esub, ajint epos, ajint reverse, ajint gapped);

static const char* estShuffleSeq(char *s, ajint *seed);




/* @func embEstSetDebug *******************************************************
**
** Sets debugging calls on
**
** @return [void]
**
** @release 1.13.0
******************************************************************************/

void embEstSetDebug(void)
{
    debug = ajTrue;

    return;
}




/* @func embEstSetVerbose *****************************************************
**
** Sets verbose debugging calls on
**
** @return [void]
**
** @release 1.13.0
******************************************************************************/

void embEstSetVerbose(void)
{
    verbose = ajTrue;

    return;
}




/* @func  embEstGetSeed *******************************************************
**
** Returns a seed for the random number generator, using the system clock.
**
** @return [ajint] seed.
**
** @release 1.13.0
** @@
******************************************************************************/

ajint embEstGetSeed(void)
{
    time_t *tloc;
    ajint seed;

    tloc = NULL;

    seed = ((ajint)time(tloc))% 100000;

    ajDebug("! seed = %d\n", seed);

    return seed;
}




/* @func embEstMatInit ********************************************************
**
** Comparison matrix initialisation.
**
** @param [r] match [ajint] Match code
** @param [r] mismatch [ajint] Mismatch penalty
** @param [r] gap [ajint] Gap penalty
** @param [r] neutral [ajint] Score for ambiguous base positions.
** @param [r] pad_char [char] Pad character for gaps in input sequences
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

void embEstMatInit(ajint match, ajint mismatch, ajint gap,
		   ajint neutral, char pad_char)
{
    ajint c1;
    ajint c2;

    for(c1=0;c1<256;c1++)
	for(c2=0;c2<256;c2++)
	{
	    if( c1 == c2 )
	    {
		if( c1 != '*' && c1 != 'n' &&  c1 != 'N' && c1 != '-' )
		    lsimmat[c1][c2] = match;
		else
		    lsimmat[c1][c2] = 0;
	    }
	    else
	    {
		if( c1 == pad_char || c2 == pad_char )
		    lsimmat[c1][c2] = lsimmat[c2][c1] = -gap;
		else if( c1 == 'n' || c2 == 'n' || c1 == 'N' || c2 == 'N' )
		    lsimmat[c1][c2] = lsimmat[c2][c1] = neutral;
		else
		    lsimmat[c1][c2] = lsimmat[c2][c1] = -mismatch;
	    }
	}

    for(c1=0;c1<256;c1++)
    {
	c2 = tolower(c1);
	lsimmat[c1][c2] = lsimmat[c1][c1];
	lsimmat[c2][c1] = lsimmat[c1][c1];
    }

    return;
}




/* @func embEstFindSpliceSites ************************************************
**
** Finds all putative DONOR and ACCEPTOR splice sites in the genomic sequence.
**
** Returns a sequence object whose "dna" should be interpreted as an
** array indicating what kind (if any) of splice site can be found at
** each sequence position.
**
**     DONOR    sites are NNGTNN last position in exon
**
**     ACCEPTOR sites are NAGN last position in intron
**
**     if forward==1 then search fot GT/AG
**     else               search for CT/AC
**
** @param [r] genome [const AjPSeq] Genomic sequence
** @param [r] forward [ajint] Boolean. 1 = forward direction
**
** @return [AjPSeq] Sequence of bitmask codes for splice sites.
**
** @release 1.13.0
** @@
******************************************************************************/

AjPSeq embEstFindSpliceSites(const AjPSeq genome, ajint forward )
{
    AjPSeq sites;
    ajint pos;
    ajint genomelen;
    const char *s;
    char *sitestr;

    sites     = ajSeqNew();
    genomelen = ajSeqGetLen(genome);
    s         = ajSeqGetSeqC(genome);
    sitestr   = ajSeqGetSeqCopyC( genome );


    for(pos=0;pos<genomelen;pos++)
	sitestr[pos] = NOT_A_SITE;

    if( forward )
    {
	/* gene is in forward direction -splice consensus is gt/ag */
	for(pos=1;pos<genomelen-2;pos++)
	{
	    /* last position in exon */
	    if( tolower((ajint) s[pos]) == 'g' &&
	       tolower((ajint) s[pos+1]) == 't' ) /* donor */
		sitestr[pos-1] = ajSysCastItoc((ajuint) sitestr[pos-1] |
					   (ajuint) DONOR);

	    /* last position in intron */
	    if( tolower((ajint) s[pos]) == 'a' &&
	       tolower((ajint) s[pos+1]) == 'g' ) /* acceptor */
		sitestr[pos+1]  = ajSysCastItoc((ajuint) sitestr[pos+1] |
					    (ajuint) ACCEPTOR);
	}

	ajSeqAssignNameC(sites, "forward"); /* so that other functions know */
    }
    else
    {
	/* gene is on reverse strand so splice consensus looks like ct/ac */
	for(pos=1;pos<genomelen-2;pos++)
	{
	    /* last position in exon */
	    if( tolower((ajint) s[pos]) == 'c' &&
	       tolower((ajint) s[pos+1]) == 't' ) /* donor */
		sitestr[pos-1] = ajSysCastItoc((ajuint) sitestr[pos-1] |
					   (ajuint) DONOR);

	    /* last position in intron */
	    if( tolower((ajint) s[pos]) == 'a' &&
	       tolower((ajint) s[pos+1]) == 'c' ) /* acceptor */
		sitestr[pos+1] = ajSysCastItoc((ajuint) sitestr[pos+1] |
					   (ajuint) ACCEPTOR);
	}

	ajSeqAssignNameC(sites,"reverse");  /* so that other functions know */
    }

    ajSeqAssignSeqC(sites, sitestr);
    AJFREE(sitestr);

    return sites;
}




/* @func embEstShuffleSeq *****************************************************
**
** Shuffle the sequence.
**
** @param [u] seq [AjPSeq] Original sequence
** @param [r] in_place [ajint] Boolean 1=shuffle in place
** @param [u] seed [ajint*] Random number seed.
**
** @return [AjPSeq] shuffled sequence.
**
** @release 1.13.0
** @@
******************************************************************************/

AjPSeq embEstShuffleSeq( AjPSeq seq, ajint in_place, ajint *seed )
{
    AjPSeq shuffled;
    AjPStr shufflestr;

    if(!in_place)
	shuffled = ajSeqNewSeq(seq);
    else
	shuffled = seq;

    shufflestr = ajSeqGetSeqCopyS(shuffled);

    estShuffleSeq(ajStrGetuniquePtr(&shufflestr), seed);
    ajSeqAssignSeqS(shuffled, shufflestr);

    return shuffled;
}




/* @funcstatic estShuffleSeq **************************************************
**
** in-place shuffle of a string
**
** @param [u] s [char*] String
** @param [u] seed [ajint*] Seed
**
** @return [const char*] shuffled string.
**
** @release 1.13.0
** @@
******************************************************************************/

static const char* estShuffleSeq( char *s, ajint *seed )
{
    EstPKeyValue tmp;
    ajint n;
    ajint len;

    len = (ajint) strlen(s);

    AJCNEW(tmp, len);

    for(n=0;n<len;n++)
    {
	tmp[n].key = estRand3(seed);
	tmp[n].value = s[n];
    }

    for(n=0;n<len;n++)
	s[n] = ajSysCastItoc(tmp[n].value);

    AJFREE(tmp);

    return s;
}




/* @funcstatic estRand3 *******************************************************
**
** Random number generator.
**
** @param [w] idum [ajint*] Seed
**
** @return [float] Random flaoting point number.
**
** @release 1.13.0
** @@
******************************************************************************/

static float estRand3(ajint *idum)
{
    static ajint inext,inextp;
    static long ma[56];
    static ajint iff = 0;
    long mj;
    long mk;
    ajint i;
    ajint ii;
    ajint k;
    float ZZ;

    static ajint MBIG  = 1000000000;
    static ajint MSEED = 161803398;
    static ajint MZ    = 0;

    ajint FAC;

    FAC = (ajint) (((float)1.0/(float)MBIG));

    if(*idum < 0 || iff == 0)
    {
	iff = 1;
	mj  = MSEED-(*idum < 0 ? -*idum : *idum);
	mj %= MBIG;
	ma[55] = mj;
	mk = 1;

	for(i=1;i<=54;i++)
	{
	    ii = (21*i) % 55;
	    ma[ii] = mk;
	    mk     = mj-mk;

	    if(mk < MZ)
		mk += MBIG;

	    mj = ma[ii];
	}

	for(k=1;k<=4;k++)
	    for(i=1;i<=55;i++)
	    {
		ma[i] -= ma[1+(i+30) % 55];

		if(ma[i] < MZ)
                    ma[i] += MBIG;
	    }

	inext  = 0;
	inextp = 31;
	*idum  = 1;
    }

    if(++inext == 56)
	inext=1;

    if(++inextp == 56)
	inextp=1;

    mj=ma[inext]-ma[inextp];

    if(mj < MZ)
	mj += MBIG;
    ma[inext] = mj;

    ZZ = (float) (mj*FAC);
    ZZ = (ZZ < (float)0.0 ? -ZZ : ZZ );
    ZZ = (ZZ > (float)1.0 ? ZZ-(ajint)ZZ : ZZ);

    return ZZ;
}




/* @func embEstFreeAlign ******************************************************
**
** Free a genomic EST alignment structure
**
** @param [d] ge [EmbPEstAlign*] Genomic EST alignment data structure
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

void embEstFreeAlign(EmbPEstAlign *ge)
{
    if( *ge )
    {
	if( (*ge)->align_path )
	    AJFREE( (*ge)->align_path );

	AJFREE(*ge);
    }

    return;
}




/* @func embEstPrintAlign *****************************************************
**
** Print the alignment
**
** @param [u] ofile [AjPFile] Output file
** @param [r] genome [const AjPSeq] Genomic sequence
** @param [r] est [const AjPSeq] EST sequence
** @param [r] ge [const EmbPEstAlign] Genomic EST alignment
** @param [r] width [ajint] Output width (in bases)
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

void embEstPrintAlign(AjPFile ofile, const AjPSeq genome, const AjPSeq est,
		      const EmbPEstAlign ge, ajint width )
{
    ajint gpos;
    ajint epos;
    ajint pos;
    ajint len;
    ajint i;
    ajint j;
    ajint max;
    ajint m;
    char *gbuf;
    char *ebuf;
    char *sbuf;
    const char *genomeseq;
    const char *estseq;

    ajint *gcoord;
    ajint *ecoord;
    ajint namelen;

    char format[256];


    genomeseq = ajSeqGetSeqC(genome);
    estseq = ajSeqGetSeqC(est);

    namelen = ajStrGetLen(ajSeqGetNameS(genome)) >
        ajStrGetLen(ajSeqGetNameS(est)) ?
	ajStrGetLen(ajSeqGetNameS(genome)) : ajStrGetLen(ajSeqGetNameS(est)) ;


    sprintf(format, "%%%dS %%6d ", namelen );

    if(ofile)
    {
	ajFmtPrintF(ofile, "\n");
	len = ajSeqGetLen(genome) + ajSeqGetLen(est) + 1;

	AJCNEW(gbuf,len);
	AJCNEW(ebuf,len);
	AJCNEW(sbuf,len);

	AJCNEW(gcoord,len);
	AJCNEW(ecoord,len);

	gpos = ge->gstart;
	epos = ge->estart;
	len = 0;

	for(pos=0;pos<ge->len;pos++)
	{
	    ajint way = ge->align_path[pos];

	    if( way == DIAGONAL  )
	    {
		/* diagonal */
		gcoord[len] = gpos;
		ecoord[len] = epos;
		gbuf[len] = genomeseq[gpos++];
		ebuf[len] = estseq[epos++];
		m = lsimmat[(ajint)gbuf[len]][(ajint)ebuf[len]];

		/*
		** MATHOG, the triple form promotes char to
		** arithmetic type, which
		** generates warnings as it might be able
		** to overflow the char type.  This is
		** equivalent but doesn't trigger any compiler noise
		** sbuf[len] = (char) ( m > 0 ? '|' : ' ' );
		*/

		if(m>0)
		    sbuf[len] = '|';
		else
		    sbuf[len] = ' ';

		len++;
	    }
	    else if(way == DELETE_EST)
	    {
		gcoord[len] = gpos;
		ecoord[len] = epos;
		gbuf[len] = '-';
		ebuf[len] = estseq[epos++];
		sbuf[len] = ' ';
		len++;
	    }
	    else if( way == DELETE_GENOME )
	    {
		gcoord[len] = gpos;
		ecoord[len] = epos;
		gbuf[len] = genomeseq[gpos++];
		ebuf[len] = '-';
		sbuf[len] = ' ';
		len++;
	    }
	    else if( way <= INTRON )
	    {
		/*
		** want enough space to print the first 5 and last 5
		** bases of the intron, plus a string containing the
		** intron length
		*/
		ajint intron_width;
		ajint half_width;
		ajint g;
		char number[30];
		ajint numlen;

		intron_width = ge->align_path[pos+1];
		g = gpos-1;
		half_width = intron_width > 10 ? 5 : intron_width/2;


		sprintf(number," %d ", intron_width );
		numlen = (ajint) strlen(number);

		for(j=len;j<len+half_width;j++)
		{
		    g++;
		    gcoord[j] = gpos-1;
		    ecoord[j] = epos-1;
		    gbuf[j] = ajSysCastItoc(tolower((ajint) genomeseq[g]));
		    ebuf[j] = '.';

		    if(way == FORWARD_SPLICED_INTRON)
			sbuf[j] = '>';
		    else if(way == REVERSE_SPLICED_INTRON)
			sbuf[j] = '<';
		    else
			sbuf[j] = '?';
		}

		len = j;

		for(j=len;j<len+numlen;j++)
		{
		    gcoord[j] = gpos-1;
		    ecoord[j] = epos-1;
		    gbuf[j] = '.';
		    ebuf[j] = '.';
		    sbuf[j] = number[j-len];
		}

		len = j;
		g = gpos + intron_width - half_width-1;

		for(j=len;j<len+half_width;j++)
		{
		    g++;
		    gcoord[j] = gpos-1;
		    ecoord[j] = epos-1;
		    gbuf[j] = ajSysCastItoc(tolower((ajint) genomeseq[g]));
		    ebuf[j] = '.';

		    if(way == FORWARD_SPLICED_INTRON)
			sbuf[j] = '>';
		    else if(way == REVERSE_SPLICED_INTRON)
			sbuf[j] = '<';
		    else
			sbuf[j] = '?';
		}

		gpos += ge->align_path[++pos];
		len = j;
	    }
	}

	for(i=0;i<len;i+=width)
	{
	    max = ( i+width > len ? len : i+width );

	    ajFmtPrintF(ofile, format, ajSeqGetNameS(genome), gcoord[i]+1 );

	    for(j=i;j<max;j++)
		ajFmtPrintF(ofile, "%c",  gbuf[j]);

	    ajFmtPrintF(ofile," %6d\n", gcoord[j-1]+1 );

	    for(j=0;j<namelen+8;j++)
		ajFmtPrintF(ofile, " ");

	    for(j=i;j<max;j++)
		ajFmtPrintF(ofile,"%c", sbuf[j]);

	    ajFmtPrintF(ofile,  "\n");
	    ajFmtPrintF(ofile, format, ajSeqGetNameS(est), ecoord[i]+1 );

	    for(j=i;j<max;j++)
		ajFmtPrintF(ofile, "%c", ebuf[j]);

	    ajFmtPrintF(ofile," %6d\n\n", ecoord[j-1]+1 );
	}

	ajFmtPrintF( ofile, "\nAlignment Score: %d\n", ge->score );

	AJFREE(gbuf);
	AJFREE(ebuf);
	AJFREE(sbuf);
	AJFREE(gcoord);
	AJFREE(ecoord);
    }

    return;
}




/* @func embEstAlignNonRecursive **********************************************
**
** Modified Smith-Waterman/Needleman to align an EST or mRNA to a Genomic
** sequence, allowing for introns.
**
** The recursion is
**
**     {  S[gpos-1][epos]   - gap_penalty
**
**     {  S[gpos-1][epos-1] + D[gpos][epos]
**
**     S[gpos][epos] = max {  S[gpos][epos-1]   - gap_penalty
**
**     {  C[epos]           - intron_penalty
**
**     {  0 (optional, only if ! needleman )
**
**     C[epos] = max{ S[gpos][epos], C[epos] }
**
**     S[gpos][epos] is the score of the best path to the cell gpos, epos
**     C[epos] is the score of the best path to the column epos
**
**
** @param [r] est [const AjPSeq] Sequence of EST
** @param [r] genome [const AjPSeq] Sequence of genomic region
** @param [r] gap_penalty [ajint] Gap penalty
** @param [r] intron_penalty [ajint] Intron penalty
** @param [r] splice_penalty [ajint] Splice site penalty
** @param [r] splice_sites [const AjPSeq] Marked splice sites.
**     The intron_penalty may be modified to splice_penalty if splice_sites is
**     non-null and there are DONOR and ACCEPTOR sites at the start and
**     end of the intron.
** @param [r] backtrack [ajint] Boolean.
**     If backtrack is 0 then only the start and end points and the score
**     are computed, and no path matrix is allocated.
** @param [r] needleman [ajint] Boolean 1 = global alignment
**                                      0 = local alignment
** @param [r] init_path [ajint] Type of initialization for the path.
**     If init_path  is DIAGONAL then the boundary conditions are adjusted
**     so that the optimal path enters the cell (0,0) diagonally. Otherwise
**     it enters from the left (ie as a deletion in the EST)
**
** @return [EmbPEstAlign] Resulting genomic EST alignment
**
** @release 1.13.0
** @@
******************************************************************************/

EmbPEstAlign embEstAlignNonRecursive(const AjPSeq est, const AjPSeq genome,
				     ajint gap_penalty, ajint intron_penalty,
				     ajint splice_penalty,
				     const AjPSeq splice_sites,
				     ajint backtrack, ajint needleman,
				     ajint init_path)
{
    AjPSeq gdup = NULL;
    AjPSeq edup = NULL;
    const char* splice_sites_str;
    unsigned char **ppath = NULL;
    unsigned char *path   = NULL;
    ajint *score1;
    ajint *score2;
    ajint *s1;
    ajint *s2;
    ajint *s3;
    ajint *best_intron_score;
    ajint *best_intron_coord;
    ajint e_len_pack;
    ajint gpos;
    ajint epos;
    ajint glen;
    ajint elen;
    ajint emax = -1;
    ajint gmax = -1;
    ajint max_score = 0;
    ajint diagonal;
    ajint delete_genome;
    ajint delete_est;
    ajint intron;
    const char *gseq;
    const char *eseq;
    char g;
    ajint max;
    ajint total = 0;
    ajint p;
    ajint pos;
    ajint *temp_path = NULL;
    ajint is_acceptor;
    EmbPEstAlign ge;
    EstPCoord start1 = NULL;
    EstPCoord start2 = NULL;
    EstPCoord t1     = NULL;
    EstPCoord t2     = NULL;
    EstPCoord t3     = NULL;

    EstPCoord best_intron_start = NULL;
    EstOCoord best_start;
    ajint splice_type = 0;

    unsigned char direction;
    unsigned char diagonal_path[4]      = { 1, 4, 16, 64 };
    unsigned char delete_est_path[4]    = { 2, 8, 32, 128 };
    unsigned char delete_genome_path[4] = { 3, 12, 48, 192 };
    unsigned char mask[4]               = { 3, 12, 48, 192 };

    /*
     ** path is encoded as 2 bits per cell:
     **
     ** 00 intron
     ** 10 diagonal
     ** 01 delete_est
     ** 11 delete_genome
     ** the backtrack path, packed 4 cells per byte
     */

    char dbgmsg[512] = "<undefined>\n";

    best_start.right = 0;
    best_start.left  = 0;

    glen = ajSeqGetLen(genome);
    elen = ajSeqGetLen(est);
    splice_sites_str = ajSeqGetSeqC(splice_sites);
    e_len_pack = elen/4+1;

    if(debug)
    {
	ajDebug("embEstAlignNonRecursive\n");
	ajDebug("   backtrack:%d needleman:%d, init_path:%d\n",
		backtrack, needleman, init_path);
    }

    AJNEW0(ge);

    if(backtrack)
    {
	AJCNEW(ppath, glen);

	for(gpos=0;gpos<glen;gpos++)
	    AJCNEW(ppath[gpos], e_len_pack);

	AJCNEW(temp_path,  glen+elen);
    }
    else
    {
	AJCNEW(start1,elen+1);
	AJCNEW(start2, elen+1);
	AJCNEW(best_intron_start, elen);

	t1 = start1+1;
	t2 = start2+1;
    }

    AJCNEW(score1, ajSeqGetLen(est)+1);
    AJCNEW(score2, ajSeqGetLen(est)+1);

    s1 = score1+1;
    s2 = score2+1;

    AJCNEW(best_intron_coord, elen+1);
    AJCNEW(best_intron_score, elen+1);

    gdup = ajSeqNewSeq(genome);
    edup = ajSeqNewSeq(est);
    ajSeqFmtLower(gdup);
    ajSeqFmtLower(edup);
    gseq = ajSeqGetSeqC(gdup);
    eseq = ajSeqGetSeqC(edup);

    if(!backtrack)
    {
	/* initialise the boundaries for the start points */
	for(epos=0;epos<elen;epos++)
	{
	    t1[epos].left = 0;
	    t1[epos].right = epos;
	    t2[epos].left = 0;	  /* try initializing t2 explicitly */
	    t2[epos].right = epos; /* otherwise it gets missed on first pass */
	    best_intron_start[epos] = t1[epos];
	}
    }

    if(needleman)
	for(epos=0;epos<elen;epos++)
	{
	    s1[epos] = MINUS_INFINITY;
	    best_intron_score[epos] = MINUS_INFINITY;
	}

    for(gpos=0;gpos<glen;gpos++) /* loop thru GENOME sequence */
    {
	s3 = s1;
	s1 = s2;
	s2 = s3;

	if((gpos % 1000) == 0)
	    ajDebug(" genome base %d\n", gpos);

	g = gseq[gpos];

	if( backtrack )
	    path = ppath[gpos];
	else
	{
	    t3 = t1; t1 = t2; t2 = t3;
	    t2[-1].left = gpos;	       /* set start1[0] to (gpos,0) */
	    t1[-1].left = gpos;	       /* set start1[0] to (gpos,0) */
	    t1[-1].right = 0;
	}

	if( splice_sites && (splice_sites_str[gpos] & ACCEPTOR ) )
	    is_acceptor = 1; /* gpos is last base of putative intron */
	else
	    is_acceptor = 0;

	/* initialisation */

	if( needleman )
	{
	    if(init_path == DIAGONAL || gpos > 0)
		s1[-1] = MINUS_INFINITY;
	    else
		s1[-1] = 0;
	}
	else
	    s1[-1] = 0;

	for(epos=0;epos<elen;epos++) /* loop thru EST sequence */
	{
	    /* align est and genome */

	    diagonal = s2[epos-1] + lsimmat[(ajint)g][(ajint)eseq[epos]];

	    /* single deletion in est */

	    delete_est = s1[epos-1] - gap_penalty;

	    /* single deletion in genome */

	    delete_genome = s2[epos] - gap_penalty;

	    /*
	    ** intron in genome, possibly modified by
	    ** donor-acceptor splice sites
	    */

	    if(is_acceptor &&
	       (splice_sites_str[best_intron_coord[epos]] & DONOR))
		intron = best_intron_score[epos] - splice_penalty;
	    else
		intron = best_intron_score[epos] - intron_penalty;

	    if(delete_est > delete_genome)
		max = delete_est;
	    else
		max = delete_genome;

	    if(diagonal > max)
		max = diagonal;

	    if(intron > max)
		max = intron;

	    if(needleman || max > 0)	/* save this score */
	    {
		if(max == diagonal)	/* match extension */
		{
		    s1[epos] = diagonal;

		    if(backtrack)
			path[epos/4] =  ajSysCastItouc((ajuint) path[epos/4] |
				      	   (ajuint) diagonal_path[epos%4]);
		    else
		    {
			if( t2[epos-1].left == -1 ) /* SW start */
			{
			    t1[epos].left = gpos;
			    t1[epos].right = epos;
			    if(debug && t1[epos].left == 10126)
				sprintf(dbgmsg,
					"t1[%d].left = gpos:%d\n",
					epos, gpos);
			}
			else
			{
			    /* continue previous match */
			    t1[epos] = t2[epos-1];

			    if(debug && t1[epos].left == 10126)
				sprintf(dbgmsg,
					"t1[%d] = t2[epos-1] "
					"left:%d right:%d gpos: %d(a)\n",
					epos, t1[epos].left, t1[epos].right,
					gpos);
			}
		    }
		}
		else if( max == delete_est ) /* (continue) gap in EST */
		{
		    s1[epos] = delete_est;

		    if( backtrack )
		    {			/* <mod> */
			path[epos/4]  =  ajSysCastItouc((ajuint) path[epos/4] |
					    (ajuint) delete_est_path[epos%4]);
		    }
		    else
		    {
			t1[epos] = t1[epos-1];

			if(debug && t1[epos].left == 10126)
			    sprintf(dbgmsg,
				    "t1[%d] = t2[epos-1] left:%d (b)\n",
				    epos, t1[epos].left);
		    }
		}
		else if( max == delete_genome )
		{
		    /* (continue) gap in GENOME */
		    s1[epos] = delete_genome;

		    if( backtrack )
		    {			/* <mod> */
			path[epos/4] = ajSysCastItouc((ajuint) path[epos/4] |
					 (ajuint) delete_genome_path[epos%4]);
		    }
		    else
		    {
			t1[epos] = t2[epos];

			if(debug && t1[epos].left == 10126)
			    sprintf(dbgmsg,
				    "t1[%d] = t2[epos] left:%d\n",
				    epos, t1[epos].left);
		    }
		}
		else
		{
		    /* Intron */
		    s1[epos] = intron;

		    if(!backtrack)
			t1[epos] = best_intron_start[epos];
		}
	    }
	    else
	    {
		/* not worth saving (SW with score < 0 ) */
		s1[epos] = 0;

		if(!backtrack)
		{
		    t1[epos].left = -1;
		    t1[epos].right = -1;
		}
	    }


	    if( best_intron_score[epos] < s1[epos] )
	    {
		/* if( intron > 0 ) */ /* will only need to store
		   if this path is positive */
		if( backtrack )
		    if( estDoNotForget(epos,
				       best_intron_coord[epos]) == 0 )
			/*
			** store the previous path just
			** in case we need it
			*/

		    {
			/*
			** error - stack ran out of memory. Clean up
			** and return NULL
			*/
			ajErr("stack ran out of memory, returning NULL");

			AJFREE(score1);
			AJFREE(score2);
			/* AJFREE(eseq); */ /* copy of pointer from edup */
			/* AJFREE(gseq); */ /* copy of pointer from gdup */
			AJFREE(best_intron_score);
			AJFREE(best_intron_coord);
			AJFREE(temp_path);

			for(gpos=0;gpos<glen;gpos++)
			    AJFREE(ppath[gpos]);

			AJFREE(ppath);
			estPairFree();
			AJFREE(ge);

			ajSeqDel(&gdup);
			ajSeqDel(&edup);

			return NULL;
		    }

		best_intron_score[epos] = s1[epos];
		best_intron_coord[epos] = gpos;

		if(!backtrack)
		    best_intron_start[epos] = t1[epos];
	    }

	    if(!needleman && max_score < s1[epos])
	    {
		max_score = s1[epos];
		emax = epos;
		gmax = gpos;

		if(!backtrack)
		{
		    best_start = t1[epos];

		    if(verbose)
			ajDebug("max_score: %d best_start = t1[%d] "
				"left:%d right:%d\n",
				max_score, epos, best_start.left,
				best_start.right);
		    if(verbose)
			ajDebug("t1 from :%s\n", dbgmsg);
		}
	    }
	}
    }

    /* back track */

    if( needleman )
    {
	ge->gstop = glen-1;
	ge->estop = elen-1;
	ge->score = s1[ge->estop];
    }
    else
    {
	ge->gstop = gmax;
	ge->estop = emax;
	ge->score = max_score;
    }

    if(backtrack)
    {
	pos = 0;

	epos = ge->estop;
	gpos = ge->gstop;
	total = 0;

	/* determine the type of spliced intron (forward or reversed) */

	if(splice_sites)
	{
	    if( ! strcmp( ajSeqGetNameC(splice_sites), "forward") )
		splice_type = FORWARD_SPLICED_INTRON;
	    else if( ! strcmp( ajSeqGetNameC(splice_sites), "reverse") )
		splice_type = REVERSE_SPLICED_INTRON;
	    else
	    {
		ajUser("splice_sites '%s'", ajSeqGetNameC(splice_sites));
		splice_type = INTRON; /* This is really an error - splice_sites
					 MUST have a direction */
	    }
	}

	while(( needleman || total < max_score) && epos >= 0 && gpos >= 0 )
	{
	    direction = ajSysCastItouc(((ajuint)ppath[gpos][epos/4] &
				    (ajuint)mask[epos%4] ) >> (2*(epos%4)));
	    temp_path[pos++] = direction;

	    if((ajuint) direction == INTRON ) /* intron */
	    {
		ajint gpos1;

		if( gpos-best_intron_coord[epos]  <= 0 )
		{
		    if( verbose )
			ajWarn("NEGATIVE intron gpos: %d %d\n",
			       gpos, gpos-best_intron_coord[epos] );
		    gpos1 = estPairRemember(epos, gpos );
		}
		else
		    gpos1 = best_intron_coord[epos];

		if( splice_sites && (splice_sites_str[gpos] & ACCEPTOR ) &&
		   ( splice_sites_str[gpos1] & DONOR ) )
		{
		    total -= splice_penalty;
		    temp_path[pos-1] = splice_type; /* make note that this
						       is a proper intron */
		}
		else
		    total -= intron_penalty;

		temp_path[pos++] = gpos-gpos1; /* intron this far */
		gpos = gpos1;
	    }
	    else if((ajuint) direction == DIAGONAL ) /* diagonal */
	    {
		total += lsimmat[(ajint)gseq[gpos]][(ajint)eseq[epos]];
		epos--;
		gpos--;
	    }
	    else if((ajuint) direction == DELETE_EST ) /* delete_est */
	    {
		total -= gap_penalty;
		epos--;
	    }
	    else			/* delete_genome */
	    {
		total -= gap_penalty;
		gpos--;
	    }
	}

	gpos++;
	epos++;


	ge->gstart = gpos;
	ge->estart = epos;
	ge->len    = pos;

	if(debug)
	    ajDebug("gstart = gpos (a) : %d\n", ge->gstart);

	AJCNEW(ge->align_path, ge->len);

	/* reverse the ge so it starts at the beginning of the sequences */

	for(p=0;p<ge->len;p++)
	{
	    if( temp_path[p] > INTRON ) /* can be INTRON or
					   FORWARD_SPLICED_INTRON or
					   REVERSE_SPLICED_INTRON */
		ge->align_path[pos-p-1] = temp_path[p];
	    else
	    {
		ge->align_path[pos-p-2] = temp_path[p];
		ge->align_path[pos-p-1] = temp_path[p+1];
		p++;
	    }
	}
    }
    else
    {
	ge->gstart = best_start.left;
	ge->estart = best_start.right;

	if(debug)
	    ajDebug("gstart = best_start.left : %d\n", ge->gstart);
    }

    AJFREE(score1);
    AJFREE(score2);

    AJFREE(best_intron_score);
    AJFREE(best_intron_coord);
    ajSeqDel(&gdup);
    ajSeqDel(&edup);

    if( backtrack )
    {
	AJFREE(temp_path);

	for(gpos=0;gpos<glen;gpos++)
	    AJFREE(ppath[gpos]);

	AJFREE(ppath);
	estPairFree();
    }
    else
    {
	AJFREE(start1);
	AJFREE(start2);
	AJFREE(best_intron_start);
    }

    if(debug)
	ajDebug("RETURN: embEstAlignNonRecursive "
		"score %d total: %d gstart %d estart %d "
		"gstop %d estop %d\n",
		ge->score, total, ge->gstart, ge->estart,
		ge->gstop, ge->estop );

    return ge;
}




/* @func embEstAlignLinearSpace ***********************************************
**
** Align EST sequence to genomic in linear space
**
** @param [r] est [const AjPSeq] Sequence of EST
** @param [r] genome [const AjPSeq] Sequence of genomic region
** @param [r] match [ajint] Match score
** @param [r] mismatch [ajint] Mismatch penalty (positive)
** @param [r] gap_penalty [ajint] Gap penalty
** @param [r] intron_penalty [ajint] Intron penalty
** @param [r] splice_penalty [ajint] Splice site penalty
** @param [r] splice_sites [const AjPSeq] Marked splice sites.
**     The intron_penalty may be modified to splice_penalty if splice_sites is
**     non-null and there are DONOR and ACCEPTOR sites at the start and
**     end of the intron.
** @param [r] megabytes [float] Maximum memory allowed in Mbytes for
**        alignment by standard methods.
**
** @return [EmbPEstAlign] Genomic EST alignment
**
** @release 1.13.0
** @@
******************************************************************************/

EmbPEstAlign embEstAlignLinearSpace( const AjPSeq est, const AjPSeq genome,
				    ajint match, ajint mismatch,
				    ajint gap_penalty,
				    ajint intron_penalty,
				    ajint splice_penalty,
				    const AjPSeq splice_sites,
				    float megabytes )
{
    EmbPEstAlign ge;
    EmbPEstAlign rge;
    AjPSeq genome_subseq;
    AjPSeq est_subseq;
    AjPSeq splice_subseq;
    float area;
    float max_area;
    ajint glen;
    ajint elen;

    elen = ajSeqGetLen(est);
    glen = ajSeqGetLen(genome);

    max_area = megabytes*(float)1.0e6;

    if(debug)
	ajDebug("embEstAlignLinearSpace\n");

    estPairInit((ajint)((float)1.0e6*megabytes) );

    area = ((float)glen+(float)1.0)
	*((float)elen+(float)1.0)
	    /(float)4;	 /* divide by 4 as we pack 4 cells per byte */

    if(debug)
	ajDebug("area %.6f max_area %.6f\n", area/1000000.0,
		max_area/1000000.0);

    /* sequences small enough to align by standard methods ? */

    if( area <= max_area )
    {
	if(debug)
	    ajDebug("using non-recursive alignment %d %d   %.6f %.6f\n",
		    glen, elen,
		    area/1000000.0, max_area/1000000.0);

	return embEstAlignNonRecursive(est, genome,
				       gap_penalty, intron_penalty,
				       splice_penalty, splice_sites,
				       1, 0, DIAGONAL);
    }

    /*
    ** need to recursively split
    **
    ** first do a Smith-Waterman without backtracking to find
    ** the start and end of the alignment
    */

    ge = embEstAlignNonRecursive(est, genome,
				 gap_penalty, intron_penalty,
				 splice_penalty, splice_sites,
				 0, 0, DIAGONAL);

    /* extract subsequences corresponding to the aligned regions */

    if(debug)
	ajDebug("sw alignment score %d gstart %d estart %d "
		"gstop %d estop %d\n", ge->score, ge->gstart,
		ge->estart, ge->gstop, ge->estop );

    genome_subseq = ajSeqNewSeq(genome);
    est_subseq = ajSeqNewSeq(est);
    ajSeqSetRange(genome_subseq, ge->gstart+1, ge->gstop+1);
    ajSeqSetRange(est_subseq, ge->estart+1, ge->estop+1);
    ajSeqTrim(genome_subseq);
    ajSeqTrim(est_subseq);

    if( splice_sites )
    {
	splice_subseq = ajSeqNewSeq(splice_sites);
	ajSeqSetRange(splice_subseq, ge->gstart+1, ge->gstop+1 );
	ajSeqTrim(splice_subseq);
    }
    else
	splice_subseq = NULL;

    /* recursively do the alignment */

    rge = estAlignRecursive(est_subseq, genome_subseq, match,
			    mismatch, gap_penalty, intron_penalty,
			    splice_penalty, splice_subseq, max_area);

    ge->len = rge->len;
    ge->align_path = rge->align_path;

    AJFREE(rge);
    ajSeqDel(&genome_subseq);
    ajSeqDel(&est_subseq);
    ajSeqDel(&splice_subseq);

    if(debug)
	ajDebug("RETURN: embEstAlignLinearSpace "
		"score %d gstart %d estart %d "
		"gstop %d estop %d\n",
		ge->score, ge->gstart, ge->estart,
		ge->gstop, ge->estop );

    return ge;
}




/* @funcstatic estAlignRecursive **********************************************
**
** Modified Smith-Waterman/Needleman to align an EST or mRNA to a Genomic
**     sequence, allowing for introns
**
** @param [r] est [const AjPSeq] Sequence of EST
** @param [r] genome [const AjPSeq] Sequence of genomic region
** @param [r] match [ajint] Match score
** @param [r] mismatch [ajint] Mismatch penalty (positive)
** @param [r] gap_penalty [ajint] Gap penalty
** @param [r] intron_penalty [ajint] Intron penalty
** @param [r] splice_penalty [ajint] Splice site penalty
** @param [r] splice_sites [const AjPSeq] Marked splice sites.
**     The intron_penalty may be modified to splice_penalty if splice_sites is
**     non-null and there are DONOR and ACCEPTOR sites at the start and
**     end of the intron.
** @param [r] max_area [float] Maximum memory available for alignment
**            by standard method (allowing 4 bases per byte).
**            Otherwise sequences are split and aligned recursively.
**
** @return [EmbPEstAlign] Resulting genomic EST alignment
**
** @release 1.13.0
** @@
******************************************************************************/

static EmbPEstAlign estAlignRecursive( const AjPSeq est,const  AjPSeq genome,
				      ajint match, ajint mismatch,
				      ajint gap_penalty, ajint intron_penalty,
				      ajint splice_penalty,
				      const AjPSeq splice_sites,
				      float max_area)
{
    ajint middle;
    ajint gleft;
    ajint gright;
    ajint score;
    ajint i;
    ajint j;
    AjPSeq left_splice  = NULL;
    AjPSeq right_splice = NULL;
    AjPSeq left_genome;
    AjPSeq right_genome;
    AjPSeq left_est;
    AjPSeq right_est;
    EmbPEstAlign left_ge;
    EmbPEstAlign right_ge;
    EmbPEstAlign ge;
    float area;
    ajint split_on_del;
    ajint glen;
    ajint elen;

    if(debug)
	ajDebug("estAlignRecursive\n");

    glen = ajSeqGetLen(genome);
    elen = ajSeqGetLen(est);

    area = ((float)glen+(float)1.0)
	*((float)elen+(float)1.0)
	    /(float)4;	 /* divide by 4 as we pack 4 cells per byte */

    if(debug)
	ajDebug("area %.6f max_area %.6f\n", area/1000000.0,
		max_area/1000000.0);

    /* sequences small enough to align by standard methods */

    if( area <= max_area )
    {
	if(debug)
	    ajDebug("using non-recursive alignment %d %d   %.6f %.6f\n",
		    ajSeqGetLen(genome), ajSeqGetLen(est),
		    area/1000000.0, max_area/1000000.0);

	ge = embEstAlignNonRecursive( est, genome,
				     gap_penalty, intron_penalty,
				     splice_penalty, splice_sites,
				     1, 1, DIAGONAL );

	if(ge != NULL)
	{
	    /* success */
	    if(debug)
		ajDebug("RETURN: estAlignRecursive success returns "
			"ge gstart:%d estart:%d gstop:%d estop:%d\n",
			ge->gstart, ge->estart, ge->gstop, ge->estop);
	    return ge;
	}
	else		    /* failure because we ran out of memory */
	{
	    if(debug)
		ajDebug("Stack memory overflow ... splitting\n");
	}
    }
    /* need to recursively split */

    if(debug)
	ajDebug("splitting genome and est\n");

    middle = ajSeqGetLen(est)/2;

    score = estAlignMidpt( est, genome, gap_penalty,
			  intron_penalty, splice_penalty, splice_sites,
			  middle, &gleft, &gright );
    if(debug)
	ajDebug("score %d middle %d gleft %d gright %d\n",
		score, middle, gleft, gright );

    split_on_del = (gleft == gright);


    /* split genome */

    left_genome = ajSeqNewSeq(genome);
    right_genome = ajSeqNewSeq(genome);
    ajSeqSetRange(left_genome,  1, gleft+1 );
    ajSeqSetRange(right_genome, gright+1, ajSeqGetLen(genome));
    ajSeqTrim(left_genome);
    ajSeqTrim(right_genome);

    if( splice_sites )
    {
	left_splice = ajSeqNewSeq(splice_sites);
	right_splice = ajSeqNewSeq(splice_sites);
	ajSeqSetRange(left_splice,  1, gleft+1 );
	ajSeqSetRange(right_splice, gright+1, ajSeqGetLen(genome));
	ajSeqTrim(left_splice);
	ajSeqTrim(right_splice);
    }

    /* split est */

    left_est = ajSeqNewSeq(est);
    right_est = ajSeqNewSeq(est);
    ajSeqSetRange(left_est,  1, middle+1 );
    ajSeqSetRange(right_est, middle+2, ajSeqGetLen(est));
    ajSeqTrim(left_est);
    ajSeqTrim(right_est);

    /* align left and right parts separately */

    if(verbose)
	ajDebug("LEFT\n");

    left_ge = estAlignRecursive(left_est, left_genome, match, mismatch,
				gap_penalty, intron_penalty,
				splice_penalty, left_splice, max_area);

    if(verbose)
	ajDebug("RIGHT\n");

    right_ge = estAlignRecursive( right_est, right_genome, match,
				 mismatch, gap_penalty, intron_penalty,
				 splice_penalty, right_splice, max_area);


    /* merge the alignments */

    AJNEW0(ge);
    ge->score = left_ge->score + right_ge->score;
    ge->gstart = 0;
    ge->estart = 0;
    ge->gstop = ajSeqGetLen(genome)-1;
    ge->estop = ajSeqGetLen(est)-1;

    ge->len = left_ge->len+right_ge->len;
    AJCNEW(ge->align_path, ge->len);

    for(i=0,j=0;j<left_ge->len;i++,j++)
	ge->align_path[i] = left_ge->align_path[j];

    if(split_on_del)			/* merge on an est deletion */
    {
	if(debug)
	    ajDebug("split_on_del split at deletion at %d\n", i);
	ge->align_path[i++] = DELETE_EST;

	for(j=1;j<right_ge->len;i++,j++) /* omit first symbol on
					    right-hand alignment */
	    ge->align_path[i] = right_ge->align_path[j];
    }
    else
	for(j=0;j<right_ge->len;i++,j++)
	    ge->align_path[i] = right_ge->align_path[j];

    ajSeqDel(&left_est);
    ajSeqDel(&right_est);
    ajSeqDel(&left_genome);
    ajSeqDel(&right_genome);

    if(splice_sites)
    {
	ajSeqDel(&left_splice);
	ajSeqDel(&right_splice);
    }

    embEstFreeAlign(&left_ge);
    embEstFreeAlign(&right_ge );

    if(debug)
	ajDebug("RETURN: estAlignRecursive at end returns "
		"ge gstart:%d estart:%d gstop:%d estop:%d\n",
		ge->gstart, ge->estart, ge->gstop, ge->estop);
    return ge;
}




/* @funcstatic estAlignMidpt **************************************************
**
** Modified Needleman-Wunsch to align an EST or mRNA to a Genomic
** sequence, allowing for introns. The recursion is
**
**     {  S[gpos-1][epos]   - gap_penalty
**
**     {  S[gpos-1][epos-1] + D[gpos][epos]
**
**     S[gpos][epos] = max {  S[gpos][epos-1]   - gap_penalty
**
**     {  C[epos]           - intron_penalty
**
**     C[epos] = max{ S[gpos][epos], C[epos] }
**
**     S[gpos][epos] is the score of the best path to the cell gpos, epos
**     C[epos] is the score of the best path to the column epos
**
**     The intron_penalty may be modified to splice_penalty if splice_sites is
**     non-null and there are DONOR and ACCEPTOR sites at the start and
**     end of the intron.
**
**     NB: IMPORTANT:
**
**     The input sequences are assumed to be subsequences chosen so
**     that they align end-to end, with NO end gaps. Call
**     non_recursive_est_to_genome() to get the initial max scoring
**     segment and chop up the sequences appropriately.
**
**     The return value is the alignment score.
**
**     If the alignment crosses middle by a est deletion (ie horizontally) then
**              gleft == gright
**
** @param [r] est [const AjPSeq] Sequence of EST
** @param [r] genome [const AjPSeq] Sequence of genomic region
** @param [r] gap_penalty [ajint] Gap penalty
** @param [r] intron_penalty [ajint] Intron penalty
** @param [r] splice_penalty [ajint] Splice site penalty
** @param [r] splice_sites [const AjPSeq] Marked splice sites.
**     The intron_penalty may be modified to splice_penalty if splice_sites is
**     non-null and there are DONOR and ACCEPTOR sites at the start and
**     end of the intron.
** @param [r] middle [ajint] Sequence mid point position.
**     This Function does not compute the path, instead it finds the
**     genome coordinates where the best path crosses epos=middle, so this
**     should be called recursively to generate the complete alignment in
**     linear space.
** @param [w] gleft [ajint*] genome left coordinate at the crossing point.
**     If the alignment crosses middle in a diagonal fashion then
**              gleft+1 == gright
** @param [w] gright [ajint*] genome right coordinate at the crossing point.
**     If the alignment crosses middle in a diagonal fashion then
**              gleft+1 == gright
**
** @return [ajint] alignment score
**
** @release 1.13.0
** @@
******************************************************************************/

static ajint estAlignMidpt( const AjPSeq est, const AjPSeq genome,
			   ajint gap_penalty,
			   ajint intron_penalty,
			   ajint splice_penalty, const AjPSeq splice_sites,
			   ajint middle, ajint *gleft, ajint *gright )
{
    AjPSeq gdup = NULL;
    AjPSeq edup = NULL;
    ajint *score1;
    ajint *score2;
    ajint *s1;
    ajint *s2;
    ajint *s3;
    ajint *best_intron_score;
    ajint *best_intron_coord;
    ajint gpos;
    ajint epos;
    ajint glen;
    ajint elen;
    ajint score;
    ajint diagonal;
    ajint delete_genome;
    ajint delete_est;
    ajint intron;
    const char *gseq;
    const char *eseq;
    char g;
    ajint max;
    ajint is_acceptor;
    EstPCoord m1;
    EstPCoord m2;
    EstPCoord m3;
    EstPCoord midpt1;
    EstPCoord midpt2;
    EstPCoord best_intron_midpt;
    const char *splice_sites_str;

    splice_sites_str = ajSeqGetSeqC(splice_sites);

    AJCNEW(score1, ajSeqGetLen(est)+1);
    AJCNEW(score2, ajSeqGetLen(est)+1);

    s1 = score1+1;
    s2 = score2+1;


    AJCNEW(midpt1, ajSeqGetLen(est)+1);
    AJCNEW(midpt2, ajSeqGetLen(est)+1);

    m1 = midpt1+1;
    m2 = midpt2+1;

    AJCNEW(best_intron_coord, ajSeqGetLen(est)+1);
    AJCNEW(best_intron_score, ajSeqGetLen(est)+1);
    AJCNEW(best_intron_midpt, ajSeqGetLen(est)+1);


    gdup = ajSeqNewSeq(genome);
    edup = ajSeqNewSeq(est);
    ajSeqFmtLower(gdup);
    ajSeqFmtLower(edup);
    gseq = ajSeqGetSeqC(gdup);
    eseq = ajSeqGetSeqC(edup);
    glen = ajSeqGetLen(genome);
    elen = ajSeqGetLen(est);

    middle++;


    /* initialise the boundary: We want the alignment to start at [0,0] */

    for(epos=0;epos<elen;epos++)
    {
	s1[epos] = MINUS_INFINITY;
	best_intron_score[epos] = MINUS_INFINITY;
    }

    for(gpos=0;gpos<glen;gpos++)
    {
	s3 = s1; s1 = s2; s2 = s3;
	m3 = m1; m1 = m2; m2 = m3;

	g = gseq[gpos];

	if(splice_sites && ( splice_sites_str[gpos] & ACCEPTOR ))
	    is_acceptor = 1; /* gpos is last base of putative intron */
	else
	    is_acceptor = 0;


	/* boundary conditions */

	s1[-1] = MINUS_INFINITY;

	/* the meat */

	for(epos=0;epos<elen;epos++)
	{
	    /* align est and genome */

	    diagonal = s2[epos-1] + lsimmat[(ajint)g][(ajint)eseq[epos]];

	    /* single deletion in est */

	    delete_est = s1[epos-1] - gap_penalty;

	    /* single deletion in genome */

	    delete_genome = s2[epos] - gap_penalty;

	    /*
	    ** intron in genome, possibly modified by
	    ** donor-acceptor splice sites
	    */

	    if(is_acceptor &&
	       (splice_sites_str[best_intron_coord[epos]] & DONOR ))
		intron = best_intron_score[epos] - splice_penalty;
	    else
		intron = best_intron_score[epos] - intron_penalty;

	    if(delete_est > delete_genome)
		max = delete_est;
	    else
		max = delete_genome;

	    if(diagonal > max)
		max = diagonal;

	    if(intron > max)
		max = intron;

	    if(max == diagonal)
	    {
		s1[epos] = diagonal;

		if(epos == middle)
		{
		    m1[epos].left = gpos-1;
		    m1[epos].right = gpos;
		}
		else
		    m1[epos] = m2[epos-1];
	    }
	    else if(max == delete_est)
	    {
		s1[epos] = delete_est;

		if( epos == middle )
		{
		    m1[epos].left = gpos;
		    m1[epos].right = gpos;
		}
		else
		    m1[epos] = m1[epos-1];
	    }
	    else if(max == delete_genome)
	    {
		s1[epos] = delete_genome;
		m1[epos] = m2[epos];
	    }
	    else			/* intron */
	    {
		s1[epos] = intron;
		m1[epos] = best_intron_midpt[epos];
	    }

	    if(best_intron_score[epos] < s1[epos])
	    {
		best_intron_score[epos] = s1[epos];
		best_intron_coord[epos] = gpos;
		best_intron_midpt[epos] = m1[epos];
	    }
	}
    }

    *gleft  = m1[ajSeqGetLen(est)-1].left;
    *gright = m1[ajSeqGetLen(est)-1].right;
    score   = s1[ajSeqGetLen(est)-1];

    if(debug)
	ajDebug("midpt score %d middle %d gleft %d gright %d "
		"est %d genome %d\n",
		score, middle-1, *gleft, *gright, ajSeqGetLen(est),
		ajSeqGetLen(genome));

    AJFREE(score1);
    AJFREE(score2);
    AJFREE(midpt1);
    AJFREE(midpt2);
    AJFREE(best_intron_score);
    AJFREE(best_intron_coord);
    AJFREE(best_intron_midpt);
    ajSeqDel(&gdup);
    ajSeqDel(&edup);

    return score;
}




/* @funcstatic estPairRemember ************************************************
**
** Recall saved pair values for row and column
**
** @param [r] col [ajint] Current column
** @param [r] row [ajint] Current row
**
** @return [ajint] Row number
**
** @release 1.13.0
** @@
******************************************************************************/

static ajint estPairRemember( ajint col, ajint row )
{
    EstOSavePair rp;
    ajint left;
    ajint right;
    ajint middle;
    ajint d;
    ajint bad;

    if(!rpairs_sorted)
    {
	qsort(rpair, rpairs, sizeof(EstOSavePair), estSavePairCmp);
	rpairs_sorted = 1;
    }

    rp.col = col;
    rp.row = row;

    left = 0;
    right = rpairs-1;

    if(debug)
	ajDebug("estPairRemember left: %d right: %d rp rp.col rp.row\n",
		left, right, rp, rp.col, rp.row);

    /*
    ** MATHOG, changed flow somewhat, added "bad" variable, inverted some
    ** tests ( PLEASE CHECK THEM!  I did this because the original version
    ** had two ways to drop into the failure code, but one of them was only
    ** evident after careful reading of the code.
    */

    if((estSavePairCmp(&rpair[left],&rp ) > 0 ) ||
       (estSavePairCmp(&rpair[right],&rp ) < 0 ))
	bad = 1;      /*MATHOG, preceding test's logic was inverted */
    else
    {
	bad = 0;
	while(right-left > 1)
	{
	    /* binary check for row/col */
	    middle = (left+right)/2;
	    d = estSavePairCmp( &rpair[middle], &rp );

	    if( d < 0 )
		left = middle;
	    else if( d >= 0 )
		right = middle;
	}

	if(debug)
	    ajDebug("col %d row %d right: col %d row %d left: col %d row %d\n",
		    col, row, rpair[right].col, rpair[right].row,
		    rpair[left].col,
		    rpair[left].row );

	/*
	** any of these fail indicates failure
	** MATHOG, next test's logic was inverted
	*/
	if( estSavePairCmp( &rpair[right], &rp ) < 0 ||
	   rpair[left].col != col ||
	   rpair[left].row >= row )
	{
	    if(debug)
	    {
		ajDebug("estPairRemember => bad2\n");
		ajDebug("estSavePairCmp( %d+%d, %d+%d) %d\n",
			rpair[right].col, rpair[right].row,
			rp.col, rp.row,
			estSavePairCmp( &rpair[right], &rp ));
		ajDebug("rpair[left].col %d %d\n", rpair[left].col, col);
		ajDebug("rpair[left].row %d %d\n", rpair[left].row, row);
	    }

	    bad = 2;
	}
    }

    /* error - this should never happen  */

    if(bad != 0)
	ajFatal("ERROR in estPairRemember() "
		"left: %d (%d %d) right: %d (%d %d) "
		"col: %d row: %d, bad: %d\n",
		left, rpair[left].col, rpair[left].row, right,
		rpair[right].col, rpair[right].row, col, row, bad);

    return rpair[left].row;
}




/* @funcstatic estSavePairCmp *************************************************
**
** Compare two EstPSavePair values. Return the column difference, or if
** the columns are the same, return the row difference.
**
** A value of zero means the two RPAIRS are identical.
**
** @param [r] a [const void*] First value
** @param [r] b [const void*] Second value
**
** @return [ajint] difference.
**
** @release 1.13.0
** @@
******************************************************************************/

static ajint estSavePairCmp( const void *a, const void *b )
{
    const EstPSavePair A;
    const EstPSavePair B;
    ajint n;

    A = (const EstPSavePair)a;
    B = (const EstPSavePair)b;
    n = A->col - B->col;

    if(n == 0)
	n = A->row - B->row;

    return n;
}




/* @funcstatic estPairInit ****************************************************
**
** Initialise the rpair settings
**
** @param [r] max_bytes [ajint] Maximum memory size (bytes)
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

static void estPairInit(ajint max_bytes)
{
    ajint maxpairs = max_bytes/sizeof(EstOSavePair);
    estPairFree();

    rpair_size = maxpairs;
 
    AJCNEW0(rpair, rpair_size);

    return;
}




/* @funcstatic estPairFree ****************************************************
**
** Free the rpairs data structure
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

static void estPairFree(void)
{
    if(debug)
	ajDebug("estPairFree: rpairs: %d rpair: %x\n", rpairs, rpair);

    if(rpair)
	AJFREE(rpair);

    rpair = NULL;
    rpair_size = 0;
    rpairs = 0;
    rpairs_sorted = 0;

    return;
}




/* @funcstatic estDoNotForget *************************************************
**
** Saving rpairs row and column values.
**
** @param [r] col [ajint] Current column
** @param [r] row [ajint] Current row
**
** @return [ajint] o upon error.
**
** @release 1.13.0
** @@
******************************************************************************/

static ajint estDoNotForget( ajint col, ajint row )
{
    if( rpairs >= rpair_size )
    {
	rpair_size = (rpairs == 0 ? 10000 : 2*rpairs);

	ajDebug("Rpair resize: %d to %d\n", rpairs, rpair_size);
	AJCRESIZE(rpair, rpair_size);

	if (!rpair)
	{
	    ajDie("Memory limit exceeded in allocating space for rpairs");

	    return 0;		     /* failure - ran out of memory */
	}

	if(verbose)
	{
	    ajDebug("rpairs %d allocated rpair_size %d rpair: %x\n",
		    rpairs, rpair_size, rpair);
	    ajDebug("test rpair[0] %x col %d row %d\n",
		    &rpair[0], rpair[0].col, rpair[0].row);
	    ajDebug("test rpair[%d] %x col %d row %d\n",
		    rpairs, &rpair[rpairs],
		    rpair[rpairs].col, rpair[rpairs].row);
	    ajDebug("test rpair[%d] %x col %d row %d\n",
		    rpair_size-1, &rpair[rpair_size-1],
		    rpair[rpair_size-1].col, rpair[rpair_size-1].row);
	}
    }

    rpair[rpairs].col = col;
    rpair[rpairs].row = row;

    rpairs++;
    rpairs_sorted = 0;

    return 1;				/* success */
}




/* @func embEstOutBlastStyle **************************************************
**
** output in blast style.
**
** @param [u] blast [AjPFile] Output file
** @param [r] genome [const AjPSeq] Genomic sequence
** @param [r] est [const AjPSeq] EST sequence
** @param [r] ge [const EmbPEstAlign] Genomic EST alignment
** @param [r] gap_penalty [ajint] Gap penalty
** @param [r] intron_penalty [ajint] Intron penalty
** @param [r] splice_penalty [ajint] Splice site penalty
** @param [r] gapped [ajint] Boolean. 1 = write a gapped alignment
** @param [r] reverse [ajint] Boolean. 1 = reverse alignment
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

void embEstOutBlastStyle(AjPFile blast, const AjPSeq genome, const AjPSeq est,
			 const EmbPEstAlign ge,
			 ajint gap_penalty, ajint intron_penalty,
			 ajint splice_penalty, ajint gapped, ajint reverse)
{

    ajint gsub;
    ajint gpos;
    ajint esub;
    ajint epos;
    ajint tsub;
    ajint p;
    ajint matches = 0;
    ajint len     = 0;
    ajint m;
    ajint total_matches = 0;
    ajint total_len     = 0;
    float percent;
    const char *genomestr;
    const char *eststr;
    ajint goff;
    ajint eoff;

    if(verbose)
	ajDebug("debugging set to %d\n", debug);

    genomestr = ajSeqGetSeqC(genome);
    eststr = ajSeqGetSeqC(est);

    gsub = gpos = ge->gstart;
    esub = epos = ge->estart;
    goff = ajSeqGetOffset(genome);
    eoff = ajSeqGetOffset(est);

    if(debug)
	ajDebug("blast_style_output: gsub %d esub %d\n", gsub, esub);

    if( blast )
    {
	tsub = 0;

	for(p=0;p<ge->len;p++)
	    if(ge->align_path[p] <= INTRON)
	    {
		estWriteMsp(blast, &matches, &len, &tsub, genome, gsub, gpos,
			    est, esub, epos, reverse, gapped);
		if(gapped)
		{
		    ajDebug("Intron: path:%d gpos:%d gstart:%d\n",
			    ge->align_path[p], gpos, ge->gstart);

		    if(ge->align_path[p] == INTRON)
		    {
			ajFmtPrintF(blast,
				    "?Intron  %5d %5.1f %5d %5d %-12S\n",
				    -intron_penalty, (float) 0.0, goff+gpos+1,
				    goff+gpos+ge->align_path[p+1],
				    ajSeqGetNameS(genome));
		    }
		    else		/* proper intron */
		    {
			if( ge->align_path[p] == FORWARD_SPLICED_INTRON )
			    ajFmtPrintF( blast,
					"+Intron  %5d %5.1f %5d %5d %-12s\n",
					-splice_penalty, (float) 0.0,
					goff+gpos+1,
					goff+gpos+ge->align_path[p+1],
					ajSeqGetNameC(genome) );
			else
			    ajFmtPrintF( blast,
					"-Intron  %5d %5.1f %5d %5d %-12s\n",
					-splice_penalty, (float) 0.0,
					goff+gpos+1,
					goff+gpos+ge->align_path[p+1],
					ajSeqGetNameC(genome) );

		    }
		}

		gpos += ge->align_path[++p];
		esub = epos;
		gsub = gpos;
	    }
	    else if(ge->align_path[p] == DIAGONAL)
	    {
		m = lsimmat[(ajint)genomestr[(ajint)gpos]]
		    [(ajint)eststr[(ajint)epos]];
		tsub += m;

		if(m > 0)
		{
		    matches++;
		    total_matches++;
		}

		len++;
		total_len++;
		gpos++;
		epos++;
	    }
	    else if(ge->align_path[p] == DELETE_EST)
	    {
		if(gapped)
		{
		    tsub -= gap_penalty;
		    epos++;
		    len++;
		    total_len++;
		}
		else
		{
		    estWriteMsp(blast, &matches, &len, &tsub, genome, gsub,
				gpos, est, esub, epos, reverse, gapped);
		    epos++;
		    esub = epos;
		    gsub = gpos;
		}
	    }
	    else if(ge->align_path[(ajint)p] == DELETE_GENOME)
	    {
		if(gapped)
		{
		    tsub -= gap_penalty;
		    gpos++;
		    total_len++;
		    len++;
		}
		else
		{
		    estWriteMsp(blast, &matches, &len, &tsub, genome, gsub,
				gpos, est, esub, epos, reverse, gapped);
		    gpos++;
		    esub = epos;
		    gsub = gpos;
		}
	    }

	estWriteMsp(blast, &matches, &len, &tsub, genome, gsub, gpos, est,
		    esub, epos, reverse, gapped);

	if(gapped)
	{
	    if(total_len > 0)
		percent = (total_matches/(float)(total_len))*(float)100.0;
	    else
		percent = (float) 0.0;

	    if(reverse)
		ajFmtPrintF( blast,
			    "\nSpan     %5d %5.1f %5d %5d %-12S %5d "
			    "%5d %-12S  %S\n",
			    ge->score, percent, goff+ge->gstart+1,
			    goff+ge->gstop+1,
			    ajSeqGetNameS(genome),
			    eoff+ajSeqGetLen(est)-ge->estart,
			    eoff+ajSeqGetLen(est)-ge->estop,
			    ajSeqGetNameS(est), ajSeqGetDescS(est) );
	    else
		ajFmtPrintF( blast,
			    "\nSpan     %5d %5.1f %5d %5d %-12S "
			    "%5d %5d %-12S  %S\n",
			    ge->score, percent, goff+ge->gstart+1,
			    goff+ge->gstop+1,
			    ajSeqGetNameS(genome), eoff+ge->estart+1,
			    eoff+ge->estop+1,
			    ajSeqGetNameS(est), ajSeqGetDescS(est) );
	}

    }

    return;
}




/* @funcstatic estWriteMsp ****************************************************
**
** write out the MSP (maximally scoring pair).
**
** @param [u] ofile [AjPFile] Output file
** @param [w] matches [ajint*] Number of matches found
** @param [w] len [ajint*] Length of alignment
** @param [w] tsub [ajint*] Score
** @param [r] genome [const AjPSeq] Genomic sequence
** @param [r] gsub [ajint] Genomic start position
** @param [r] gpos [ajint] Genomic end position
** @param [r] est [const AjPSeq] EST sequence
** @param [r] esub [ajint] EST start position
** @param [r] epos [ajint] EST end position
** @param [r] reverse [ajint] Boolean 1=reverse the EST sequence
** @param [r] gapped [ajint] Boolean 1=full gapped alignment
**                         0=display ungapped segment
**
** @return [void]
**
** @release 1.13.0
** @@
******************************************************************************/

static void estWriteMsp(AjPFile ofile, ajint *matches,
			ajint *len, ajint *tsub,
			const AjPSeq genome, ajint gsub, ajint gpos,
			const AjPSeq est,
			ajint esub, ajint epos, ajint reverse, ajint gapped)
{
    float percent;
    ajint goff;
    ajint eoff;

    goff = ajSeqGetOffset(genome);
    eoff = ajSeqGetOffset(est);

    if( *len > 0 )
	percent = (*matches/(float)(*len))*(float)100.0;
    else
	percent = (float) 0.0;

    if(percent > 0)
    {
	if( gapped )
	    ajFmtPrintF( ofile, "Exon     " );
	else
	    ajFmtPrintF( ofile, "Segment  " );

	if(reverse)
	    ajFmtPrintF(ofile, "%5d %5.1f %5d %5d %-12S %5d %5d %-12S  %S\n",
			*tsub, percent, gsub+1, gpos, ajSeqGetNameS(genome),
			eoff+ajSeqGetLen(est)-esub, 
			eoff+ajSeqGetLen(est)-epos+1,
			ajSeqGetNameS(est), ajSeqGetDescS(est) );
	else
	    ajFmtPrintF(ofile, "%5d %5.1f %5d %5d %-12S %5d %5d %-12S  %S\n",
			*tsub, percent, goff+gsub+1, goff+gpos,
			ajSeqGetNameS(genome),
			eoff+esub+1, eoff+epos, ajSeqGetNameS(est),
			ajSeqGetDescS(est) );
    }

    *matches = *len = *tsub = 0;

    return;
}