File: sequence.cc

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (3604 lines) | stat: -rw-r--r-- 108,157 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
/*
Copyright (C) 2006-2008 Keio University
(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)

This file is part of Murasaki.

Murasaki is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Murasaki 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.
*/

//////////////
// murasaki project
// sequence.cc
// provides "sequence" class for doing operations on dna sequences
//////////////

#include "globaltypes.h"
#include "murasaki.h"
#include "sequence.h"
#include "dinkymath.h"
#include "cmultiset.h"
#include "ecohash.h"
#include "murasaki_mpi.h"
#include "seqread.h"
#include "binseq.hh"
#include "scoring.h"
#include "mingw32compat.h"
#include "cryptohasher.h"
#include "openhash.h"
#include "timing.h"
#include "hashing.h"

#include <fstream>
#include <limits.h>
#include <assert.h>
#include <set>
#include <iterator>
#include <functional>
#include <algorithm>
#include <math.h> //need log...
#include <ctype.h> //for tolower <-- im a lazy lazy man
//#include <error.h>
#include <errno.h>
#include <unistd.h>
#include <new>
#include <strings.h> //memcpy

#ifdef USE_SHM_MMAP
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
namespace fs = boost::filesystem;
#endif

#ifdef USE_SHM_SYSV
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#endif

#ifdef USE_LIBCRYPTOPP
#include <cryptopp/misc.h>
#endif

//these guys are used in creating the adaptive hash stuff:
#include <ext/functional>
using namespace __gnu_cxx;

using namespace std;


int next_sequence_=0;
int _wordsize=WORDSIZE;
int hash_bits=27;
word hash_padding=0;
int max_hash_bits=27; //keeps the approx 256mb hash as default (or 515mb on 64bit)
word hash_mask=lowN(hash_bits);
int hash_max=intpow(2,max_hash_bits);
//int hash_max=67108879; //first prime over .5gb/8bytes
//524288057; //arbitrary default. first prime number past .5gb
word hash_size;

word alternating_mask;
word activeHash; //for building hash member lists
word totalSequenceMemory=0;
word sys_pagesize=getpagesize();

//static inits
map<int,int> HashMethod::popmap;

//hasher objects
//if we're scrapping the bottom of the barrel for RAM (or cache performance is suffering), we could use a smaller type here
typedef SBox<unsigned short int> SBoxT;
//typedef SBox<unsigned char> SBoxT;
SBoxT *sbox=0;
CryptoHasher *cryptoHasher=0;

//seqtable bits
Sequence** seq_table;
SeqIdx seq_table_size;
map<Sequence*,SeqIdx> seq2idx;
bool _seq_no_data=false;
double globalBaseFreq[4]={0,0,0,0};
word globalBaseCount[4]={0,0,0,0};
word globalCounted=0;

const SeqPos maxSeqPos=((unsigned)((SeqPos)-1))>>1;

void set_seqtable(vector<Sequence*> seqs){
  seq_table_size = seqs.size();

  seq_table = (Sequence**)malloc(sizeof(Sequence*)*seq_table_size);
  if(seq_table == NULL) { cerr << "set_seqtable(): malloc() failed." << endl; exit(-1); }
  for(SeqIdx i=0; i<seq_table_size; i++){
    seq_table[i] = seqs[i];
    seq2idx[seqs[i]] = i;
  }  
}

void initHashParams(int bits,BitSequence *pat){
  hash_bits=bits;
  hash_mask=lowN(bits);
  hash_size=intpow(2,bits);
  cout << "Using "<<bits<<" hashbits"<<endl;
  srandom(opt.rand_seed);
#ifndef NDEBUG
  srandom(0);
#endif

  hash_padding=random()&hash_mask;

  if(opt.quick_hash==3 && hash_bits<2){
    cerr << "Warning: adaptive hashing doesn't work with less than 2 hashbits."<<endl
	 << "         Using hashfunc 2 instead."<<endl;
    opt.quick_hash=2;
  }

  if(opt.quick_hash>100){
    opt.quick_hash=100;
  }

  switch(opt.quick_hash){
    //nothing to initialize (absurdly naive hashers)
  case 1:case 2:break;
    //adaptive hashers
  case 0:
    pat->compileHashFunc();
    sbox=new SBoxT(hash_bits);
    break;
  case 3:
    pat->compileHashFunc();
    break; 
#ifdef USE_LIBCRYPTOPP
    //cryptographic hash functions
  case 4:cryptoHasher=new MD5CryptoHasher();break;
  case 5:cryptoHasher=new SHACryptoHasher();break;
  case 6:cryptoHasher=new WhirlpoolCryptoHasher();break;
  case 7:cryptoHasher=new CRC32CryptoHasher();break;
  case 8:cryptoHasher=new Adler32CryptoHasher();break;
#endif
  case 100:
    pat->randomHashFunc(opt.randomHashInputs); //for testing only. this is absolutely crazy
    break;
  default:
    assert((cerr << "Bad quick_hash value" << endl) && 0);
    throw MurasakiDebugException("Unknown hash function");
  }
  switch(opt.hashPref){
  case EcoHash_t:
    EcoHash::init(seq_count,longestSeq,totalHashLength,bits);
    break;
  case OpenHash_t:
    OpenHash::init(seq_count,longestSeq,totalHashLength,bits);
    break;
  default: ;
  }
}

void initConstants(){
  srandom(time(0));
  alternating_mask=1;
  //make a mask like 010101010101010101
  for(int bit=2;bit<WORDSIZE;bit<<=1)
    alternating_mask|= (alternating_mask<<bit);
}

inline word revComp8bit(word t){
  switch(t & 255){
#include "revcomptable.cxx"    
  }
  throw MurasakiDebugException("revcomp8bit switch table is broken.");
}

inline word revCompWord(word t){
#if defined(USE_LIBCRYPTOPP) && WORDSIZE == 32
    //  t = ((t & 0xAAAAAAAA) >> 1) | ((t & 0x55555555) << 1);
    t = ((t & 0xCCCCCCCC) >> 2) | ((t & 0x33333333) << 2);
    t = ((t & 0xF0F0F0F0) >> 4) | ((t & 0x0F0F0F0F) << 4);
    return CryptoPP::ByteReverse((CryptoPP::word32)(~t));
#elif defined(USE_LIBCRYPTOPP) && WORDSIZE == 64
    //  t = ((t & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | ((t & W64LIT(0x5555555555555555)) << 1);
    t = ((t & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | ((t & W64LIT(0x3333333333333333)) << 2);
    t = ((t & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | ((t & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
    return CryptoPP::ByteReverse((CryptoPP::word64)(~t));
#else
    //if WORDSIZE isn't 32 or 64, Murasaki will probably break...but
    //for historical raisins (and in case we don't have crypto++), I'll leave this intact:
    word res=0;
    for(int i=0;i<WORDSIZE;i+=8)
      res=(res<<8) | revComp8bit(t>>i);
    return res;
#endif
}

int highestBit(word t){
  for(int i=WORDSIZE-4;i>=0;i-=4){
    switch((t>>i) & (word)15){
    case 1:return i;
    case 2:case 3:return i+1;
    case 4:case 5:case 6:case 7:return i+2;
    case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:
      return i+3;
      //this could be unrolled arbitrarily for performance
    }
  }
  assert(0);
  return -1;//wtf?
}

int lowestBit(word t){
  for(int i=0;i<WORDSIZE;i+=4){
    switch((t>>i) & (word)15){
    case 1:case 3:case 5:case 7: case 9: case 11: case 13: case 15:
      return i;
    case 2:case 6:case 10:case 14:return i+1;
    case 4:case 12:return i+2;
    case 8:return i+3;
      //this could be unrolled arbitrarily for performance
    }
  }
  assert(0);
  return -1;//wtf?
}

int matchCount(word t){ //count whole-base matches
  int count=0;
  for(int i=0;i<WORDSIZE;i+=4){
    switch((t>>i) & (word)15){ //4 bits at a time
    case 3:case 12:count+=1;break;
    case 15:count+=2;break;
    default:break;
    }
  }
  return count;
}

int popCount(word t){
  int count=0;
  for(int i=0;i<WORDSIZE;i+=4){
    switch((t>>i) & (word)15){
    case 1:case 2:case 4:case 8:count+=1;break;
    case 3:case 5:case 6:case 9:case 10:case 12:count+=2;break;
    case 7:case 11:case 13:case 14:count+=3;break;
    case 15:count+=4;
      //this could be unrolled arbitrarily for performance
    }
  }
  return count;
}

SeqPos Sequence::length() const{
  return fwd->length();
}

Sequence::Sequence()
  : 
  fwd(),rev(),seqID(next_sequence_++)
#ifdef USE_SHM_SYSV
  ,sysv_key(-1),sysv_shmid(-1)
#endif
{
}

Sequence::Sequence(string _filename):
  filename(_filename),name(_filename),baseFilename(_filename),
  seqID(next_sequence_++)
#ifdef USE_SHM_SYSV
  ,sysv_shmid(-1)
#endif
{
#ifdef MURASAKI_MPI
  if(mpi_capable){
    word length;
    if(opt.mpi_fileDistro){
      if(mpi_id==0){
	fwd=new BitSequence(this);
	length=(word)fwd->length();
	MPI_Bcast(&length,1,MPI_UNSIGNED_LONG,0,MPI_COMM_WORLD);
	cout << "Distributing "<<filename<<" via MPI"<<endl;
      }else{
	pair<size_t,size_t> range; //rangeSpec wants to use this
	SequenceFileReader::parseRangeSpec(baseFilename,range,opt.seqreadOptions);
	cout << "Waiting for node 0 to finish parsing "<<filename<<endl;
	MPI_Bcast(&length,1,MPI_UNSIGNED_LONG,0,MPI_COMM_WORLD);
	fwd=new BitSequence(length,this);
	cout << "Receiving "<<filename<<" from node 0"<<endl;
      }
    }else{
      fwd=new BitSequence(this);
    }
    //synch str with other procs
    fwd->mpi_distribute();

    cout << "Done with forward strand ("<<fwd->length()<<"bp). Preparing reverse complement..."<<endl;
    rev=fwd->reverseComplement();
  
    if(mpi_usingShm){
      if(!mpi_isHostLeader)
	cout << "Waiting for leader nodes to finish preparing sequence."<<endl;
      MPI_Barrier(MPI_COMM_WORLD);
      if(mpi_isHostLeader)
	cout << "Distributing to listener nodes."<<endl;
      else
	cout << (opt.use_shm_mmap ? "Mapping in shared pages from leader node.":"Finalizing shared region data.")<<endl;
      fwd->shm_distribute();
      rev->shm_distribute();
    }
  }else{
#endif
    fwd=new BitSequence(this);
    cout << "Done with forward strand ("<<fwd->length()<<"bp). Preparing reverse complement..."<<endl;
    rev=fwd->reverseComplement();
#ifdef MURASAKI_MPI
  }
#endif
  cout << "Done."<<endl;
  if(length()<100){
    cout << "Fwd contents:\n"<<*fwd<<endl;
    cout << "Rev contents:\n"<<*rev<<endl;
  }
}

Sequence::Sequence(const Sequence &a):
  filename(a.filename),
  name(a.name),
  fwd(a.fwd),
  rev(a.rev),  seqID(a.seqID)
#ifdef USE_SHM_SYSV
  ,sysv_shmid(a.sysv_shmid)
#endif
{
  assert(cerr << "Alert: Copying sequence: "<<a.name<<endl);
}

Sequence::~Sequence(){
  assert(cerr << "Alert: Destructing "<<name<<endl);
#ifdef USE_SHM_SYSV
  if(opt.use_shm_sysv){
    if(sysv_shmid==-1){//never been used?
      assert(cerr << "Alert: "<<name<<" never got assigned a shared memory region?"<<endl);
    }else{
      if(shmctl(sysv_shmid,IPC_RMID,NULL)<0)
	throw MurasakiException("Couldn't mark System V IPC shared memory region for deletion for sequence "+name+strerror(errno));
    }
  }
#endif
  delete fwd;
  delete rev;
}

//inline int Sequence::getId(){return seqID;}

//inline const vector<word>& BitSequence::words(){return _words;}
int BitSequence::wordsize(){return WORDSIZE;};

inline int BitSequence::readCode(SeqPos bitpos) const {
  word w=readWord(bitpos/WORDSIZE);
  return first2(w<<(MODWORDSIZE(bitpos)));
}

inline BASE_TYPE BitSequence::readBase(SeqPos basepos) const {
  word w=readWord(basepos*2/WORDSIZE);
  return first2(w<<(MODWORDSIZE(basepos*2)));
}

inline word BitSequence::wordAtBase(SeqPos basepos) const {
  SeqPos bitpos=basepos*2;
  word w=readWord(bitpos/WORDSIZE);
  SeqPos offset=MODWORDSIZE(bitpos);
  if(offset){
    //need to shuffle and append next word in place
    return ( (w << offset) |
	     (readWord(bitpos/WORDSIZE+1) >> (WORDSIZE-offset) )
	     );
  }
  return w;  
}

inline word BitSequence::readRawWord(SeqPos wordpos) const{
  return _words[wordpos];
}

word BitSequence::readWord(SeqPos wordpos) const{
  if(wordpos>=(SeqPos)word_count || wordpos<0)
    return 0;
  return (opt.reverseOtf && reverse) ? reverseOtf(wordpos):_words[wordpos];
}

inline word BitSequence::reverseOtf(SeqPos pos) const{
  int bitOffset=MODWORDSIZE(bit_count);
  if(bitOffset){
    if((word)pos<word_count-1){ //if it's not the very last word, it's actually composed of 2 words' data...
      return (revCompWord(_words[word_count-pos-1])<<(WORDSIZE-bitOffset)) |
	(revCompWord(_words[word_count-pos-2])>>(bitOffset));
    }
    else
      return (revCompWord(_words[word_count-pos-1])<<(WORDSIZE-bitOffset)); //last word is a lonely muffin.
  }
  return revCompWord(_words[word_count-pos-1]);
}

void BitSequence::shm_distribute(){
 //no distribution in non-mpi modes
#ifndef MURASAKI_MPI
  throw MurasakiDebugException("Distribute called without MPI support compiled??");
  return;
#else
  if(!mpi_capable)
    throw MurasakiDebugException("Distribute called without MPI enabled??");

  if(!opt.use_shm_sysv && !opt.use_shm_mmap)
    throw MurasakiDebugException("Distribute called without any shared memory modes enabled.");

#ifdef USE_SHM_SYSV
  if(opt.use_shm_sysv){
    if(reverse || !seq)
      return; //no distribution necessary. w00t.

    //on the forward strand
    //however now that we know that everyone has their sequence mapped and attached,
    //if we do the rm on the segment now, we'll prevent memory leaks in a segfaulty disaster
    if(seq->sysv_shmid==-1){//never been used?
      assert(cerr << "Alert: "<<seq->name<<" never got assigned a shared memory region?"<<endl);
    }else{
      if(opt.verbose)cout << "Tagging seq "<<seq->name<<"'s sysv region for deletion."<<endl;
      if(shmctl(seq->sysv_shmid,IPC_RMID,NULL)<0)
	throw MurasakiException("Couldn't mark System V IPC shared memory region for deletion for sequence "+seq->name+strerror(errno));
    }
    return;
  }
#endif
#ifdef USE_SHM_MMAP
  if(opt.use_shm_mmap){
    int fd;
    void *mem;
    const int NFS_Timeout=60;
    fs::path bitFile;
    switch(shmUsed){
    case SHM_MMAP_RW: //nothing, we're done.
      break;
    case SHM_MMAP_RO: //open file and mmap it.
      if(opt.reverseOtf && reverse){
	assert(seq);assert(seq->fwd);assert(seq->fwd->_words);
	_words=seq->fwd->_words; //attach to fwd seq's words, and we're done
	break;
      }
      bitFile=fs::path(genBitFilename());
      for(int trial=0;!fs::exists(bitFile);trial++){
	if(trial+1>NFS_Timeout){
	  throw MurasakiException("Gave up waiting for "+bitFile.string()+" to appear in filesystem.");
	}
	cerr << bitFile.string() << " not found. Waiting for filesystem to catch up..."<<endl;
	sleep(1);
      }
      if((fd=open(bitFile.string().c_str(),O_RDONLY))<0){
	throw MurasakiException("Couldn't open 2bit storage file for reading: "+bitFile.string()+" : "+strerror(errno));
      }
      if((mem=mmap(NULL,word_count*sizeof(word),PROT_READ,MAP_SHARED | MAP_POPULATE,fd,0))==MAP_FAILED){
	throw MurasakiException("Failed mapping listener block: "+string(strerror(errno)));
      }
      _words=(word*)mem;
      break;
    default:
      assert(cerr << "Don't have a shm mode assigned??"<<endl &&  0);
    }

    return;
  }
#endif
  throw MurasakiDebugException("BitSequence::shm_distribute called without shared memory support compiled");
  return;
#endif
}

void BitSequence::mpi_distribute(){
#ifdef MURASAKI_MPI
  if(mpi_capable){
    assert(_words);
    if(opt.mpi_fileDistro){
      word *start=_words;
      word sent=0;
      if(mpi_isHostLeader){ //leaders only!
	Stopwatch filesend;
	filesend.start();
	while(sent<word_count){
	  word block=min<word>(word_count-sent,INT_MAX>>1); //silly MPI specifies transmission count in ints...
	  cout << (mpi_id==0 ? "Sending a ":"Receiving a ")<<humanMemory(block*sizeof(word))<<" block."<<endl;
	  MPI_Bcast(start+sent,block,MPI_UNSIGNED_LONG,0,mpi_leaders_comm);
	  sent+=block;
	  cout << percent((double)sent,(double)word_count) << (mpi_id==0 ? " sent":" received")<<endl;
	}
	filesend.stop();
	if(opt.verbose)
	  cout << "Data distributed in "<<filesend<<" ("<<humanMemory(((double)(word_count)*sizeof(word))/filesend.asDouble())<<"/s)"<<endl;
      }else
	cout << "My leader's receiving a copy of the sequence for me."<<endl;
    }

    //and distribute meta-data!
    if(opt.mpi_fileDistro || mpi_usingShm){
      cout << "Synchronizing sequence meta-data:"<<endl;
      matchRegions.worldSync();
      subSeqs.worldSync();
    }
  }else
#endif
    throw MurasakiDebugException("BitSequence::mpi_distribute called without MPI support!");
}

string BitSequence::genBitFilename(){
  assert(seq);
  assert(!seq->filename.empty());
  return seq->filename+string(reverse ? ".2bit.rev":".2bit.fwd")+string(opt.repeatMask ? ".repeatmasked":"");
}

string baseToString(BASE_TYPE b){
  switch(b){
  case BASE_A:return "A";break;
  case BASE_C:return "C";break;
  case BASE_G:return "G";break;
  case BASE_T:return "T";break;
  case BASE_N:return "N";break;
  default: return "*";break;
  }
}

string bitToString(word w){
  switch(w & (word)3){
  case 0:return "A"; break;
  case 1:return "C"; break;
  case 2:return "G"; break;
  case 3:return "T"; break;
  }
  return " ";
}

string wordToString(word w,int bits){
  string ret;
  int start=bits < 0 ? bits+WORDSIZE:0;
  for(int i=start;i<WORDSIZE;i+=2)
    switch(first2(w<<i)){
    case 0:ret+="A"; break;
    case 1:ret+="C"; break;
    case 2:ret+="G"; break;
    case 3:ret+="T"; break;
    }
  return ret;
}

string wordToPattern(word w,int bits){
  string ret;
  for(int i=0;i<bits;i+=2)
    switch(first2(w<<i)){
    case 0:ret+="0"; break;
    case 1:ret+="-"; break;
    case 2:ret+="x"; break;
    case 3:ret+="1"; break;
    }
  return ret;
}

string repString(string s,int count){
  if(count<1)
    return string();
  string r=s;
  while(--count)
    r+=s;
  return r;
}

string BitSequence::asString() const {
  string ret;

  if(seq){
    SeqPos i=0;
    int li=0;
    BaseIterator b(seq,reverse ? -1:1);
    while(i<_length){
      if(li==0){
	char buf[50];
#ifdef LARGESEQ_SUPPORT
	sprintf(buf,"%4ld ",i+1);
#else
	sprintf(buf,"%4d ",i+1);
#endif
	ret+=buf;
      }
      ret+=baseToString(*b);
      ++b;
      i++;
      if(i%(WORDSIZE/2)==0)
	ret+=" ";
      li++;
      if(li>=64){
	ret+="\n";
	li=0;
      }
    }
  } else {
    const int wordsPerLine=(80/WORDSIZE*2);
    for(word i=0;i<word_count;i++){
      if(i%wordsPerLine==0){
	char buf[50];
	sprintf(buf,"%4lu ",i*WORDSIZE/2+1);
	ret+=buf;
      }
      
      string seg=wordToString(readWord(i));
      if(i>=word_count-1)
	seg.resize((((bit_count-1)%WORDSIZE)+1)/2);
      ret+=seg;
      
      
      if(i<word_count-1 && (i+1)%wordsPerLine==0)
	ret+="\n";
      else
	ret+=" ";
    }
  }
  return ret;
}

string BitSequence::asPattern() const {
  string ret;
  for(word i=0;i<word_count;i++){
    if(i%(80/WORDSIZE*2)==0){ //used to be i%4 but that looks weird on hpc
      char buf[50];
      sprintf(buf,"%4lu ",i*WORDSIZE/2+1);
      ret+=buf;
    }
    ret+=wordToPattern(readWord(i),i<word_count-1 ? WORDSIZE:
		      ((bit_count-1)%WORDSIZE)+1);
    if(i<word_count-1 && (i+1)%(80/WORDSIZE*2)==0)
	ret+="\n";
      else
	ret+=" ";
  }
  return ret;
}

int BitSequence::compHashLength(){
  int count=0;
  for(word i=0;i<word_count;i++){
    count+=popCount(readWord(i))/2;
  }
  _hashLength=count;
  return count;
}

//operator
SeqPos BitSequence::cmpRight(SeqPos base_pos,BitSequence& target,SeqPos base_targetPos){
  if(base_pos>=_length || base_targetPos>=target._length)return 0; //no can do, mack
  SeqPos pos=2*base_pos;//to bitspace
  SeqPos targetPos=2*base_targetPos;

  SeqPos myOffset=MODWORDSIZE(pos),tOffset=MODWORDSIZE(targetPos);
  word myFrame=pos/WORDSIZE,tFrame=targetPos/WORDSIZE;
  word myWord=readWord(myFrame),myNext=readWord(myFrame+1);
  word tWord=target.readWord(tFrame),tNext=target.readWord(tFrame+1);

  SeqPos max=min<SeqPos>(spaceRight(base_pos),target.spaceRight(base_targetPos));
  //  assert(cout << "local Spaceright: "<<spaceRight(base_pos)<< " target spaceright: "<< target.spaceRight(base_targetPos)<<endl);
  //  assert(cout << "Valid range: "<<(base_pos)<<","<<(base_pos+max)<<endl);
  if(!max)return 0; //if dead, die
  SeqPos matched=0;
  while(myFrame<word_count && tFrame<target.word_count){
    if(myOffset)
      myWord=(myWord<<myOffset) | ((myNext>>(WORDSIZE-myOffset)));
    if(tOffset)
      tWord=(tWord<<tOffset) | ((tNext>>(WORDSIZE-tOffset)));
    word res=(tWord ^ myWord);
    //    assert(cout << "Cmp right -> "<<wordToString(myWord)<<" to "<<wordToString(tWord) << " = "
    //	   << wordToString(res) << endl);
    if(res){ //sucky, not a whole match
      SeqPos highest=highestBit(res);
      matched+=WORDSIZE/2-1-(highest/2);
      break; //game over man, game over!
    }
    else
      matched+=WORDSIZE/2;
    
    myFrame++;tFrame++;
    myWord=myNext;myNext=readWord(myFrame+1);
    tWord=tNext;tNext=target.readWord(tFrame+1);
  }
  assert(matched>=0);
  if(matched>=max)
    matched=max;
  assert(matched>=0);
  return matched;
}

SeqPos BitSequence::cmpLeft(SeqPos base_pos,BitSequence& target,SeqPos base_targetPos){
  if(base_pos < 0 || base_targetPos < 0)return 0; //no can do, mack
  SeqPos pos=2*(base_pos);//to bitspace
  SeqPos targetPos=2*(base_targetPos);
  SeqPos myOffset=MODWORDSIZE(pos+2),tOffset=MODWORDSIZE(targetPos+2);
  SeqPos myFrame=pos/WORDSIZE,tFrame=targetPos/WORDSIZE;
  word myWord=readWord(myFrame),myNext=readWord(myFrame-1);
  word tWord=target.readWord(tFrame),tNext=target.readWord(tFrame-1);

  SeqPos max=min<SeqPos>(spaceLeft(base_pos),target.spaceLeft(base_targetPos));
  if(!max)return 0; //if dead, die
  SeqPos matched=0;
  while(myFrame>=0 && tFrame>=0){
    //    cout << "myOffset: "<<myOffset<<" tOffset: "<<tOffset<<endl;
    //    cout << "*Slice: "<<wordToString(myWord>>(WORDSIZE-myOffset)) << " | " << wordToString(myNext<<myOffset) << endl;
    //    cout << "& Dice: "<<wordToString(tWord) << " | "<< wordToString(tNext)<<endl;
    if(myOffset)
      myWord=(myWord>>(WORDSIZE-myOffset)) | ((myNext<<(myOffset)));
    if(tOffset)
      tWord=(tWord>>(WORDSIZE-tOffset)) | ((tNext<<(tOffset)));
    word res=(tWord ^ myWord);
    //    assert(cout << "Cmp Left <- "<<wordToString(myWord)<<" to "<<wordToString(tWord) << " = "
    //    	   << wordToString(res) << endl);
    if(res){ //sucky, not a whole match
      SeqPos highest=lowestBit(res);
      matched+=(highest/2);
      break; //game over man, game over!
    }
    else
      matched+=WORDSIZE/2;
    
    myFrame--;tFrame--;
    myWord=myNext;myNext=readWord(myFrame-1);
    tWord=tNext;tNext=target.readWord(tFrame-1);
  }
  assert(matched>=0);
  if(matched>=max)
    matched=max;
  assert(matched>=0);
  return matched;
}

bool BitSequence::equal(SeqPos pos,BitSequence& target,SeqPos targetPos,BitSequence& patt){
  pos*=2;//to bitspace
  targetPos*=2; 
  SeqPos myOffset=MODWORDSIZE(pos),tOffset=MODWORDSIZE(targetPos);
  word myMask=highN(myOffset),tMask=highN(tOffset);
  word myFrame=pos/WORDSIZE,tFrame=targetPos/WORDSIZE;
  word myWord=readWord(myFrame),myNext=readWord(myFrame+1);
  word tWord=target.readWord(tFrame),tNext=readWord(tFrame+1);

  word pFrame=0;
  word pWord;

  SeqPos matched=0;
  while(myFrame<word_count && tFrame<target.word_count && pFrame<patt.word_count){
    pWord=patt.readWord(pFrame%patt.word_count); //pattern just loops for now
    if(myOffset)
      myWord=(myWord<<myOffset) | (myNext<<myOffset & ~myMask);
    if(tOffset)
      tWord=(tWord<<tOffset) | (tNext<<tOffset & ~tMask);
    word res=(tWord ^ myWord) & pWord;
    if(res){ //sucky, not a whole match
      SeqPos highest=highestBit(tWord);
      if(highest>=0) //partial match
	matched+=highest/2+1;
      break; //game over man, game over!
    }
    else
      matched+=WORDSIZE/2;
    
    myFrame++;tFrame++;pFrame++;
    myWord=myNext;myNext=readWord(myFrame+1);
    tWord=tNext;tNext=readWord(tFrame+1);
  }
  return matched>=patt._length;
}

pair<SeqPos,SeqPos>* Location::localRegion(){ 
  //  cout << "Converting pos "<<pos<<" on "<<seqno<<" into a region.\n";
  return (pos>0 ? seq()->fwd->localRegion(pos-1):seq()->rev->localRegion(seq()->length()+pos));
}

SeqPosPairArray::iterator Location::localRegionIte(){ //find region local to pos
  //  cout << "Converting "<<(*this)<<" into a local region. pos is "<<pos;
  SeqPos bitseqp=(pos>0 ? pos:0-pos)-1;
  //  cout << ", but bitseqp is "<<bitseqp<<endl;
  SeqPosPairArray &regions=bitSeq()->matchRegions;
  pair<SeqPos,SeqPos> target(bitseqp,bitseqp); //for simplicity

  SeqPosPairArray::iterator
    result=lower_bound(regions.begin(),regions.end(),target,ltRegion());
  if(result==regions.end() || bitseqp<result->first){
    if(result==regions.end())assert(cout << "bitseqp "<<bitseqp << " not in any region"<<endl && 0);
    if(bitseqp<result->first)assert(cout << "bitseqp "<<bitseqp<<" falls before start of next region"<<endl && 0);
    return regions.end();
  }
  //  assert(cout << "region found: "<<result->first<<","<<result->second<<endl);
  return result;
}

pair<SeqPos,SeqPos>* BitSequence::localRegion(SeqPos pos){ //find region local to pos
  pair<SeqPos,SeqPos> target(pos,pos); //for simplicity
  SeqPosPairArray::iterator
    result=lower_bound(matchRegions.begin(),matchRegions.end(),target,ltRegion());
  if(result==matchRegions.end()){
    //    assert(cout << "pos "<<pos << " not in any region"<<endl);
    return 0;
  }
  if(pos<result->first){
    //    assert(cout << "pos "<<pos<<" falls before start of next region"<<endl);
    return 0;
  }
  //  assert(cout << "region found: "<<result->first<<","<<result->second<<endl);
  return &(*result);
}

SeqPosPairArray::iterator BitSequence::localRegionIte(SeqPos pos){ //find region local to pos
  pair<SeqPos,SeqPos> target(pos,pos); //for simplicity

  SeqPosPairArray::iterator
    result=lower_bound(matchRegions.begin(),matchRegions.end(),target,ltRegion());
  return result;
}

SeqPos BitSequence::spaceRight(SeqPos pos){ //find region local to pos
  pair<SeqPos,SeqPos> target(pos,pos); //for simplicity
  pair<SeqPos,SeqPos> *region(localRegion(pos));
  if(!region){
    return 0;
  }
  return region->second-pos+1;
}

SeqPos BitSequence::spaceLeft(SeqPos pos){ //find region local to pos
  pair<SeqPos,SeqPos> target(pos,pos); //for simplicity
  pair<SeqPos,SeqPos> *region(localRegion(pos));
  if(!region){
    return 0;
  }
  return pos-region->first+1;
}

UsedInt BitSequence::subSeqBounds(SeqPos at){
  pair<SeqPos,SeqPos> target(at,at);
  SeqPosPairArray::iterator
    result=lower_bound(subSeqs.begin(),subSeqs.end(),target,ltRegion());
  assert(result!=subSeqs.end());
  assert(result->first<=at);
  return UsedInt(result->first,result->second);
}

UsedInt Sequence::getSubSeqBounds(SeqPos at){
  UsedInt subSeqBounds((at>0 ? fwd:rev)->subSeqBounds(bitSeqCoords(at)));
  if(at<0)
    swap<SeqPos>(subSeqBounds.start,subSeqBounds.stop);
  return seqCoords(subSeqBounds,at); //coordinate system insanity!
}

UsedInt Sequence::growInBounds(const UsedInt &basis,SeqPos amount){
  UsedInt bounds(getSubSeqBounds(basis.start));
  return UsedInt(max<SeqPos>(bounds.start,basis.start-amount),min<SeqPos>(bounds.stop,basis.stop+amount));
}

BaseIterator Sequence::iterate(SeqPos at){
  return BaseIterator(this,at);
}

pair<BaseIterator,BaseIterator> Sequence::iterate(const UsedInt &at){
  pair <BaseIterator,BaseIterator> r(BaseIterator(this,at.start),BaseIterator(this,at.stop));
  if(at.start<0)
    swap(r.first,r.second);
  return r;
}

//mutator
void BitSequence::invert(){ //flips to reverse comp sequence
  for(word i=0;i<word_count;i++){
    _words[i]= ~_words[i];
  }
  //last word is tricky. all trailing elements have to be C in order
  //to not screw up dumb hashing techniques
  SeqPos last=word_count-1;
  _words[last]=_words[last] & highN(MODWORDSIZE(bit_count));
}

word* BitSequence::allocWords(){
  word *mem;
  assert(!_words); //better not already have words allocated....!
  if(opt.verbose)cout << "Allocing words...";

  if(reverse && opt.reverseOtf){
    assert(seq);assert(seq->fwd);assert(seq->fwd->_words);
    if(opt.verbose)cout << "as mirror of fwd"<<endl;
    return seq->fwd->_words; //shares the same data, and we're done.
  }

#ifdef MURASAKI_MPI
#ifdef USE_SHM_SYSV
  if(opt.use_shm_sysv && seq){
    if(opt.verbose)cout << "using sysv";
    size_t size=word_count*sizeof(word);
    if(!opt.reverseOtf)
      size*=2;//fetch double the size because we're storing both fwd and rev in there
    //sysv segments are ephemereal and local to this mpi set, so we just use the filename as our key
    shmUsed=SHM_SYSV;
    if(reverse){
      assert(seq->fwd->_words); //MUST allocate fwd before rev.
      if(opt.verbose)cout << " (continued from fwd allocation)"<<endl;
      return seq->fwd->_words+word_count; //second half of block
    }
    if(opt.verbose)cout << " (new segment)"<<endl;
    //ok, going to create a new segment
#ifdef SYSV_KEYBYFILE
    //I can't think of any reasonable reason why this method would be preferred. We'll call this "deprecated"
      if((seq->sysv_key=ftok(seq->baseFilename.c_str(),mpi_sysv_projid))==-1)
	throw MurasakiException("Error generating System V IPC key for "+string(seq->filename)+": "+strerror(errno));
    if((seq->sysv_shmid=shmget(seq->sysv_key,size,IPC_CREAT | 00600))==-1)
      throw MurasakiException("Error creating System V IPC shared memory segment (size: "+humanMemory(size)+") for "+string(seq->filename)+": "+strerror(errno));
#else
      //create a unique key by magics
      if(mpi_myLocalRank==0){
	if((seq->sysv_shmid=shmget(IPC_PRIVATE,size,IPC_CREAT | 00600))==-1)
	  throw MurasakiException("Error creating System V IPC shared memory segment (size: "+humanMemory(size)+") for "+string(seq->filename)+": "+strerror(errno));
      }
      MPI_Bcast(&seq->sysv_shmid,sizeof(key_t),MPI_BYTE,0,mpi_localhost_comm);
#endif
    if((mem=(word*)shmat(seq->sysv_shmid,NULL,mpi_isHostLeader ? O_RDWR:(O_RDONLY | SHM_RDONLY)))==(void*)-1)
      throw MurasakiException("Error attaching to System V IPC shared memory segment for "+string(seq->filename)+strerror(errno));
    cout << "Mapped a "<<humanMemory(size)<<" sysv chunk (key: "<<dhstring(seq->sysv_key)<<" shmid: "<<seq->sysv_shmid<<")"<<endl;

    if(shmctl(seq->sysv_shmid,IPC_RMID,NULL)<0)
      throw MurasakiException("Couldn't mark System V IPC shared memory region for deletion for sequence "+seq->name+strerror(errno));

    if(mpi_isHostLeader) //keep track of how much mem is lost to sequence storage
      totalSequenceMemory+=((((size-1)/sys_pagesize)+1)*sys_pagesize)/1024;
    return mem; //wee. done. much cleaner than mmap.
  }
#endif
#ifdef USE_SHM_MMAP
  if(opt.use_shm_mmap && seq){
    if(opt.verbose)cout << "using mmap"<<endl;
    if(opt.reverseOtf && reverse){
      assert(seq);assert(seq->fwd);
      shmUsed=SHM_MMAP_RO; //we'll pretend to be RO.
      return 0; 
    }
    //prepare to write my bitsequence to file if needed
    fs::path bitFile(genBitFilename());
    bool freshen=(!fs::exists(bitFile) || fs::last_write_time(bitFile)<fs::last_write_time(seq->filename));
    int fd; //actually we never need this again...
    if(freshen && ((opt.mmap_writePerHost && mpi_hostLeader[mpi_id]==mpi_id) ||
		   (mpi_id==0))){
      cerr << "Writing 2bit data out to file..."<<endl;
      fd=open(bitFile.string().c_str(),O_RDWR | O_CREAT | O_TRUNC | O_NOCTTY,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); //create and/or trunc
      if(fd<0)
	throw MurasakiException("Couldn't create 2bit storage file: "+bitFile.string()+" : "+strerror(errno));
      //make file big enough to fit our sequence
      lseek(fd,word_count*sizeof(word)-1,SEEK_SET);
      write(fd,"",1); //write a byte.
      mem=(word*)mmap(NULL,word_count*sizeof(word),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
      if(mem==MAP_FAILED){
	int mmap_error=errno;
	throw MurasakiException("Failed mapping initial block: "+string(strerror(mmap_error)));
      }
      totalSequenceMemory+=((word_count*sizeof(word))/(sys_pagesize-1)*sys_pagesize/1024);
      shmUsed=SHM_MMAP_RW;
    }else{
      //don't write just load from file when distribute is called.
      mem=0;
      shmUsed=SHM_MMAP_RO;
    }
    return mem;
  }
#endif
#endif
  mem=new word[word_count];
  totalSequenceMemory+=(word_count*sizeof(word));

  if(opt.verbose)cout << "directly"<<endl;
  return mem;
}

//init
void BitSequence::initPattern(const string &str){
  _hashLength=0;
  _length=str.length();
  bit_count=_length*2;
  word_count=((bit_count+WORDSIZE-1)/(WORDSIZE)); //rounds up to nearest full word
  assert(_words==0);
  _words=allocWords();
  bool writeWords=_words;
  word wordsStored=0;
  hasher=0;
  SeqPos bit=WORDSIZE;
  word w=0;
  pair<SeqPos,SeqPos> region(0,0);
  for(SeqPos i=0;i<_length;i++){
    bit-=2;
    SeqPos inpi=reverse ? (_length-i-1):i;
    switch(str[inpi]){
    case '1': w|=((word)3<<bit);isPattern=true;_hashLength++;break;
    case '0':isPattern=true;break;
    default: throw MurasakiException("Invalid pattern character (dec:"+dstring(inpi)+" char: "+str[inpi]+") encountered at position "+dstring(inpi));
    }

    if(bit==0){
      if(writeWords)
	_words[wordsStored++]=(reverse ? ~w:w);
      bit=WORDSIZE;
      w=0;
    }
  }

  if(bit<WORDSIZE)
    _words[wordsStored++]=highN(WORDSIZE-bit) & (reverse ? ~w:w);
}

BitSequence::BitSequence(Sequence* s):
  shmUsed(SHM_NONE),
  _hashLength(0),
  isPattern(false),
  seq(s),_words(0),
  reverse(false),
  counted(0)
{
  Stopwatch seqLoadTime;
  seqLoadTime.start();

  try {
    if(opt.useSeqBinary){
      try {
	cout << "Loading "<<s->filename<<endl;
	SequenceBinary binseq(s->filename);
	loadBinary(binseq);
      }catch(SeqReadException e){
	if(opt.verbose)
	  cerr << "Binary load failed ("<<e.reason()<<")."<<endl
	       <<"Parsing "<<s->filename<<" directly"<<endl;
	try {
	  SequenceFileReader reader(s->filename,opt.seqreadOptions);
	  SequenceBinary binseq(reader);
	  loadBinary(binseq);
	  if(!binseq.save())
	    cerr << "#Warning: Save of binary sequence to "<<binseq.getBinaryFilename()<<" failed";
	}catch(SeqReadException e){
	  throw MurasakiException("Error reading "+s->filename+": "+e.reason());
	}
      }
    }else{
      cout << "Parsing "<<s->filename<<" directly"<<endl;
      SequenceFileReader reader(s->filename,opt.seqreadOptions);
      loadReader(reader);
    }
  }catch(SeqReadException e){
    throw MurasakiException("Error reading "+s->filename+": "+e.reason());
  }

  seqLoadTime.stop();

  if(counted<1)
    throw MurasakiException("Murasaki can't use empty sequences ("+s->filename+")");

  cout << "Read "<<counted<<"bp ("<<humanMemory(counted)<<"p) in "<<seqLoadTime<<" ("<<humanMemory((double)counted/seqLoadTime.asDouble())<<"p/s)"<<endl;
}

void BitSequence::loadBinary(const SequenceBinary &binseq){
  hasher=0;
  _length=binseq.length();
  bit_count=_length*2;
  word_count=((bit_count+WORDSIZE-1)/(WORDSIZE)); //rounds up to nearest full word
  _words=allocWords();
  bool writeWords=_words;
#ifdef MURASAKI_MPI
  if(seq && mpi_capable && !mpi_isHostLeader)
    writeWords=false;
#endif

  if(writeWords){
    memcpy(_words,binseq.words(),binseq.getWordCount()*sizeof(word));
  }
  
  const int srcMatchRegionsIdx=opt.repeatMask ? 2:1;
  subSeqs.resize(binseq.regionSizes[0]);
  matchRegions.resize(binseq.regionSizes[srcMatchRegionsIdx]);
  assert(sizeof(SequenceBinary::Region)==sizeof(SeqPosPair));
  memcpy(&matchRegions.front(),binseq.regions[srcMatchRegionsIdx],sizeof(SequenceBinary::Region)*binseq.regionSizes[srcMatchRegionsIdx]);
  memcpy(&subSeqs.front(),binseq.regions[0],sizeof(SequenceBinary::Region)*binseq.regionSizes[0]);
  
  //grab base frequency
  for(int b=0;b<4;b++){
    word count=binseq.counters[b]-(opt.repeatMask ? binseq.counters[4+b]:0);
    globalBaseCount[b]+=count;
    counted+=count;
  }
  globalCounted+=counted;

#ifdef USE_SHM_MMAP
  if(shmUsed==SHM_MMAP_RW)
    mmap_msync();
#endif
}

void BitSequence::loadReader(SequenceFileReader& reader)
{
  hasher=0;
  _length=reader.peekLength();
  bit_count=_length*2;
  word_count=((bit_count+WORDSIZE-1)/(WORDSIZE)); //rounds up to nearest full word
  _words=allocWords();
  bool writeWords=_words;
#ifdef MURASAKI_MPI
  if(seq && mpi_capable && !mpi_isHostLeader)
    writeWords=false;
#endif
  word wordsStored=0;
  SeqPos counters[4]={0,0,0,0};
  SeqPos bit=WORDSIZE;
  word w=0;
  bool inRegion=false;
  bool matchable=false;
  pair<SeqPos,SeqPos> region(0,0),subSeqBounds(0,0);
  long prevSubSeqId=reader.getSubSeqId();
  for(SeqPos i=0;i<_length;i++){
    bit-=2;
    char c=reader.getc();
    switch(c){
    case 'A':case 'a': counters[0]++;counted++;matchable=true;break;
    case 'C':case 'c': w|=((word)1<<bit);counters[1]++;counted++;matchable=true;break;
    case 'G':case 'g': w|=((word)2<<bit);counters[2]++;counted++;matchable=true;break;
    case 'T':case 't': w|=((word)3<<bit);counters[3]++;counted++;matchable=true;break;
    case 'N':case 'n': matchable=false; break;
    case 0: //eof
      throw MurasakiDebugException("Fewer characters in stream than predicted ("+dstring(i)+" read vs "+dstring(_length)+") predicted!");
    default: throw MurasakiException("Unusable character (dec:"+dstring(c)+" char: "+c+") encountered at position "+dstring(i));
    }
    if(inRegion){ //in a matchable zone
      if(!matchable){//region end!
	region.second=i-1;
	inRegion=!inRegion;
	matchRegions.push_back(region);
      }
    }else{ //was in an N zone
      if(matchable){//region start
	region.first=i;
	inRegion=!inRegion;
      }
    }

    if(reader.getSubSeqId()!=prevSubSeqId){ //subseq changed!
      subSeqBounds.second=i-1;
      assert(subSeqBounds.second>=subSeqBounds.first);
      subSeqs.push_back(subSeqBounds);
      
      subSeqBounds.first=i+10; //this looks a bit hinky, but between every subseq there _should_ be exactly 10 Ns, so this accounts for that
      assert(c=='N'); //see? we're looking at an N!
      prevSubSeqId=reader.getSubSeqId();
    }

    if(bit==0){
      if(writeWords)
	_words[wordsStored++]=(reverse ? ~w:w);
      bit=WORDSIZE;
      w=0;
    }
  }

  if(inRegion){
    region.second=_length-1;
    matchRegions.push_back(region);
  }
  
  //finish up last subseq
  subSeqBounds.second=_length-1;
  assert(subSeqBounds.second>=subSeqBounds.first);
  subSeqs.push_back(subSeqBounds);

  if(bit<WORDSIZE)
    if(writeWords){
      _words[wordsStored++]=highN(WORDSIZE-bit) & (reverse ? ~w:w);
    }
  if(writeWords){
    assert(wordsStored==word_count);
    cout << "Collected "<<wordsStored<<" words (size: "<<word_count<<")"<<endl;
  }
  else {
    cout << "Postponed loading of "<<word_count<<" words (will fetch them directly later)"<<endl;
  }
  //set base frequency
  globalCounted+=counted;
  for(int b=0;b<4;b++){
    globalBaseCount[b]+=counters[b];
    //    globalBaseFreq[b]+=(double)counters[b]/(double)counted/2;
  }

#ifdef USE_SHM_MMAP
  if(shmUsed==SHM_MMAP_RW)
    mmap_msync();
#endif
}

BitSequence::BitSequence(const word length,Sequence *s,bool _reverse) :
  shmUsed(SHM_NONE),
  _length(length),bit_count(length*2),
  word_count((bit_count+WORDSIZE-1)/(WORDSIZE)), //rounds up to nearest full word)
  _hashLength(0),isPattern(false),
  seq(s),
  _words(0),
  reverse(_reverse),
  counted(0)
{
  _words=allocWords();
}

BitSequence* BitSequence::reverseComplement(){
  BitSequence* rev=new BitSequence(_length,seq,!reverse);
  bool writeWords=!opt.reverseOtf;
#ifdef MURASAKI_MPI
  if(seq && mpi_capable && !mpi_isHostLeader)
    writeWords=false;
#endif
  if(writeWords){
    int bitOffset=MODWORDSIZE(bit_count);
    for(word *src=_words+word_count-1,*dst=rev->_words;src>=_words;--src,++dst){
      *dst=revCompWord(*src);
      if(bitOffset){//have to shuffle bits
	if(dst!=rev->_words){ //if this wasn't my first, i have to fix the one before me too
	  *(dst-1)|=*dst>>bitOffset;
	}
	*dst<<=WORDSIZE-bitOffset;
      }
    }

    //and if we're doing the mmap grunt work, we have to write this out.
#ifdef USE_SHM_MMAP
    if(shmUsed==SHM_MMAP_RW && !opt.reverseOtf)
      rev->mmap_msync();
#endif
  }

  //have to flip regions too
#ifdef MURASAKI_MPI
  if(!(matchRegions.hasShm() && mpi_myLocalRank!=0)){
#endif
    cout << " <-> Reversing metdata." << endl;
    rev->matchRegions.reserve(matchRegions.size());
    //    cout << "(Filling "<<rev->matchRegions.size()<<" / "<<rev->matchRegions.capacity()<<" array with "<<matchRegions.size()<<" "<<sizeof(SeqPosPair)<<" elems"<<endl; 
    for(SeqPosPairArray::iterator i=matchRegions.begin();i!=matchRegions.end();++i){
      //      cout << "((Adding #"<<rev->matchRegions.size()<<" == #"<<(i-matchRegions.begin())<<" ~ "<<i->first<<","<<i->second<<endl;
      rev->matchRegions.push_back(pair<SeqPos,SeqPos>(_length-i->second-1,_length-i->first-1));
    }
    //    cout << "(Reversing array of "<<rev->matchRegions.size()<<" at "<<(void*)(&(*rev->matchRegions.begin()))<<" ending "<<(void*)(&(*rev->matchRegions.end()))<<endl;
    std::reverse(rev->matchRegions.begin(),rev->matchRegions.end()); //oops. i eclipsed std::reverse with my variable name.
    
    //and subsequences
    rev->subSeqs.reserve(subSeqs.size());
    for(SeqPosPairArray::iterator i=subSeqs.begin();i!=subSeqs.end();++i)
      rev->subSeqs.push_back(pair<SeqPos,SeqPos>(_length-i->second-1,_length-i->first-1));
    std::reverse(rev->subSeqs.begin(),rev->subSeqs.end()); //oops. i eclipsed std::reverse with my variable name.
#ifdef MURASAKI_MPI
  }
  if(matchRegions.hasShm()){
    rev->matchRegions.localSync();
    rev->subSeqs.localSync();
  }
#endif

  globalCounted+=counted; //add this to globalCounted or we'll get confused about our sequence lengths.
  return rev;
}

void BitSequence::mmap_msync(){
#ifdef USE_SHM_MMAP
  assert(shmUsed==SHM_MMAP_RW);
  cout << "Flushing mmap'd region to disk."<<endl;
  int res=msync(_words,word_count*sizeof(word),MS_SYNC);
  if(res<0){
    int err=errno;
    throw MurasakiException(string("Error synching mmap'd sequence to disk")+string(strerror(err)));
  }
#else
  throw MurasakiDebugException("mmap_msync called without mmap support??");
#endif
}

void finishGlobalFrequencies(){
  const char *forwardBases[4]={"A","C","G","T"};
  const char *bases[4]={"A/T","C/G","G","T"};
  cout << "Forward frequencies:";
  word baseTotal=0;
  for(int b=0;b<4;b++)baseTotal+=globalBaseCount[b];
  for(int b=0;b<4;b++)
    cout << "  "<<forwardBases[b]<<":"<<(double)globalBaseCount[b]/(double)baseTotal*100<<"%";
  cout << endl;
  for(int b=0;b<2;b++){
    globalBaseFreq[b]=((double)(globalBaseCount[b]+globalBaseCount[3-b]))/(double)baseTotal;
    globalBaseFreq[3-b]=globalBaseFreq[b];
  }
  cout << "Global base frequencies:";
  for(int b=0;b<2;b++){
    cout << "  "<< bases[b] << ":" << globalBaseFreq[b]*100 << "%";
  }
  cout << endl;
}

void BitSequence::init(const BitSequence& a){
  _words=a._words;
  word_count=a.word_count;
  bit_count=a.bit_count;
  _length=a._length;
  _hashLength=a._hashLength;
  hasher=a.hasher;
}

//constructors
BitSequence::BitSequence(const string &str):
  shmUsed(SHM_NONE),isPattern(false),
  seq(NULL),
  _words(0),reverse(false),
  counted(0)
{ //from 0101-ish patterns (as mask: ie double each bit)
  initPattern(str);
}

BitSequence::BitSequence(const BitSequence& a) :  //copy
  matchRegions(a.matchRegions),
  subSeqs(a.subSeqs),
  shmUsed(a.shmUsed),
  _length(a._length),
  bit_count(a.bit_count),
  word_count(a.word_count),
  _hashLength(a._hashLength),
  isPattern(a.isPattern),
  seq(a.seq),
  _words(a._words),
  reverse(a.reverse),
  counted(a.counted),
  hasher(a.hasher)
{
  assert(cerr << "Alert: Copying a bitsequence."<<endl);
}

BitSequence::BitSequence() : //uninited
  _length(0),
  bit_count(0),word_count(0),
  _hashLength(-1),isPattern(false),seq(0),_words(0),reverse(false),
  counted(0)
{}

BitSequence::~BitSequence() {
  if(_words){  //if a sequence got inited and never used, it's possible it didn't get _words
    if(reverse && opt.reverseOtf)return; //not our job to cleanup.
    switch(shmUsed){
    case SHM_NONE:
      delete[] _words;
      break;
    case SHM_MMAP_RO:case SHM_MMAP_RW:
#ifdef USE_SHM_MMAP
      munmap(_words,word_count*sizeof(word));
#endif
      break;
    case SHM_SYSV:
#ifdef USE_SHM_SYSV
      if(reverse)
	break; //nothing to do. w00t!
      //not really critical, but we can detach the sysv pages...
      if(shmdt(_words)<0)
	throw MurasakiException("Couldn't detach System V shared memory region for "+(seq ? seq->filename:string("(anon)"))+strerror(errno));
#endif
      break;
    default:
      assert(cerr << "Impossible case." << endl && 0);
    }
  }
}

int HashMethod::maxSources(){
  vector<int> members;
  vector<int> tmp;
  transform(inputs.begin(),inputs.end(),back_insert_iterator<vector<int> >(tmp),select1st<pair<int,int> >());
  sort(tmp.begin(),tmp.end());
  unique_copy(tmp.begin(),tmp.end(),back_insert_iterator<vector<int> >(members));
  int score=0;
  for(vector<int>::iterator i=members.begin();i!=members.end();i++){
    if(!popmap.count(*i)) //new to the area?
      score+=(popmap[*i]=popCount(seq->readWord(*i)));
    else
      score+=popmap[*i];
  }
  return score;
}

string HashMethod::srcSetToString(const set<int> &a){
  ostringstream r;
  for(set<int>::const_iterator i=a.begin();i!=a.end();++i)
    r << *i << ";";
  return r.str();
}

double HashMethod::fitnessCheck(){
  //calculate entrop based on pattern and inputs
  int targetBases=(hash_bits+1)/2;
  used.clear();entropy.clear(); //reset state
  entropy.resize(targetBases,0);
  used.resize(seq->length(),0);
  size_t srcCount=used.size(),sinkCount=entropy.size(),patWeight=seq->_hashLength;
  vector<set<int> > entropySrcToSink(srcCount),entropySinkToSrc(sinkCount);
  active=0;
  for(InputList::iterator i=inputs.begin();i!=inputs.end();i++){
    word w=seq->readRawWord(i->first);
    if(i->second > 0)
      w=w>>(i->second*2);
    else
      w=w<<(-i->second*2);
    w&=hash_mask;
    for(unsigned b=0;b<entropy.size();b++){
      int srcbase=i->first*WORDSIZE/2+ //word this input is selecting
	(WORDSIZE/2-1-i->second)- //b=0 would be operating on
	b;
      if(srcbase < 0 || srcbase>=(int)used.size()) {
	continue;
      }
      if(w & (word)(3L<<(b*2L))){ //damn int literals
	assert(srcbase<seq->length() && srcbase>=0);
	assert(seq->readBase(srcbase)==3);
	entropySrcToSink[srcbase].insert(b);
	entropySinkToSrc[b].insert(srcbase);
	active|=3<<(b*2);
	used[srcbase]++;
      }
    }
  }

  //if any any sink uses more than half of the sourcs, flip them so we count the UNUSED ones instead
  for(unsigned sink=0;sink<sinkCount;sink++){
    if(entropySinkToSrc[sink].size()>patWeight){ //need to flip
      set<int> realSrcs(entropySinkToSrc[sink]);
      for(set<int>::iterator src=realSrcs.begin();src!=realSrcs.end();++src){
	entropySrcToSink[*src].erase(sink);
	entropySinkToSrc[sink].erase(*src);
      }
      for(unsigned src=0;src<srcCount;src++){
	if(!realSrcs.count(src) && seq->readCode(src)){ //is in the effective set
	  entropySrcToSink[src].insert(sink);
	  entropySinkToSrc[sink].insert(src);
	}
      }
    }
  }

  int totalUsed=0;
  for(size_t i=0;i<used.size();i++)
    totalUsed+=used[i];

  /*
  cout << "Initial src->sink map: ";
  for(unsigned i=0;i<entropySrcToSink.size();++i){
    if(entropySrcToSink[i].empty())
      continue;
    cout << i << "->" << "{";
    for(set<int>::iterator sinki=entropySrcToSink[i].begin();sinki!=entropySrcToSink[i].end();++sinki)
      cout << *sinki<<",";
    cout << "} ";
  }
  cout << endl;
  */

  if(opt.hasherFairEntropy){
    totalCorrelationPenalty=0;
    for(unsigned sink=0;sink<entropySinkToSrc.size();sink++){ //foreach sink
      if(entropySinkToSrc[sink].empty())
	continue;
      
      double correlationPenalty=0;
      if(opt.hasherCorrelationAdjust && entropySinkToSrc[sink].size()>1){
	//sum of distance pair squares
	long distSum=0,pairs=0;
	for(set<int>::iterator srcA=entropySinkToSrc[sink].begin();srcA!=entropySinkToSrc[sink].end();++srcA){
	  set<int>::iterator srcB=srcA;
	  for(++srcB;srcB!=entropySinkToSrc[sink].end();++srcB){
	    distSum+=(*srcA-*srcB)*(*srcA-*srcB);
	    //	      cout << " dist @"<<sink<<" pair "<<pairs<<":  "<<(*srcA-*srcB)<<endl;
	    pairs++;
	  }
	}
	//	  correlationPenalty=1/sqrt((double)distSum/pairs); //inverse mean distance squared * C (magic penalty constant. at a distance of 1 this is the penalty)
	correlationPenalty=.2/((double)distSum/(double)pairs); //inverse mean distance squared * C (magic penalty constant. at a distance of 1 this is the penalty)
	//	  cout << "Correlation @"<<sink<<": "<<distSum<<"/"<<pairs<<"=\t"<<correlationPenalty<<endl;
	totalCorrelationPenalty+=correlationPenalty;
      }
      
      for(set<int>::iterator srcA=entropySinkToSrc[sink].begin();srcA!=entropySinkToSrc[sink].end();++srcA){
	double weight=(1.0-correlationPenalty)/(double)used[*srcA];
	entropy[sink]+=weight;
      }
    }
    //All done in time o(entropy.size()) O(used.size()*entropy.size())
  }else{
    //now that we've figured out the src->sink graph, assign each sink at least one src.
    //do low degree sinks first so we don't undercount
    vector<set<int> > sinkDegrees;
    for(unsigned i=0;i<entropy.size();i++){
      if(sinkDegrees.size()<=entropySinkToSrc[i].size())
	sinkDegrees.resize(entropySinkToSrc[i].size()+1);
      sinkDegrees[entropySinkToSrc[i].size()].insert(i);
    }
    
    for(unsigned degree=1;degree<sinkDegrees.size();degree++){
      while(!sinkDegrees[degree].empty()){
	int sink=*(sinkDegrees[degree].begin());
	//this sink must have at least one source, we arbitrarily choose the first one
	//(I'm pretty sure this is safe, but equally sure that the proof of that is complicated)
	assert(!entropySinkToSrc[sink].empty());
	int src=*(entropySinkToSrc[sink].begin());
	//      cout << "Using "<<src<<" -> "<<sink<<endl;
	//note that sink gets entropy from src
	entropy[sink]++;

	//update all the other sinks available to src (noting that they're no longer available)
	//and change the sink degree      
	for(set<int>::iterator altsinki=entropySrcToSink[src].begin();altsinki!=entropySrcToSink[src].end();){
	  set<int>::iterator nextAltsinki=altsinki; ++nextAltsinki;
	  int altsink=*altsinki;
	  assert(sinkDegrees[entropySinkToSrc[altsink].size()].count(altsink)==1);
	  sinkDegrees[entropySinkToSrc[altsink].size()].erase(altsink);
	  entropySinkToSrc[altsink].erase(src);
	  entropySrcToSink[src].erase(altsink);
	  //	cout << "Pruning "<<src<<" <-> "<<altsink<<endl;
	  if(entropySinkToSrc[altsink].size()) //don't actually use 0
	    sinkDegrees[entropySinkToSrc[altsink].size()].insert(altsink);
	  altsinki=nextAltsinki;
	}
      }
    }

    //any remaining entropy is just a bonus. distribute arbitrarily
    for(unsigned src=0;src<entropySrcToSink.size();src++){
      if(!entropySrcToSink[src].empty())
	entropy[*(entropySrcToSink[src].begin())]++;
    }
  }

  sources=0;
  for(unsigned i=0;i<used.size();i++)
    if(used[i])
      sources++;
  assert(sources<=seq->hashLength());

  //kill entropy from any redundant source sets
  set<string> usedSrcSets;
  for(int sink=0;sink<(int)entropy.size();sink++){
    string srcSet(srcSetToString(entropySinkToSrc[sink]));
    pair<set<string>::iterator, bool> res(usedSrcSets.insert(srcSet));
    if(!res.second)//already existed
      entropy[sink]=0;
  }

  //evaluate entropy
  entropyHi=entropy.front(),entropyLo=entropy.front(),entropyTotal=0;
  empties=0;
  int J=0;
  for(vector<double>::iterator i=entropy.begin();i!=entropy.end();i++,J++){
    entropyTotal+=*i;
    if(*i<.4){
      //      cout << "empty @"<<J<<": "<<(1-*i)<<endl;
      empties+=1-*i;
    }
    entropyHi=max<int>(entropyHi,*i);
    entropyLo=min<int>(entropyLo,*i);
  }
  entropyMean=(double)entropyTotal/(double)entropy.size();
  double variance=0;
  for(vector<double>::iterator i=entropy.begin();i!=entropy.end();i++)
    variance+=sqr((double)(*i)-entropyMean);
  variance/=entropy.size();
  entropyStd=sqrt(variance);

  /*  cout << *this << ": ";
  for(unsigned i=0;i<entropy.size();i++)
    cout << entropy[i]<<":";
  cout << " ("<<entropyTotal<<")"<<endl;
  cout << endl;*/

  double entropyAgro=opt.hasherEntropyAgro; //the bigger this is, the more anxiously we go after entropy
  double x=seq->_hashLength; //basically we estimate how much entropy to aim for based on how many entropy sources are available
  
  fitness=entropyTotal //overall entropy is a good thing
    -((double)inputs.size()/(double)WORDSIZE) //using more inputs is to a certain extent a bad thing, but hardly the end of the universe.
    -max<double>(1,x/WORDSIZE/2.0+entropyAgro*log(x)*sqrt(x)) //target entropy scaling function, asymtotically sqrt(x) like, weighted to be at about x/2 by 1000-ish
    -(double)(empties*entropy.size()*entropy.size()) //empties are evil
    -(entropyStd) //hopefully we're spreading entropy evenly over the whole key (or else we're wasting cycles)
    //    -(empties==0 && targetBases==seq->_hashLength ? totalUsed-seq->_hashLength:0) //special case that we have exactly as many input as outputs, if we don't have any empties prefer to use sources as few times as possible (ie: minimize reuse of sources)
    ;
  return fitness;
}

void BitSequence::randomHashFunc(int n){
  cout << "Generating random hash function with "<<n<<" hash inputs."<<endl;
  hasher=new HashMethod(this,n);
  hasher->fitnessCheck();
  cout << "Random uses "<<hasher->sources<<"/"<<(hashLength())<<" bases and has "<<hasher->empties<<" empties from "<<hasher->inputlist().size()<<" inputs."<<endl;
  cout << "Score: "<<hasher->fitness<<endl;
  cout << "Entropy: high: "<<hasher->entropyHi<<" lo: "<<hasher->entropyLo<< " total: "<<((double)hasher->entropyTotal)<<" bases (mean: "<<hasher->entropyMean<<" stddev: "<<hasher->entropyStd<<")"<<endl;
  cout << "Total correlation penalty: "<<hasher->totalCorrelationPenalty<<endl;
  //  cout << "Pre cleanup: "<<*hasher<<endl;
  cout << "Function content: "<<*hasher<<endl<<hasher->prettyPrint();
}

void BitSequence::compileHashFunc() {
  assert(isPattern);
  vector<HashMethod>  funcs;
  for(int c=0;c<100;c++){ //spawn 100 population
    funcs.push_back(HashMethod(this));
  }
  
  int cycle,lastImprovedCycle=0;
  const int targetCycles=opt.hasherTargetGACycles;
  double improved=0;
  sort(funcs.begin(),funcs.end());
  double worstScore=funcs.front().fitness;
  double bestScore=funcs.back().fitness;
  ticker.reset(targetCycles);
  for(cycle=0;
      bestScore<hash_bits && (cycle<targetCycles || (cycle-lastImprovedCycle)<(cycle/(targetCycles/10)));cycle++,ticker.tick()){ //arbitrarily large!
    double prevBestFitness=bestScore;
    //make the top N mate together, cull the bottom N
    int population=funcs.size();
    int kidCount=population/3;
    int maters=kidCount/2;
    int minMate=population-maters;
    
    for(int matei=0;matei<kidCount;matei++){
      if(random() & 1){ //actually mate with another hash function
	const HashMethod &a=funcs[randint(maters)+minMate],&b=funcs[randint(maters)+minMate];
	HashMethod c(a,b);
	funcs.push_back(c);
      }else{
	HashMethod c(funcs[randint(maters)+minMate]); //clone one
	c.mutate(); //mutate
	funcs.push_back(c);
      }
    }
    
    funcs.erase(funcs.begin(),funcs.begin()+kidCount);
    
    sort(funcs.begin(),funcs.end());
    
    bestScore=funcs.back().fitness;
    improved=bestScore-prevBestFitness;
    if(improved>0)
      lastImprovedCycle=cycle;
  }
  ticker.done();

  cout << "Acceptable hash function found after "<<cycle<<" cycles."<<endl;
  hasher=new HashMethod(funcs.back());//keep the best
  hasher->finalize();
  cout << "Best uses "<<hasher->sources<<"/"<<(hashLength())<<" bases and has "<<hasher->empties<<" empties from "<<hasher->inputlist().size()<<" inputs."<<endl;
  cout << "Score: "<<hasher->fitness<<" (cf. worst: "<<worstScore<<")"<<endl;
  cout << "Entropy: high: "<<hasher->entropyHi<<" lo: "<<hasher->entropyLo<< " total: "<<((double)hasher->entropyTotal)<<" bases (mean: "<<hasher->entropyMean<<" stddev: "<<hasher->entropyStd<<")"<<endl;
  cout << "Total correlation penalty: "<<hasher->totalCorrelationPenalty<<endl;
  //  cout << "Pre cleanup: "<<*hasher<<endl;
  cout << "Post cleanup: "<<*hasher<<endl<<hasher->prettyPrint();
}

void HashMethod::finalize(){
  removeDuplicates();
  pruneUseless();
  fitnessCheck();
}

void HashMethod::removeDuplicates(){
  InputList tmp;
  sort(inputs.begin(),inputs.end());
  unique_copy(inputs.begin(),inputs.end(),insert_iterator<InputList>(tmp,tmp.begin()));
  inputs=tmp;
}

string HashMethod::prettyPrint(){
  //each line starts with input tag
  int leaderSize=10;
  string spacer=repString(" ",leaderSize);
  string str=spacer;
  //                            |0                              |32                             |64
  static const char alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //the base64 alphabet
  static const int alphasize=sizeof(alphabet)-1; assert(alphasize==64);
  int lineWidth=70;
  int hashLen=((int)hash_bits+1)/2; //only show base positions
  int padLeft=(lineWidth-hashLen)/2;

  //draw hash positions
  if(hashLen>=10){ //extra tens digit line
    str+=repString(" ",padLeft);
    for(int p=hashLen-1;p>=0;p--){
      if(p>=10)
	str+=dstring((int)(p/10)%10);
      else
	str+=" ";
    }
    str+="\n";str+=spacer;
  }
  str+=repString(" ",padLeft);
  for(int p=hashLen-1;p>=0;p--)
    str+=dstring((int)p%10);
  str+="\n";str+=spacer;
  str+=repString(" ",padLeft);
  str+=repString("=",hashLen);
  str+="\n";

  //draw each input
  HashMethod::InputList::const_iterator last=inputs.end();
  last--;
  for(HashMethod::InputList::const_iterator i=inputs.begin();i!=inputs.end();i++){
    char leader[50];
    sprintf(leader,"w[%2d]%s%2d:",i->first,(i->second>0 ? ">>":"<<"),abs(i->second));
    leader[leaderSize+1]='\0';
    str+=leader;
    int linePos=0;
    int start=i->first*WORDSIZE/2+ //first base used in key
      (WORDSIZE/2-1-i->second)- 
      hashLen+1;

    for(int p=start-padLeft;p<seq->length() && linePos<lineWidth;p++,linePos++){
      if(p<0 || p/(WORDSIZE/2)!=i->first){
	str+=" ";
	continue;
      }
      bool patOn=(seq->readBase(p)==3);
      if(linePos<padLeft || linePos>=padLeft+hashLen)
	str+=patOn ? "-":"_";
      else {
	if(patOn)
	  str+=alphabet[p%alphasize];
	else
	  str+=".";
      }
    }
    str+="\n";
  }

  return str;
}

ostream& operator<<(ostream &os,const HashMethod &a){
  HashMethod::InputList::const_iterator last=a.inputs.end();
  last--;
  for(HashMethod::InputList::const_iterator i=a.inputs.begin();i!=a.inputs.end();i++){
    if(i->second > 0)
      os << "w["<<i->first<<"]>>"<<i->second;
    else if(i->second < 0)
      os << "w["<<i->first<<"]<<"<<0-i->second;
    else 
      os << "w["<<i->first<<"]";
  if(i!=last)
    os << " ^ ";
  }
  os << " {"<<a.inputs.size()<<"}";
  return os;
}

int HashMethod::align(int w){
  word pat=seq->readRawWord(w);
  //try all possible alignments
  multimap<int,int> score2shift;
  int bestscore=0;
  for(int shift=1-WORDSIZE/2;shift<WORDSIZE/2-1;shift++){
    int score;
    if(shift>0)
      score=popCount( ((pat>>shift*2)) & hash_mask);
    else
      score=popCount( ((pat<<-shift*2)) & hash_mask);
    bestscore=max<int>(score,bestscore);
    score2shift.insert(pair<int,int>(score,shift));
  }
  //choose randomly from among the non-zero scoring options
  vector<int> options;
  transform(score2shift.lower_bound(1),score2shift.end(),
	    insert_iterator<vector<int> >(options,options.begin()),
	    select2nd<map<int,int>::value_type>());
  if(options.empty())
    return randint(WORDSIZE)-WORDSIZE/2; //wtf?
  return options[randint(options.size())];
}

void HashMethod::pruneUseless(){
  vector<InputList::iterator> toErase;
  for(InputList::iterator i=inputs.begin();i!=inputs.end();i++){
    word w=seq->readRawWord(i->first);
    if(i->second>=0)
      w=w>>(i->second*2);
    else
      w=w<<(-i->second*2);
    w&=hash_mask;
    if(!popCount(w))
      toErase.push_back(i);
  }
  for(vector<InputList::iterator>::iterator i=toErase.begin();
      i!=toErase.end();i++)
    inputs.erase(*i);
}

void HashMethod::addWord(){
  int w;
  if(!unusedWords.empty()){
    int wi=randint(unusedWords.size());
    w=unusedWords[wi];
    unusedWords.erase(unusedWords.begin()+wi);
  }else{
    w=randint(seq->word_count);
  }
  inputs.push_back(pair<int,int>(w,align(w))); //add a word
}

void HashMethod::removeWord(){
  int wi=randint(inputs.size());
  //  int w=inputs[wi].first;
  inputs.erase(inputs.begin()+wi); //pull off inputs
  //pretend it never existed because we don't want force it to be pushed back on
  //  unusedWords.push_back(w);
}

void HashMethod::mutate(){
  //  cerr << "Mutating "<<id<<" "<<*this<<" ";
  int fate=randint(100); //magical 100-sided mutation die
  if(fate<50 || maxSources()<hash_bits){//randomly add another word
    addWord();
  }else if(fate<5 && inputs.size()>1){ //randomly kill a word
    removeWord();
  }else{
    //bump a random word in a random direction
    int w=randint(inputs.size());
    int shift=inputs[w].second+(random()&1) ? 1:-1;
    if(shift>=WORDSIZE/2)
      shift-=WORDSIZE; //wraparound
    else if(shift<=-WORDSIZE/2)
      shift+=WORDSIZE;
    inputs[w].second=shift;
  }
  finalize();
  //   cerr << "->" << *this<< " new score: "<<score<<endl;
}

HashMethod::HashMethod(const HashMethod &a) :
  inputs(a.inputs),seq(a.seq),
  unusedWords(a.unusedWords),
  sources(a.sources),empties(a.empties),fitness(a.fitness),
  active(a.active)
{
  //  cout << a.id << " cloned => "<<id<<" ("<<*this<<")"<<endl;
}

HashMethod::HashMethod(const HashMethod &a,const HashMethod &b) :
  inputs(a.inputs),
  seq(a.seq)
{
  inputs.insert(inputs.end(),b.inputs.begin(),b.inputs.end()); //add in inputs from b
  
  //erase a third
  int toErase=inputs.size()/3;
  for(int i=0;i<toErase;i++)
    inputs.erase(inputs.begin()+randint(inputs.size()));

  //reconstruct unused words:
  set<int> usedWords;
  transform(inputs.begin(),inputs.end(),insert_iterator<set<int> >(usedWords,usedWords.begin()),select1st<pair<int,int> >());
  for(word w=0;w<seq->word_count;w++)
    if(!usedWords.count(w))
      unusedWords.push_back(w);

  //  mutate();
  finalize();
}

HashMethod::HashMethod(BitSequence *s) :
  seq(s),active(0)
{
  cout.flush();
  for(word w=0;w<s->word_count;w++)
    unusedWords.push_back(w);
  addWord();
  fitnessCheck();
}

HashMethod::HashMethod(BitSequence *s,int n) : //random hash func for n words
  seq(s),active(0)
{
  if(n){ //craft a random hash function with exactly n inputs
    cout << "# Generating random hash function with "<<n<<" random inputs"<<endl;
    set<pair<int,int> > usedInps;
    while((int)inputs.size()<n){
      pair<int,int> inp(randint(s->wordCount()),randint(WORDSIZE-1)-WORDSIZE/2+1);
      if(!usedInps.count(inp)){
	usedInps.insert(inp);
	inputs.push_back(inp);
      }
    }
  }else{ //randomly selected hash function out of all possible hash functions
    cout << "# Selecting hash function purely at random."<<endl;
    for(int i=0;i<(int)seq->wordCount();i++)
      for(int shift=1-WORDSIZE/2;shift<=WORDSIZE/2-1;shift++)
	if(random() & 1)
	  inputs.push_back(pair<int,int>(i,shift));
  }
}

bool operator==(const BitSequence& a,const BitSequence& b){
  for(word i=0;i<a.word_count && i<b.word_count;i++)
    if(a.readWord(i)!=b.readWord(i))return false;
  return true;
}

Location::Location(Sequence *s,SeqPos p) :
  seqno(lookup_seqtable(s)),pos(p) { }

Location::Location(SeqIdx s,SeqPos p) :
  seqno(s),pos(p) { }

Location::Location() :
  seqno(255),pos(0) { } //this should only be used to create temp storage

Sequence* Location::seq() const{
  return seq_table[seqno];
}

BitSequence* Location::bitSeq() const {return pos>0 ? seq()->fwd:seq()->rev;}

word Hash::sizeAt(const HashKey key,const HashVal &a){
  //universally functional sizeAt...(slow. should be specialized for each hash)
  if(emptyAt(key))
    return 0;
  Location aloc(a);
  Window awin(aloc,hashpat);
  list<LocList> fulllist;
  mfh->getMatchingSets(key,fulllist);
  for(list<LocList>::iterator seti=fulllist.begin();seti!=fulllist.end();++seti){
    LocList &l=*seti;
    SeqIdx baseSeq=0;
    while(l[baseSeq].empty() && baseSeq<seq_count)
      baseSeq++;
    if(baseSeq>=seq_count){
      assert((cerr << "Empty loclist??") && 0);
      continue; //wtf? how'd that happen?
    }
    Location &loc=l[baseSeq].front();
    Window locwin(loc,hashpat);
    if(locwin.equals(awin)){ //this is the one we care about!
      word sum=0;
      for(SeqIdx si=0;si<seq_count;si++)
	sum+=l[si].size();
      return sum;
    }
  }
  return 0;
}

void Hash::dump(ostream &os){
  HashKey key;
  unsigned s;

  for(key=0; key<(unsigned)hash_size; key++){
    unsigned c=0;
    LocList  l(seq_count); lookup(key, l);    

    s = sizeAt(key);
    if( s==0 ) continue;

    os.write( (char*)&key, sizeof(HashKey)  );
    os.write( (char*)&s,   sizeof(unsigned) );
    //    cout << "dump: size=" << s<< endl;
    for(unsigned i=0; i<l.size(); i++){
      for(list<Location>::iterator ll=l.at(i).begin(); ll!=l.at(i).end(); ll++){
	Location lll=*ll;
	os.write( (char*)&lll, sizeof(Location) );
	c++;
      }
    }
    if (s!=c){ cerr << "Hash::dump(): incorrect size?" << endl; }
  }

  key = 0;
  s = 0;
  os.write( (char*)&key, sizeof(HashKey)  );
  os.write( (char*)&s,   sizeof(unsigned) );
}

void Hash::load(istream &is){
  HashKey key;
  unsigned s;
  Location l;
  Location *buf;

  do {
    is.read( (char*)&key, sizeof(HashKey)  );
    is.read( (char*)&s,   sizeof(unsigned) );
    if( key==0 && s==0 ) break;

    buf = (Location*)malloc(sizeof(Location) * s);
    is.read( (char*)buf, sizeof(Location) * s);
    for(unsigned i=0; i<s; i++) add(key, buf[i]);
    free(buf);
  } while(true);
}

Hash::Hash(BitSequence *pat) :
  hashpat(pat)
{
}

Hash::~Hash(){}

void Hash::writeHistogram(ostream &of){
  vector<SeqPos> histo(1,0);
  for(word base=0;base<(word)hash_size;base++){ //oh this is fun...
    if(emptyAt(base))
      continue;
    usedBuckets++;
    unsigned size=sizeAt(base);
    if(size>=histo.size())
      histo.resize(size+1);
    histo[size]++;
  }
  
  // compare the pointers instead of the objects 
  if(&of != &cerr)
    for(unsigned i=1;i<histo.size();i++){
      of << i << "\t" << histo[i]<<endl;
    }
}

void Hash::writeDetailedHistogram(ostream &of){
  for(word base=0;base<(word)hash_size;base++){ //oh this is fun...
    if(emptyAt(base))
      continue;
    unsigned size=sizeAt(base);
    if(size){
      if(opt.histogram>3){ //super freaking detailed
	LocList ll(seq_count);
	lookup(base,ll); //fetch all locations...
	vector<Location> locs;
	back_insert_iterator<vector<Location> > ii(locs);
	for(int i=0;i<seq_count;i++) 
	  copy(ll[i].begin(),ll[i].end(),ii); //throw all into big list
	sort(locs.begin(),locs.end());
	vector<Location>::iterator i=locs.begin();
	Location last(*i);
	word count=1;
	usedPats++; //we got at least 1 new one
	do{
	  i++;
	  if(i==locs.end())
	    break;
	  Location here(*i);
	  if(last<here){ //different src pattern
	    of << base << "\t" << Window(last,hashpat).prettyString() << "\t" << count << endl;
	    if(count>worstPat)
	      worstPat=count;
	    count=1;
	    last=here;
	    usedPats++;
	  }
	  count++;
	}
	while(1);
	if(count>worstPat)
	  worstPat=count;
	of << base << "\t" << Window(last,hashpat).prettyString() << "\t" << count << endl;
      }else
	of << base<<":"<<size << endl;
    }
  }
}

void Hash::writePerformanceData(string prefix){
  //i have no performance, i'm just an abstract class =P
}

UsedMap::UsedMap():
  used(seq_count)
{ }

bool UsedMap::sanityCheck() {
  for(unsigned i=0;i<used.size();i++){
    for(usedItree::iterator s=used[i].begin();
	s!=used[i].end();s++){
      assert(*s);
      assert((*s)->sanityCheck());
    }
  }
  return 1;
}

bool AnchorSet::sanityCheck() const {
  for(unsigned i=0;i<spaces.size();i++){
    assert(UsedInt_sanityCheck(spaces[i].key()));
    assert(*spaces[i]==this);
  }
  return 1;
}

bool IntervalSet::sanityCheck() const {
  for(unsigned i=0;i<spaces.size();i++){
    assert(UsedInt_sanityCheck(spaces[i]));
  }
  return 1;
}


bool Hash::sanityCheck(){
  for(word base=0;base<(word)hash_size;base++){
    if(emptyAt(base))
      continue;
    LocList loclist;
    lookup(base,loclist);
    for(unsigned s=0;s<loclist.size();s++)
      for(LocSubList::iterator i=loclist[s].begin();
	  i!=loclist[s].end();i++){
	Window w(*i,hashpat);
	word here=w.hash();
	//      cout << "hash for "<<l<<" ("<<w<<"): "<<wordToString(here) << " (vs "<< wordToString(base)<<")"<<endl;
	if(here!=base){
	  assert(here==base);
	  return false;
	}
      }
  }
  return true;
}

bool Hash::sanityCheck(word base){
  if(emptyAt(base))
    return true;
  //  cout << "Spot checking "<<wordToString(base)<<endl;
  LocList loclist;
  lookup(base,loclist);
  for(unsigned s=0;s<loclist.size();s++)
    for(LocSubList::iterator i=loclist[s].begin();
	i!=loclist[s].end();i++){
      Window w(*i,hashpat);
      word here=w.hash();
      //    cout << "  ** hash for "<<l<<" ("<<w<<"): "<<wordToString(here)<<endl;
      if(here!=base){
	assert(here==base);
      return false;
      }
    }
  return true;
}

bool UsedMap::fetchOverlaps(int seq,const UsedInt &a,set<AnchorSet*> &out){
  bool res=false;

  for(usedItree::range_iterator i(used[seq].in_range(a));i!=used[seq].end();++i){
    out.insert(*i);
    res=true;
  }

  return res;
}

bool UsedMap::fetchNearbyOverlaps(int seq,const UsedInt &a,SeqPos maxgrow,set<AnchorSet*> &out){
  bool res=false;
  UsedInt bounds(maxgrow ? seqs[seq]->growInBounds(a,maxgrow):a);

  for(usedItree::range_iterator i(used[seq].in_range(bounds));
      i!=used[seq].end();++i){
    out.insert(*i);
    res=true;
  }

  return res;
}

bool UsedMap::alreadyExists(const IntervalSet& a){
  set<AnchorSet*> matches,temp,context;

  int i=0;
  while(isZero(a.spaces[i])){
    i++;
    assert(i<seq_count);
  }


  if(!fetchOverlaps(i,a.spaces[i],context)){
    return false;
  }

  for(i++;i<seq_count;i++){
    if(isZero(a.spaces[i]))
      continue;
    if(!fetchOverlaps(i,a.spaces[i],temp))
      return false;
    set_intersection(temp.begin(),temp.end(),
		     context.begin(),context.end(),
		     inserter(matches,matches.begin()));
    if(matches.empty())
      return false;
    context.clear();
    context.insert(matches.begin(),matches.end());
    matches.clear();
  }
  bool winner=false;
  //must find out if a is entirely inside of anything in context
  for(set<AnchorSet*>::iterator ite=context.begin();
      ite!=context.end();
      ite++){
    AnchorSet *s=*ite;
    if(s->contains(a)){
      winner=true;
      if(opt.retainMembers){ //if we're keeping track of members, this counts as a hit.
	for(HashCount::const_iterator i=a.members.begin();i!=a.members.end();i++)
	  s->members[i->first]+=i->second;
      }
    }
  }
  return winner;
}

bool UsedMap::merge(IntervalSet& a){
  //  assert(a.sanityCheck());
  set<AnchorSet*> matches,temp,context;
  SeqPos joinDist=opt.joinNeighbors ? opt.joinDist:1;

  int i=0;
  while(isZero(a.spaces[i])){
    i++;
    assert(i<seq_count);
  }

  if(!fetchNearbyOverlaps(i,a.spaces[i],joinDist,context))
    return false;

  for(i++;i<seq_count;i++){
    if(isZero(a.spaces[i]))
      continue;
    if(!fetchNearbyOverlaps(i,a.spaces[i],joinDist,temp))
      return false;
    set_intersection(temp.begin(),temp.end(),
		     context.begin(),context.end(),
		     inserter(matches,matches.begin()));
    if(matches.empty())
      return false;
    context.clear();
    context.insert(matches.begin(),matches.end());
    matches.clear();
  }
  //context now contains all anchorsets which a overlaps in each sequence individually
  //(but any single anchorset might not overlap in all sequences!!!)
  assert(a.sanityCheck());
  bool didMerge=false;
  for(set<AnchorSet*>::iterator i=context.begin();
      i!=context.end();
      i++){
    if(!a.colinear(**i,joinDist)){
      continue;
    }
    assert((*i)->sanityCheck());
    //    cout << "Merging: "<<a<<" with "<< IntervalSet(**i)<<endl;
    //    assert(sanityCheck());
    assert(a.sanityCheck());
    a.coalesce(**i);
    //    assert(sanityCheck());
    assert(a.sanityCheck());
    remove(*i);
    //    cout << "Result: "<<a<<endl;
    //    assert(sanityCheck());
    assert(a.sanityCheck());
    didMerge=true;
  }
  if(didMerge)
    add(a);
  return didMerge;
}

void UsedMap::add(const IntervalSet &a){
  //  cout << "UsedMap::Add("<<const_cast<IntervalSet&>(a)<<")"<<endl;
  new AnchorSet(a,*this); //add it
}

void UsedMap::insert(IntervalSet& a){
  //  assert(cout << "Insert: "<<a<<endl);
  assert(a.sanityCheck());
  if(alreadyExists(a)){
    //      cout << "--- Already exists."<<endl;
    return; //already complete inside some other anchor?
  }

  Score ascore=opt.scoreFilter ? a.score():0; //we only care about the score at this point if we're going to filter by it

  if(opt.fuzzyExtend)
    ascore+=a.fuzzyExtend();
  else
    a.exactExtend();

  if(opt.scoreFilter && ascore<opt.scoreFilter)
    return;

  if(merge(a)){ //try to merge it
    //    cout << "--- Merged"<<endl;
    return; 
  }

  add(a); //completely new and fresh!
  //  cout << "--- Added as a new anchor"<<endl;
}

void UsedMap::remove(AnchorSet *a){
  //  assert(sanityCheck());
  for(unsigned i=0;i<a->spaces.size();i++){
    //    assert(cerr << "Erasing seq "<<i<<" - "<<*(a->spaces[i])<<" from: "<<used[i]<<endl);
    used[i].erase(a->spaces[i]);
    //    assert(sanityCheck());
  }
  //  assert(sanityCheck());
  delete a;
  //  assert(sanityCheck());
}

bool AnchorSet::contains(const IntervalSet &a) const {
  if(opt.gappedAnchors){
    for(unsigned i=0;i<spaces.size();i++){
      if(isZero(a.spaces[i]) && isZero(spaces[i].key()))
	continue;
      if(isZero(a.spaces[i]) != isZero(spaces[i].key()))
	return false;
      if(!UsedInt_contains(spaces[i].key(),a.spaces[i]))
	return false;
    }
    return true;
  }else{
    if(!(a.overlaps(*this) & OVERLAP_AINB))
      return false;
    if(a.hasGaps(*this))
      return false;
    return true;
  }
}

bool IntervalSet::contains(const IntervalSet &a) const {
  for(unsigned i=0;i<spaces.size();i++){
    if(isZero(a.spaces[i]) && isZero(spaces[i]))
      continue;
    if(isZero(a.spaces[i]) != isZero(spaces[i]))
      return false;
    if(!UsedInt_contains(spaces[i],a.spaces[i]))
      return false;
  }
  return true;
}

SeqPos UsedInt_distance(UsedInt a,UsedInt b){
  if(isRev(a)){
    UsedInt_rawInvert(a);
    UsedInt_rawInvert(b);
  }
  if(UsedInt_overlaps(a,b))
    return 0;
  return min<SeqPos>(abs(a.stop-b.start),abs(a.start-b.stop));
}

OverlapSense UsedInt_overlaps(UsedInt a,UsedInt b){
  assert(!isZero(a));
  assert(!isZero(b));
  
  if(isRev(a)){ //work in standardized coordinate space (ugh, so crazy)
    UsedInt_rawInvert(a);
    UsedInt_rawInvert(b);
  }

  
  if(!a.overlaps(b))
    return OVERLAP_NONE; //absolutely no overlap

  if(opt.gappedAnchors) //if we relied on strict matching overlap types under gapped anchor rules the order of anchor merges would make a difference resulting in icky non-determinism
    return ~OVERLAP_NONE; //we don't know what kind of overlap, but it's definitely "not none"

  OverlapSense res=OVERLAP_NONE;
  //flush cases are both AB and BA
  if(UsedInt_contains(b,a))res|=OVERLAP_AINB;
  if(UsedInt_contains(a,b))res|=OVERLAP_BINA;

  if(a.start<=b.start)
    res|=OVERLAP_START_AB;
  if(b.start<=a.start)
    res|=OVERLAP_START_BA;
  
  if(a.stop<=b.stop)
    res|=OVERLAP_STOP_AB;
  if(b.stop<=a.stop)
    res|=OVERLAP_STOP_BA;
  
  //  assert(cout << a << " overlaps " << b << " "<< OverlapSense2str(res) << endl);

  return res;
}

string OverlapSense2str(OverlapSense o){
  ostringstream res;
  vector<string> bits;
  if(o==OVERLAP_NONE)
    bits.push_back("nowhere");
  else if(o==~OVERLAP_NONE)
    bits.push_back("somewhere");
  else {
    if(o & OVERLAP_AINB && o & OVERLAP_BINA)
      bits.push_back("perfectly");
    else {
      if(o & OVERLAP_AINB)
	bits.push_back("a in b");
      else if(o & OVERLAP_BINA)
	bits.push_back("b in a");
      else {
	if(o & OVERLAP_START_AB && o & OVERLAP_START_BA)
	  bits.push_back("start_flush");
	else{
	  if(o & OVERLAP_START_AB)
	    bits.push_back("start_ab");
	  if(o & OVERLAP_START_BA)
	    bits.push_back("start_ba");
	}

	if(o & OVERLAP_STOP_AB && o & OVERLAP_STOP_BA)
	  bits.push_back("stop_flush");
	else{
	  if(o & OVERLAP_STOP_AB)
	    bits.push_back("stop_ab");
	  if(o & OVERLAP_STOP_BA)
	    bits.push_back("stop_ba");
	}
      }
    }
  }
  if(o & COLINEAR_AB)
    bits.push_back("colinear_ab");
  if(o & COLINEAR_AB)
    bits.push_back("colinear_ba");
  assert(!bits.empty()); //i should have taken care of all everything possible...
  copy(bits.begin(),bits.end(),ostream_iterator<string>(res,","));
  return res.str();
}

OverlapSense IntervalSet::overlaps(const AnchorSet &a) const {
  OverlapSense ref=OVERLAP_NONE;
  bool first=true;
  //  cout << "Testing overlap of "<<*this<<" with "<<IntervalSet(a)<<endl;
  for(unsigned i=0;i<spaces.size();i++){
    if(isZero(a.spaces[i].key()) && isZero(spaces[i]))
      continue;
    OverlapSense here=UsedInt_overlaps(spaces[i],a.spaces[i].key());
    if(!here)
      return here;
    //ok, overlaps partially, but do they overlap the same way?
    if(first){
      ref=here;
      first=false;
    }else{
      if(ref!=here) //overlaps only count among anchorsets if they're the same sense
	return OVERLAP_NONE;
    }
  }
  return ref;
}

SeqPos UsedInt_offset(UsedInt a,UsedInt b){
  return isRev(a) ? b.stop-a.stop:a.start-b.start;
}

SeqPos IntervalSet::offset(const AnchorSet& a) const {
  assert(!gapOffset(a).first);
  return gapOffset(a).second;  
}

pair<bool,SeqPos> IntervalSet::gapOffset(const AnchorSet &a) const {
  SeqPos offset;
  uint i=0;
  while(isZero(spaces[i])){
    assert(isZero(a.spaces[i].key()));
    i++;
    assert(i<spaces.size());
  }

  //  cout << "Testing "<<*this<<" and "<<IntervalSet(a)<<" for offset/gaps: "<<endl;
  offset=UsedInt_offset(spaces[i],a.spaces[i].key());
  if(seqs[i]->getSubSeqBounds(spaces[i].start).start!=seqs[i]->getSubSeqBounds(a.spaces[i].key().start).start){
    //    cout << spaces[i]<<" and "<<a.spaces[i].key()<<" are in different subsequences of "<<i<<endl;
    return pair<bool,SeqPos>(true,maxSeqPos);
  }
  //  cout << "  Offset "<<i<<": "<<offset<<endl;
  for(i++;i<spaces.size();i++){
    if(isZero(spaces[i])){
      assert(isZero(a.spaces[i].key()));
      continue;
    }
    if(seqs[i]->getSubSeqBounds(spaces[i].start).start!=seqs[i]->getSubSeqBounds(a.spaces[i].key().start).start){
      //      cout << spaces[i]<<" and "<<a.spaces[i].key()<<" are in different subsequences of "<<i<<endl;
      return pair<bool,SeqPos>(true,maxSeqPos);
    }
    //    cout << "  Offset "<<i<<": "<< UsedInt_offset(spaces[i],a.spaces[i].key()) << endl;
    if(UsedInt_offset(spaces[i],a.spaces[i].key())!=offset)
      return pair<bool,SeqPos>(true,maxSeqPos);
  }
  return pair<bool,SeqPos>(false,offset);
}

bool IntervalSet::hasGaps(const AnchorSet &a) const {
  return gapOffset(a).first;
}

ColinearSense IntervalSet::colinear(const AnchorSet &a,SeqPos maxDist) const {
  OverlapSense res=overlaps(a);
  if(!opt.gappedAnchors && hasGaps(a)){
    return COLINEAR_NONE;
  }

  if(res){
    //amend with colinear details
    if(res & (OVERLAP_START_AB | OVERLAP_STOP_AB | OVERLAP_AINB | OVERLAP_BINA))
      res|=COLINEAR_AB;
    if(res & (OVERLAP_START_BA | OVERLAP_STOP_BA | OVERLAP_AINB | OVERLAP_BINA))
      res|=COLINEAR_BA;
    return res;
  }

  if(opt.gappedAnchors){
    res=COLINEAR_AB|COLINEAR_BA; //one of those...dunno+dont care which

    //possible non-overlapping colinearity
    for(unsigned i=0;i<spaces.size();i++){
      if(isZero(a.spaces[i].key()) && isZero(spaces[i]))
	continue;
      if(isZero(a.spaces[i].key())!=isZero(spaces[i]) || isRev(a.spaces[i].key())!=isRev(spaces[i]))
	return COLINEAR_NONE;
      
      if(seqs[i]->getSubSeqBounds(spaces[i].start).start!=seqs[i]->getSubSeqBounds(a.spaces[i].key().start).start)
	return COLINEAR_NONE;

      if(opt.gappedAnchors){ //if using gaps, everything just has to be "close enough". actual colinearity is ignored
	if(UsedInt_distance(spaces[i],a.spaces[i].key())>maxDist)
	  return COLINEAR_NONE;
      }
    }
    return res;
  }else{
    for(uint i=0;i<spaces.size();i++){
      assert(isZero(spaces[i])==isZero(a.spaces[i].key()));
      if(isZero(spaces[i]) && isZero(a.spaces[i].key()))
	continue;
      if(UsedInt_distance(spaces[i],a.spaces[i].key())>maxDist){
	return COLINEAR_NONE;
      }
      //because we're gappless, all distances must be the same
      return (COLINEAR_AB|COLINEAR_BA); //not sure which. doesn't matter though.
    }
  }
  assert(0); //control doesn't reach here. really.
  return COLINEAR_NONE; //but just to quiet the compiler...
}

bool UsedInt_contains(const UsedInt &outer,const UsedInt &inner){
  return outer.start<=inner.start && outer.stop>=inner.stop;
}

void IntervalSet::coalesce(const AnchorSet &a){
  for(size_t i=0;i<spaces.size();i++){
    if(isZero(a.spaces[i]) || isZero(spaces[i]))
      continue;
    UsedInt_coalesce(spaces[i],a.spaces[i].key());
  }
  //mmmm tasty metadata - nom nom!
  if(opt.retainMembers)
    for(HashCount::const_iterator i=a.members.begin();i!=a.members.end();i++)
      members[i->first]+=i->second;
}

void UsedInt_coalesce(UsedInt &x,const UsedInt &a){
  if(isZero(x) || isZero(a))
    return;
  x.start=x.start<=a.start ? x.start:a.start;
  x.stop=x.stop>=a.stop ? x.stop:a.stop;
}

UsedInt UsedInt_coalesced(const UsedInt &a,const UsedInt &b){
  assert(!isZero(a));  assert(!isZero(b));  //no forcing coalesces of non-intervals
  return UsedInt(a.start<=b.start ? a.start:b.start, a.stop>=b.stop ? a.stop:b.stop);
}

inline UsedInt UsedInt_grown(const UsedInt &a,const SeqPos amt){
  if(isZero(a)) //no growing non-intervals
    return a;

  if(a.start>0)
    return UsedInt(max<SeqPos>(a.start-amt,1),a.stop+amt);
  else
    return UsedInt(a.start-amt,min<SeqPos>(a.stop+amt,-1));
}

UsedInt UsedInt_inverted(const UsedInt &a,const Sequence& s){
  if(isZero(a))
    return a;
  SeqPos length=s.length();
  if(a.start>0) //ugh. that took way more reverse engineering than it should have.
    return UsedInt(0-(length-a.start+1),0-(length-a.stop+1));
  else
    return UsedInt(a.start+length+1,a.stop+length+1);
}

UsedInt& UsedInt_invert(UsedInt &a,const Sequence& s){
  if(isZero(a))
    return a;
  SeqPos length=s.length();
  if(a.start>0){ //ugh. that took way more reverse engineering than it should have.
    a.start=0-(length-a.start+1);
    a.stop=0-(length-a.stop+1);
  }else{
    a.start=a.start+length+1;
    a.stop=a.stop+length+1;
  }
  return a;
}

UsedInt& UsedInt_rawInvert(UsedInt &x){ //use with care (most of the time sequence coordinates need to be inverted with the sequence-aware form above)
  swap<SeqPos>(x.start,x.stop);
  x.start=-x.start;
  x.stop=-x.stop;
  return x;
}

bool UsedInt_sanityCheck(const UsedInt &a){
  assert(a.start <= a.stop);
  return true;
}

AnchorSet::AnchorSet(const IntervalSet &a, UsedMap &usedMap) :
  members(a.members) //if opt.retainMembers is off, this should be empty anyway
{
  spaces.reserve(seq_count);
  for(size_t i=0;i<a.spaces.size();++i)
    spaces.push_back(usedMap.used[i].insert(a.spaces[i],this));
}

void IntervalSet::add(HashVal &a,SeqPos length){
  length--;
  if(a.pos)
    spaces.push_back(UsedInt(a.pos>0 ? a.pos:a.pos-length,
			     a.pos>0 ? a.pos+length:a.pos));
  else //it's a blank in an island
    spaces.push_back(UsedInt(0,0));
  //  assert(cout << "Added "<<spaces.back()<<" to interval set "<<*this<<endl);
}

SeqPos length(const UsedInt& a){
  return a.stop-a.start+1;
}

bool operator<(const Location &a,const Location &b){
  BitSequence *as=a.bitSeq(),*bs=b.bitSeq(),*pat=mfh->hashpat;
  word wc=pat->wordCount();
  SeqPos aPos=bitSeqCoords(a.pos),bPos=bitSeqCoords(b.pos);
  for(word wi=0;wi<wc;wi++,aPos+=WORDSIZE/2,bPos+=WORDSIZE/2){
    word pw=pat->readWord(wi);
    word aw=(as->wordAtBase(aPos) & pw), bw=(bs->wordAtBase(bPos) & pw);
    if(aw < bw){
      return true;
    } else if(aw > bw){
      return false;
    }
  }
  return false;  
}

bool operator<(const Window &a,const Window &b){
  for(SeqPos frame=0;frame<a.frames;frame++){
    word pword=a.pat->readWord(frame);
    word resa=a.buffer[frame] & pword;
    word resb=b.buffer[frame] & pword;
    if(resa<resb)
      return 1;
    if(resb<resa)
      return 0;
  }
  return 0;
}

void IntervalSet::invert(){
  for(unsigned i=0;i<spaces.size();++i){
    UsedInt_invert(spaces[i],*seqs[i]);
  }
}

void IntervalSet::exactExtend(){
  //  assert(cout << "Extend: "<<*this<<endl);
  int baseSeq=0;
  while(isZero(spaces[baseSeq])){
    baseSeq++;
    assert(baseSeq<seq_count);
  }
  assert(baseSeq<seq_count-1);
  BitSequence *mySeq=spaces[baseSeq].stop>0 ? seqs[baseSeq]->fwd :
    seqs[baseSeq]->rev,*tSeq;
  SeqPos mstart=bitSeqCoords(spaces[baseSeq].start),tstart;
  SeqPos mstop=bitSeqCoords(spaces[baseSeq].stop),tstop;
  SeqPos right=mySeq->length()-mstop,
    left=mstart;
  assert(mstart>=0);
  for(unsigned i=baseSeq+1;i<spaces.size();i++){
    if(isZero(spaces[i]))
       continue;
    tSeq=spaces[i].stop>0 ? seqs[i]->fwd :
      seqs[i]->rev;
    tstart=bitSeqCoords(spaces[i].start);
    tstop=bitSeqCoords(spaces[i].stop);
    if(spaces[i].stop<0)
      swap(tstart,tstop); //sneaky devils

    assert(tstart>=0);
    
    right=min<SeqPos>(tSeq->length()-tstop-1,min<SeqPos>(right,mySeq->cmpRight(mstop+1,*tSeq,tstop+1)));
    left=min<SeqPos>(tstart,min<SeqPos>(left,mySeq->cmpLeft(mstart-1,*tSeq,tstart-1)));
  }

  if(right || left){
    //    assert(cout << *this << "-> Extending "<<mstart<<","<<mstop<<" by "<<left<<","<<right<<" to ");
    assert(sanityCheck());
    if(right)
      for(unsigned i=0;i<spaces.size();i++){
	if(isZero(spaces[i]))
	  continue;
	if(spaces[i].stop>0)
	  spaces[i].stop+=right;
	else
	  spaces[i].start-=right;
      }
    if(left)
      for(unsigned i=0;i<spaces.size();i++){
	if(isZero(spaces[i]))
	  continue;
	if(spaces[i].start>0)
	  spaces[i].start-=left;
	else
	  spaces[i].stop+=left;
      }
    //    assert(cout << *this<<"<--"<<endl);
  }else{
    //    assert(cout << *this << "\\\\// Not extending"<<endl);
  }
  assert(sanityCheck());
}

Score IntervalSet::fuzzyExtend(){
  SeqPos maxExtendLeft=maxSeqPos,maxExtendRight=maxSeqPos;
  vector<BaseIterator> leftEdges,rightEdges;
  for(size_t i=0;i<spaces.size();i++){
    if(isZero(spaces[i]))
      continue;
    UsedInt bounds(seqs[i]->getSubSeqBounds(spaces[i].start));
    SeqPos leftPos=isRev(spaces[i]) ? spaces[i].stop:spaces[i].start;
    SeqPos rightPos=isRev(spaces[i]) ? spaces[i].start:spaces[i].stop;
    leftEdges.push_back(seqs[i]->iterate(leftPos));
    rightEdges.push_back(seqs[i]->iterate(rightPos));
    maxExtendLeft=min<SeqPos>(maxExtendLeft,isRev(spaces[i]) ? bounds.stop-spaces[i].stop:spaces[i].start-bounds.start);
    maxExtendRight=min<SeqPos>(maxExtendRight,isRev(spaces[i]) ? spaces[i].start-bounds.start:bounds.stop-spaces[i].stop);
  }
  SeqPos exRight=0,exLeft=0;
  Score scoreRight=0,scoreLeft=0;
  //  assert(cout << "** Checking fuzzyExtend on "<<*this<<" up to "<<maxExtendLeft<<","<<maxExtendRight<<endl);
  if(maxExtendRight)
    exRight=fuzzyExtendUntil(rightEdges,maxExtendRight,1,&scoreRight);
  if(maxExtendLeft)
    exLeft=fuzzyExtendUntil(leftEdges,maxExtendLeft,-1,&scoreLeft);
  if(exRight || exLeft){
    //    assert(cout << *this << "-> Fuzzy Extending by "<<exLeft<<","<<exRight<<" to ");
    for(size_t i=0;i<spaces.size();i++){
      if(isZero(spaces[i]))
	continue;
      if(exRight){
	if(isRev(spaces[i]))
	  spaces[i].start-=exRight;
	else
	  spaces[i].stop+=exRight;
      }
      if(exLeft){
	if(isRev(spaces[i]))
	  spaces[i].stop+=exLeft;
	else
	  spaces[i].start-=exLeft;
      }
    }
    //    assert(cout << *this<<"<--"<<endl);
  }else{
    //    assert(cout << *this << "\\\\// Not extending"<<endl);
  }
  return scoreRight+scoreLeft; //score boosted by this much through extend.
}

string IntervalSet::contents(string delim) const {
  ostringstream os;
  for(size_t si=0;si<spaces.size();si++){
    pair<BaseIterator,BaseIterator> r(seqs[si]->iterate(spaces[si]));
    while(r.first!=r.second)
      os << baseToString(*(r.first++));
    if(si+1!=spaces.size())
      os << delim;
  }
  return os.str();
}

Score IntervalSet::score(){
  if(opt.gappedAnchors)return 0; //no scoring for gapped intervals. too crazy.
  Score baseScore=0;
  vector<BaseIterator> column;
  vector<vector<Score> > pairScores;

  SeqPos width=0;
  for(size_t i=0;i<spaces.size();i++){
    if(isZero(spaces[i]))
      continue;
    if(width==0)
      width=spaces[i].stop-spaces[i].start+1;
    else
      assert((spaces[i].stop-spaces[i].start+1)==width);
    column.push_back(seqs[i]->iterate(spaces[i]).first);
  }
  for(SeqPos i=0;i<width;i++){
    if(opt.scoreByMinimumPair){
      addColumnPairScores(column,pairScores);
    }else{
      baseScore+=scoreColumn(column);
    }
    for(vector<BaseIterator>::iterator r=column.begin();
	r!=column.end();++r){
      ++(*r);
    }
  }
  if(opt.scoreByMinimumPair)
    return minimumPairScore(pairScores);
  return baseScore;
}

bool operator==(const Location &a,const Location &b) {
  BitSequence *mySeq=a.pos>0 ? a.seq()->fwd : a.seq()->rev,
    *tSeq=b.pos>0 ? b.seq()->fwd : b.seq()->rev;
  SeqPos mstop=bitSeqCoords(a.pos),
    tstop=bitSeqCoords(b.pos);
  return mySeq->equal(mstop,*tSeq,tstop,*mfh->hashpat);
}

ostream& operator<<(ostream &os, const Window &a){
  for(SeqPos i=0;i<a.frames-1;i++){
    os << wordToString(a.buffer[i]) << " ";
  }
  os << "+" << wordToString(a.buffer[a.frames-1]);
  return os;
}

ostream& operator<<(ostream &os,const BitSequence &a){
  if(a.isPattern)
    return os<<a.asPattern();
  else
    return os << a.asString();
}

ostream& operator<<(ostream &os,const Location &a){
  return os << "Location: ("<< a.seq()->getId()<<","<<a.seq()->extCoords(a.pos)<<")";
}

void BitSequence::maskString(string &str) const{
  SeqPos j=0;
  for(word i=0;i<word_count;i++){
    word w=readWord(i);
    word mask=highN(2);
    while(mask){
      if(!(w & mask))
	str[j]='.';
      j++;
      mask>>=2;
    }
  }
}

string wordToMaskedString(word w,word p,int bits){
  string foo(wordToString(w,bits));
  assert((int)foo.length()<=bits);
  SeqPos j=0;
  word mask=highN(2);
  while(mask && j<(SeqPos)foo.length()){
    if(!(p & mask))
      foo[j]='.';
    j++;
    mask>>=2;
  }
  assert((int)foo.length()<=bits);
  return foo;
}

string Window::toRawString(){
  string ret;
  for(unsigned i=0;i<buffer.size();i++)
    ret+=wordToString(buffer[i]);
  ret.resize(pat->length());
  return ret;
}

string Window::prettyString(){
  string ret(toRawString());
  pat->maskString(ret);
  size_t len=ret.length(),patlen=min<word>(pat->length(),hash_bits/2);
  switch(opt.quick_hash){
  case 2:
    for(size_t i=patlen;i<len;i++)
      ret[i]=tolower(ret[i]);
    break;
  case 1:
    for(size_t i=WORDSIZE/2;i<len;i++)
      ret[i]=tolower(ret[i]);
    break;
  case 3:
    for(size_t i=0;i<len;i++)
      if(!pat->hasher->used[i])
	ret[i]=tolower(ret[i]);
    break;
  }
  return ret;
}

void Window::slide(){
  pos+=2;
  SeqPos i;
  for(i=0;i<frames-1;i++){
    buffer[i]=(buffer[i]<<2) | (buffer[i+1]>>(WORDSIZE-2));
  }
  buffer[i]<<=2;

  //this should be done at the end. thus frame is always correct and no buffers are ever at empty
  if(pos/WORDSIZE!=frame){
    frame=pos/WORDSIZE;
    buffer[frames-1]=seq->readWord(frame+frames-1);
  }
}

void Window::slideWord(){
  //update to new positions
  pos+=WORDSIZE;
  frame++;

  SeqPos i;
  for(i=0;i<frames-1;i++){
    buffer[i]=buffer[i+1];
  }
  //[i] is now the last buffer
  buffer[i]=seq->readWord(frame+frames-1);
  SeqPos offset=MODWORDSIZE(pos);
  if(offset) //[i-1] needs to get the offset bits that had been chopped off of the previous [i]
    buffer[i-1]|=buffer[i]>>(WORDSIZE-offset);
  //and [i] needs to not duplicate those on a subsequent slide...
  buffer[i]<<=offset;
}

void Window::slide(SeqPos dist){ //bah. this function isnt actually used so, dont care that it's not as efficient as possible
  while(dist>WORDSIZE){
    slideWord();
    dist-=WORDSIZE;
  }

  while(dist>0){
    slide();
    dist-=2;
  }
}

void Window::initslide(SeqPos dist){
  assert(dist<=WORDSIZE-(MODWORDSIZE(pos)));
  pos+=dist;
  SeqPos i;
  for(i=0;i<frames-1;i++){
    buffer[i]=(buffer[i]<<dist) | (buffer[i+1]>>(WORDSIZE-dist));
  }
  buffer[i]<<=dist;

  if(pos/WORDSIZE!=frame){
    frame=pos/WORDSIZE;
    buffer[frames-1]=seq->readWord(frame+frames-1);
  }
}

bool Window::equals(const Window &a) const {
  assert(pat==a.pat); //dont be dumb
  if(pos+pat->bit_count>seq->bit_count) //overruns end of seq
    return false;
  for(SeqPos i=0;i<frames-1;i++){
    word result=(buffer[i] & pat->readWord(i)) ^ (a.buffer[i] & pat->readWord(i));
    if(result)
      return false; //a bit's amiss!
  }
  return true;
}

inline word Window::eqbases(const Window &a) const {
  return ~(buffer[0] ^ a.buffer[0]);
}

Window::Window(const UsedInt &a,const Sequence *s,BitSequence *p) :
  seq(a.start>0 ? s->fwd:s->rev),pat(p),pos(bitSeqCoords(a.start>0 ? a.start:a.stop)*2),
  frames(p->word_count+1),buffer(frames)
{
  SeqPos stop=pos;
  frame=pos/WORDSIZE;
  pos=frame*WORDSIZE;
  for(SeqPos i=0;i<frames;i++)
    buffer[i]=seq->readWord(frame+i);
  if(pos!=stop)
    initslide(MODWORDSIZE(stop)); //scuttle right the leftover bits
}

Window::Window(BitSequence *_seq,SeqPos _pos,BitSequence *_pat):
  seq(_seq),pat(_pat),pos(_pos*2),
  frames(_pat->word_count+1),buffer(frames)
{
  frame=pos/WORDSIZE;
  pos=frame*WORDSIZE;
  for(SeqPos i=0;i<frames;i++){
    buffer[i]=seq->readWord(frame+i);
  }
  if(pos!=_pos*2)
    initslide(MODWORDSIZE(_pos*2));//scuttle right the leftover bits
}

Window::Window(Location &v,BitSequence *p):
  seq(v.bitSeq()),pat(p),pos(bitSeqCoords(v.pos)*2),
  frames(p->word_count+1),buffer(frames)
{
  SeqPos stop=pos;
  frame=pos/WORDSIZE;
  pos=frame*WORDSIZE;
  for(SeqPos i=0;i<frames;i++)
    buffer[i]=seq->readWord(frame+i);
  if(pos!=stop)
    initslide(MODWORDSIZE(stop)); //scuttle right the leftover bits
}
  
word Window::hash(){
  word hash=hash_padding;
  word patpos=0;
  word filled=0,bit=WORDSIZE-2,frame=0;

  word patword=0,input;
  SeqPos lastpati=-1;

  switch(opt.quick_hash){
  case 2: //naive hash: use first hash_bits bits
  while(filled<WORDSIZE && patpos<pat->bit_count){
    if(pat->readCode(patpos)){
      hash=hash<<2 | ((buffer[frame]>>bit) & 3);
      filled+=2;
    }
    patpos+=2;
    if(bit==0){
      frame++;
      bit=WORDSIZE-2;
    }else{
      bit-=2;
    }
  }
  break;
  case 1: //use first word only (usually very bad waste of hash)
    hash=buffer[0] & pat->readWord(0);
    break;
  case 4:case 5:case 6:case 7:case 8: //use cryptographic hash functions. seems unreasonable, but for comparison's sake, lets give it a shot
    assert(cryptoHasher);
    hash^=cryptoHasher->digest(buffer,pat);
    break;
  case 0: //adaptive hasher with s-boxes. Hopefully even smarter.
    for(HashMethod::InputList::const_iterator i=pat->hasher->inputlist().begin();
	i!=pat->hasher->inputlist().end();i++){
      if(i->first!=lastpati){
	patword=pat->readWord(i->first);
	lastpati=i->first;
      }
      input=buffer[i->first] & patword;
      if(i->second==0)
	hash^=input;
      else {
	if(i->second>=0)
	  hash^=(input>>(word)(i->second*2));
	else
	  hash^=(input<<(word)(i->second*2));
      }
    }
    return sbox->confuse(hash & hash_mask);

  case 3:case 100: //adaptive hasher. freakin' smart (usually...)
    for(HashMethod::InputList::const_iterator i=pat->hasher->inputlist().begin();
	i!=pat->hasher->inputlist().end();i++){
      if(i->first!=lastpati){
	patword=pat->readRawWord(i->first);
	lastpati=i->first;
      }
      input=(buffer[i->first] & patword);
      if(i->second==0)
	hash^=input;
      else {
	if(i->second>=0)
	  hash^=(input>>i->second*2);
	else
	  hash^=(input<<i->second*2);
      }
    }
  }

  return hash & hash_mask;
}

ostream& operator<<(ostream &os, const AnchorSet &a){
  return os << a.asString();
}

string UsedMap::asString() {
  string ret;
  for(usedItree::iterator i=used[0].begin();
      i!=used[0].end();i++){
    ret+= (*i)->asString() + "\n";
  }
  return ret;
}

ostream& operator<<(ostream &os,const pair<word,SeqPos> &p){
  return os << p.first << ":" << p.second;
}

ostream& UsedMap::writeTfidf(ostream &os){
  if(used[0].empty())
    return os;
  if(!dfCount)
    dfCount=makeDfCount();
  for(usedItree::iterator i=used[0].begin();
      i!=used[0].end();i++){
    assert((*i));
    AnchorSet *&s=*i;
    if(!opt.hitfilter || s->hitCount()>=opt.hitfilter)
      os << s->uniqueness(this) << endl;
  }
  return os;
}

ostream& UsedMap::writeScores(ostream &os){
  if(used[0].empty())
    return os;
  for(usedItree::iterator i=used[0].begin();
      i!=used[0].end();i++){
    assert((*i));
    AnchorSet *&s=*i;
    if(!opt.hitfilter || s->hitCount()>=opt.hitfilter)
      os << s->score() << endl;
  }
  return os;
}

ostream& UsedMap::saveDetails(ostream &os,ostream &bitos){
  if(used[0].empty())
    return os;
  if(opt.tfidf && !dfCount)
    dfCount=makeDfCount();
  for(usedItree::iterator i=used[0].begin();
      i!=used[0].end();i++){
    assert((*i));
    AnchorSet *&s=*i;
    if(!opt.hitfilter || s->hitCount()>=opt.hitfilter){
      os << s->asString() << "\t" << s->hitCount();

      if(opt.retainMembers){
	double score;
	if(opt.tfidf){
	  if(opt.gappedAnchors)
	    score=s->uniqueness(this);
	  else
	    score=sqrt((s->uniqueness(this))*(s->score()));
	}
	else {
	  score=s->score();
	}
	os << "\t" << score << "\t";
	HashCount::iterator last=s->members.end();
	assert(!s->members.empty());
	last--;
	for(HashCount::iterator i=s->members.begin();i!=last;i++)
	  os << i->first << ":" << i->second <<",";
	os << last->first << ":" << last->second;
      }

      if(opt.bitscore && & bitos != &cerr){
	pair<SeqPos,SeqPos> scores(s->bitscore());
	bitos << scores.first << "\t" << scores.second << endl;
      }
      os << endl;
    }
  }
  return os;
}

int UsedMap::count() const {
  return used[0].size();
}

ostream& UsedMap::writeOut(ostream &os){
  if(used[0].empty())
    return os;
  for(usedItree::iterator i=used[0].begin();
      i!=used[0].end();i++){
    assert(*i);
    if(!opt.hitfilter || (*i)->hitCount()>=opt.hitfilter)
      os << (*i)->asString() << "\n";
  }
  //as these output sets can get huge, this might be a bad idea
  //  return os << asString();
  return os;
}

word* UsedMap::makeDfCount(){
  size_t size;
  word *df;
  if(opt.tfidf){
    assert(!dfCount);
#ifdef MURASAKI_MPI
    if(mpi_capable)
      size=mpi_total_hash_size;
    else
#endif
      size=hash_size;

    cout << "(Creating df table for "<<size<<" entries...)"<<endl;
    df=new (std::nothrow) word[size]; //this has a high probability of failing if we tuned hash table size to fill up memory completely...
    if(!df){
      cerr << "Warning: insufficient RAM for df table creation (disabling tfidf scoring)."<<endl;
      opt.tfidf=false;
      return df;
    }
    bzero(df,size*sizeof(word));

    if(count())
      for(usedItree::iterator i=used[0].begin();
	  i!=used[0].end();i++){
	assert(*i);
	AnchorSet *&s=*i;
	for(HashCount::iterator i=s->members.begin();i!=s->members.end();i++)
	  df[i->first]+=i->second;
      }
    return df;
  }
  return 0;
}

string AnchorSet::asString() const {
  string ret;
  for(unsigned i=0;i<spaces.size();i++){
    assert(*spaces[i]);
    ret+=asAnchor(spaces[i].key(),seqs[i]);
    if(i!=spaces.size()-1)
      ret+="\t";
  }
  return ret;
}

string asAnchor(const UsedInt& a,const Sequence *s){
  if(a.start<0) //gotta flip
    return dstring(s->extCoords(a.stop))+string("\t")+
      dstring(s->extCoords(a.start))+string("\t")+
      string(((a.start<0) != (a.stop<0)) ? "?":(a.start>=0 ? "+":"-"));
  else return dstring(s->extCoords(a.start))+string("\t")+
	 dstring(s->extCoords(a.stop))+string("\t")+
	 string(((a.start<0) != (a.stop<0)) ? "?":(a.start>=0 ? "+":"-"));
}

double AnchorSet::uniqueness(UsedMap *context) const {
  double sum=0;
#ifdef MURASAKI_MPI
  if(mpi_capable){
    if(!dfCount)dfCount=context->makeDfCount();
    if(dfCount)
      for(HashCount::const_iterator i=members.begin();i!=members.end();i++){
	sum+=i->second*log(anchors->count()/dfCount[i->first]);
      }
    return sum;
  }
#endif
  if(!opt.retainMembers){ //old way. takes into account non-anchored noise. not so cool
    for(HashCount::const_iterator i=members.begin();i!=members.end();i++){
      // wi = tfi*log(D/dfi) by the money
      if(!mfh->sizeAt(i->first)){
	throw MurasakiDebugException("What the monkey? "+dstring((long)i->first)+" isn't in hash?");
      }
      sum+=i->second*log((double)usedBuckets/(double)mfh->sizeAt(i->first));
    }
  }else{ //new way. separate counters. cleaner
    if(!dfCount)dfCount=context->makeDfCount();
    if(!dfCount)return 0;
    for(HashCount::const_iterator i=members.begin();i!=members.end();i++){
      if(!dfCount[i->first])
	throw MurasakiDebugException("dfCount missing at "+dstring((long)i->first)+" in anchor "+(this->asString()));
      sum+=i->second*log(anchors->count()/dfCount[i->first]);
    }
  }
  return sum;
}

pair<double,SeqPos> IntervalSet::entropy() const {
  double ret=0;
  vector<Window> windows;
  SeqPos shortest=0,shortlen=length(spaces[0]);
  for(int i=0;i<(int)spaces.size();i++){
    windows.push_back(Window(spaces[i],seqs[i],mfh->hashpat));
    if(shortlen>length(spaces[i])){
      shortest=i;
      shortlen=length(spaces[i]);
    }
  }

  int counters[4],offset;
  for(SeqPos pos=0;pos<shortlen;){
    for(offset=WORDSIZE-2;offset>=0 && pos<shortlen;pos++,offset-=2){
      memset(counters,0,sizeof(int)*4);
      
      for(uint s=0;s<spaces.size();s++)
	counters[(windows[s].firstWord()>>offset) & 3]++;
      
      //calculate (and add in) entropy for this column
      for(int b=0;b<4;b++)
	if(counters[b]){
	  double count=(double)counters[b];
	  ret+=count*log(count/globalBaseFreq[b]);
	}
    }
    for(vector<Window>::iterator ite=windows.begin();ite!=windows.end();ite++)
      ite->slideWord();
  }
  return pair<double,SeqPos>(ret,shortlen);
}

size_t AnchorSet::hitCount() const {
  size_t ret=0;
  for(HashCount::const_iterator i=members.begin();i!=members.end();++i)
    ret+=i->second;
  return ret;
}

Score AnchorSet::score() const {
  return IntervalSet(*this).score(); //theoretically it might be faster to have all the code here, but that's just stupid...
}

pair<SeqPos,SeqPos> AnchorSet::bitscore() const {
  vector<Window> windows;
  SeqPos shortest=0,shortlen=length(spaces[0].key());
  for(int i=0;i<(int)spaces.size();i++){
    windows.push_back(Window(spaces[i].key(),seqs[i],globalPat));
    if(shortlen>length(spaces[i].key())){
      shortest=i;
      shortlen=length(spaces[i].key());
    }
  }
  SeqPos eqbits=0;
  for(SeqPos pos=0;pos<shortlen;pos+=WORDSIZE/2){
    word ret=~0;
    //compare everything to ref seq. store in ret
    for(int comp=0;comp<(int)windows.size();comp++){
      if(comp==shortest)continue;
      word eq=windows[comp].eqbases(windows[shortest]);
      if(pos+WORDSIZE/2>length(spaces[comp].key()))
        eq=(eq & (highN(2*(length(spaces[comp].key())-pos))));
      eq=(((eq & alternating_mask)<<1) & eq);
      ret&=eq;
    }
    //count ret and add it up!
    eqbits+=popCount(ret);
    
    //shuffle everybody
    for(vector<Window>::iterator ite=windows.begin();ite!=windows.end();ite++)
      ite->slideWord();
  }
  return pair<SeqPos,SeqPos>(eqbits,shortlen);
}

string hashCacheName(string name, BitSequence *pat){
  ostringstream os;
  
  char *n = strdup(name.c_str());
  string fr;
  if ( !opt.skipFwd && !opt.skipRev ) fr = "both";
  if ( !opt.skipFwd &&  opt.skipRev ) fr = "fwd";
  if (  opt.skipFwd && !opt.skipRev ) fr = "rev";

  string rm;
  if ( opt.repeatMask ) rm="r"; else rm="nr";
					
    
  for(unsigned int i=0; i<strlen(n); i++)
    if(n[i]=='/' || n[i]=='.') n[i]='-';
    
  os << opt.cache_dir << "mc-" << n << "-";
  for(unsigned int p=0; p<pat->wordCount(); p++)
    os << hex << pat->readWord(p);
  os << "-" << fr;
  os << "-" << rm;
  os << "-" << dec << opt.rand_seed;
  os << "-" << hash_bits;
  free(n);
    
  return os.str();
}

RepeatMap::RepeatMap() : clusters() {}

void RepeatMap::add(const LocList &l){
  clusters.push_back(l);
}

void RepeatMap::writeOut(ostream &os){
  for(list<LocList>::iterator i=clusters.begin();i!=clusters.end();++i){
    LocList &l=*i;
    bool first=true;
    for(int s=0;s<seq_count;s++){
      if(l[s].empty()) //skip any seqs which aren't part of the repeat (possible with rifts)
	continue;
      if(first){ //first sequence out should tell _what_ the repeat is
	first=false;
	assert(l[s].front().seqId()<seq_count);
	os << "R: "<<Window(l[s].front(),globalPat).prettyString()<<endl;
      }
      os << s << ": ";
      LocSubList::iterator lite=l[s].begin();
      do {
	SeqPos p=lite->seq()->extCoords(lite->pos);
	os << dstring(p);
	++lite;
	if(lite!=l[s].end())
	  os << " ";
	else{
	  os << endl;
	  break;
	}
      }while(1);
    }
    os << endl; //extra new line on group end.
  }
}

IntervalSet::IntervalSet() :
  spaces() {
  spaces.reserve(seq_count);
  if(opt.retainMembers)
    members[activeHash]++;
}

IntervalSet::IntervalSet(const AnchorSet& a):
  spaces() , members(a.members)
{
  spaces.reserve(seq_count);
  for(vector<MapIte>::const_iterator i=a.spaces.begin();
      i!=a.spaces.end();++i)
    spaces.push_back(i->key());
}

IntervalSet::IntervalSet(const _IntervalIterator &intStart, const _IntervalIterator &intStop,
			 const _MemberIterator &memberStart,const _MemberIterator &memberStop){
  spaces.reserve(seq_count);
  for(_IntervalIterator i=intStart;i!=intStop;++i)
    spaces.push_back(*i);
  for(_MemberIterator i=memberStart;i!=memberStop;++i)
    members.insert(*i);
}

ostream& operator<<(ostream& os,const IntervalSet& a){
  os << "(";
  vector<UsedInt>::const_iterator i=a.spaces.begin();
  if(i==a.spaces.end())
    return os << ")";
  vector<UsedInt>::const_iterator next=i;
  int idx;
  for(next++,idx=0;next!=a.spaces.end();next++,i++,idx++)
    os << anchorCoords(*i,seqs[idx]) << ",";
  return os << anchorCoords(*i,seqs[idx]) << ")";
}

UsedInt anchorCoords(const UsedInt &b,Sequence *s){
  if(b.start<0)
    return s->length()-b;
  return b;
}

UsedInt operator-(SeqPos a,const UsedInt& b){
  return UsedInt(-1-(a+b.stop),-1-(a+b.start));
}

string SeqPosPair2string(const SeqPosPair& a){
  ostringstream os;
  os << "["<<a.first<<","<<a.second<<"]";
  return os.str();
}

BaseIterator::BaseIterator(Sequence *seq,SeqPos pos):
  rev(pos<0), src(rev ? seq->rev:seq->fwd),idx(bitSeqCoords(pos)),here(src->localRegionIte(idx)),prev(here),next(here)
{
  assert(!src->matchRegions.empty());
  if(prev!=src->matchRegions.begin())
    --prev;
  else
    prev=src->matchRegions.end();
  if(next!=src->matchRegions.end())
    ++next;
}

BaseIterator::BaseIterator(const BaseIterator& a):
  rev(a.rev),src(a.src),idx(a.idx),here(a.here),prev(a.prev),next(a.next)
{
}

BaseIterator& BaseIterator::operator++(){
  shiftFwd();
  return *this;
}

BaseIterator& BaseIterator::operator--(){
  shiftBack();
  return *this;
}

BaseIterator BaseIterator::operator++(int){
  BaseIterator old(*this);
  shiftFwd();
  return old;
}

BaseIterator BaseIterator::operator--(int){
  BaseIterator old(*this);
  shiftBack();
  return old;
}

bool BaseIterator::operator==(const BaseIterator &a) const{
  return src==a.src && idx==a.idx;
}

bool BaseIterator::operator!=(const BaseIterator &a) const{
  return !(*this==a);
}

BASE_TYPE BaseIterator::operator*() const {
  if(idx<here->first || idx>here->second)
      return BASE_N;
  return src->readBase(idx);
}

void BaseIterator::shiftFwd(){
  idx++;
  if(idx>here->second && next!=src->matchRegions.end() && idx>=next->first){
    prev=here;
    here=next;
    ++next;
  }
}

void BaseIterator::shiftBack(){
  idx--;
  if(idx<here->first && prev!=src->matchRegions.end() && idx<=prev->second){
    next=here;
    here=prev;
    if(here==src->matchRegions.begin())
      prev=src->matchRegions.end();
    else
      --prev;
  }
}

string BaseIterator::debugInfo(){
  ostringstream os;
  os <<src->genBitFilename();
  os <<"@"<<idx<<"="<<baseToString(**this)<<" in ";
  os << (prev==src->matchRegions.end() ? "??":SeqPosPair2string(*prev)) << " << ";
  os << SeqPosPair2string(*here) << " << ";
  os << (next==src->matchRegions.end() ? "??":SeqPosPair2string(*next));
  return os.str();
}