File: aligner.h

package info (click to toggle)
bowtie 1.2.3+dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 16,888 kB
  • sloc: cpp: 35,784; perl: 5,903; ansic: 1,247; sh: 1,180; python: 487; makefile: 426
file content (2092 lines) | stat: -rw-r--r-- 66,271 bytes parent folder | download | duplicates (2)
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
/**
 * aligner.h
 *
 * A generic class providing a stateful way to find alignments.
 */

#ifndef ALIGNER_H_
#define ALIGNER_H_

#include <iostream>
#include <set>
#include <stdint.h>
#include "seqan/sequence.h"
#include "assert_helpers.h"
#include "ebwt.h"
#include "pat.h"
#include "range.h"
#include "range_source.h"
#include "range_chaser.h"
#include "ref_aligner.h"
#include "reference.h"
#include "aligner_metrics.h"
#include "search_globals.h"

#ifdef PER_THREAD_TIMING
/// Based on http://stackoverflow.com/questions/16862620/numa-get-current-node-core
void get_cpu_and_node(int& cpu, int& node) {
	unsigned long a,d,c;
	__asm__ volatile("rdtscp" : "=a" (a), "=d" (d), "=c" (c));
	node = (c & 0xFFF000)>>12;
	cpu = c & 0xFFF;
}
#endif

/**
 * State machine for carrying out an alignment, which usually consists
 * of a series of phases that conduct different alignments using
 * different backtracking constraints.
 *
 * Each Aligner should have a dedicated PatternSourcePerThread.
 */
class Aligner {
public:
	Aligner(bool _done, bool rangeMode) :
		done(_done), patsrc_(NULL), bufa_(NULL), bufb_(NULL),
		rangeMode_(rangeMode)
	{ }

	virtual ~Aligner() { }
	/// Advance the range search by one memory op
	virtual bool advance() = 0;

	/// Prepare Aligner for the next read
	virtual void setQuery(PatternSourcePerThread *patsrc) {
		assert(patsrc != NULL);
		patsrc_ = patsrc;
		bufa_ = &patsrc->bufa();
		assert(bufa_ != NULL);
		bufb_ = &patsrc->bufb();
		alen_ = bufa_->length();
		blen_ = (bufb_ != NULL) ? bufb_->length() : 0;
		rand_.init(bufa_->seed);
	}

	/**
	 * Set to true if all searching w/r/t the current query is
	 * finished or if there is no current query.
	 */
	bool done;

protected:

	// Current read pair
	PatternSourcePerThread* patsrc_;
	Read* bufa_;
	uint32_t alen_;
	Read* bufb_;
	uint32_t blen_;
	bool rangeMode_;
	RandomSource rand_;
};

/**
 * Abstract parent factory class for constructing aligners of all kinds.
 */
class AlignerFactory {
public:
	virtual ~AlignerFactory() { }
	virtual Aligner* create() const = 0;

	/**
	 * Allocate a vector of n Aligners; use destroy(std::vector...) to
	 * free the memory.
	 */
	virtual std::vector<Aligner*>* create(uint32_t n) const {
		std::vector<Aligner*>* v = new std::vector<Aligner*>;
		for(uint32_t i = 0; i < n; i++) {
			v->push_back(create());
			assert(v->back() != NULL);
		}
		return v;
	}

	/// Free memory associated with the aligner
	virtual void destroy(Aligner* al) const {
		assert(al != NULL);
		// Free the Aligner
		delete al;
	}

	/// Free memory associated with an aligner list
	virtual void destroy(std::vector<Aligner*>* als) const {
		assert(als != NULL);
		// Free all of the Aligners
		for(size_t i = 0; i < als->size(); i++) {
			if((*als)[i] != NULL) {
				delete (*als)[i];
				(*als)[i] = NULL;
			}
		}
		// Free the vector
		delete als;
	}
};

/**
 * Coordinates multiple aligners of the same type (i.e. either all
 * single-end or all paired-end).
 */
class MultiAligner {
public:
	MultiAligner(
			uint32_t n,
			uint32_t qUpto,
			const AlignerFactory& alignFact,
			const PatternSourcePerThreadFactory& patsrcFact) :
			n_(n), qUpto_(qUpto),
			alignFact_(alignFact), patsrcFact_(patsrcFact),
			aligners_(NULL), patsrcs_(NULL)
	{
		aligners_ = alignFact_.create(n_);
		assert(aligners_ != NULL);
		patsrcs_ = patsrcFact_.create(n_);
		assert(patsrcs_ != NULL);
	}

	/// Free memory associated with the aligners and their pattern sources.
	virtual ~MultiAligner() {
		alignFact_.destroy(aligners_);
		patsrcFact_.destroy(patsrcs_);
	}

	/**
	 * Advance an array of aligners in parallel, using prefetches to
	 * try to hide all the latency.
	 */
	void run() {
		bool saw_last_read = false;
		while(!saw_last_read) {
			for(uint32_t i = 0; i < n_; i++) {
				if(!(*aligners_)[i]->done) {
					// Advance an aligner already in progress
					(*aligners_)[i]->advance();
				} else {
					if(saw_last_read) {
						break;
					}
					// Get a new read and initialize an aligner with it
					pair<bool, bool> ret = (*patsrcs_)[i]->nextReadPair();
					saw_last_read = ret.second;
					if(ret.first && (*patsrcs_)[i]->rdid() < qUpto_) {
						(*aligners_)[i]->setQuery((*patsrcs_)[i]);
					} else if (ret.first) {
						saw_last_read = true;
					}
				}
			}
		}
	}

protected:
	uint32_t n_;     /// Number of aligners
	uint32_t qUpto_; /// Number of reads to align before stopping
	const AlignerFactory&                  alignFact_;
	const PatternSourcePerThreadFactory&   patsrcFact_;
	std::vector<Aligner *>*                aligners_;
	std::vector<PatternSourcePerThread *>* patsrcs_;
};

/**
 * Coordinates multiple single-end and paired-end aligners, routing
 * reads to one or the other type as appropriate.
 */
class MixedMultiAligner {
public:
	MixedMultiAligner(
			uint32_t n,
			uint32_t qUpto,
			const AlignerFactory& alignSEFact,
			const AlignerFactory& alignPEFact,
			const PatternSourcePerThreadFactory& patsrcFact) :
			n_(n), qUpto_(qUpto),
			alignSEFact_(alignSEFact),
			alignPEFact_(alignPEFact),
			patsrcFact_(patsrcFact),
			alignersSE_(NULL),
			alignersPE_(NULL),
			seOrPe_(NULL),
			patsrcs_(NULL)
	{
		// Instantiate all single-end aligners
		alignersSE_ = alignSEFact_.create(n_);
		assert(alignersSE_ != NULL);
		// Instantiate all paired-end aligners
		alignersPE_ = alignPEFact_.create(n_);
		assert(alignersPE_ != NULL);
		// Allocate array of boolean flags indicating whether each of
		// the slots is currently using the single-end or paired-end
		// aligner
		seOrPe_ = new bool[n_];
		for(uint32_t i = 0; i < n_; i++) {
			seOrPe_[i] = true;
		}
		// Instantiate all read sources
		patsrcs_ = patsrcFact_.create(n_);
		assert(patsrcs_ != NULL);
	}

	/// Free memory associated with the aligners and their pattern sources.
	virtual ~MixedMultiAligner() {
		alignSEFact_.destroy(alignersSE_);
		alignPEFact_.destroy(alignersPE_);
		patsrcFact_.destroy(patsrcs_);
		delete[] seOrPe_;
	}

	/**
	 * Advance an array of aligners in parallel, using prefetches to
	 * try to hide all the latency.
	 */
	void run(bool verbose = false, int tid = -1) {
#ifdef PER_THREAD_TIMING
		uint64_t ncpu_changeovers = 0;
		uint64_t nnuma_changeovers = 0;
		
		int current_cpu = 0, current_node = 0;
		get_cpu_and_node(current_cpu, current_node);
	
		std::stringstream ss;
		std::string msg;
		ss << "thread: " << tid << " time: ";
		msg = ss.str();
		Timer timer(std::cout, msg.c_str());
#endif
		bool first = true;
		bool saw_last_read = false;
		if(n_ == 1) {
			Aligner *al = seOrPe_[0] ? (*alignersSE_)[0] : (*alignersPE_)[0];
			PatternSourcePerThread *ps = (*patsrcs_)[0];
			while(true) {
#ifdef PER_THREAD_TIMING
				int cpu = 0, node = 0;
				get_cpu_and_node(cpu, node);
				if(cpu != current_cpu) {
					ncpu_changeovers++;
					current_cpu = cpu;
				}
				if(node != current_node) {
					nnuma_changeovers++;
					current_node = node;
				}
#endif
				if(!first && !al->done) {
					// Advance an aligner already in progress; this is
					// the common case
					al->advance();
				} else {
					if(saw_last_read) {
						break;
					}
					// Get a new read
					pair<bool, bool> ret = ps->nextReadPair();
					saw_last_read = ret.second;
					if(ret.first && ps->rdid() < qUpto_) {
						if(ps->paired()) {
							// Read currently in buffer is paired-end
							(*alignersPE_)[0]->setQuery(ps);
							al = (*alignersPE_)[0];
							seOrPe_[0] = false; // false -> paired
						} else {
							// Read currently in buffer is single-end
							(*alignersSE_)[0]->setQuery(ps);
							al = (*alignersSE_)[0];
							seOrPe_[0] = true; // true = unpaired
						}
					} else if (ret.first) {
						break;
					}
				}
				first = false;
			}
		} else {
			while(true) {
#ifdef PER_THREAD_TIMING
				int cpu = 0, node = 0;
				get_cpu_and_node(cpu, node);
				if(cpu != current_cpu) {
					ncpu_changeovers++;
					current_cpu = cpu;
				}
				if(node != current_node) {
					nnuma_changeovers++;
					current_node = node;
				}
#endif
				bool saw_last_read = false;
				for(uint32_t i = 0; i < n_; i++) {
					Aligner *al = seOrPe_[i] ? (*alignersSE_)[i] :
											   (*alignersPE_)[i];
					if(!first && !al->done) {
						// Advance an aligner already in progress; this is
						// the common case
						al->advance();
					} else {
						if(saw_last_read) {
							break;
						}
						// Feed a new read to a vacant aligner
						PatternSourcePerThread *ps = (*patsrcs_)[i];
						// Get a new read
						pair<bool, bool> ret = ps->nextReadPair();
						saw_last_read = ret.second;
						if (ret.first && ps->rdid() < qUpto_) {
							if(ps->paired()) {
								// Read currently in buffer is paired-end
								(*alignersPE_)[i]->setQuery(ps);
								seOrPe_[i] = false; // false -> paired
							} else {
								// Read currently in buffer is single-end
								(*alignersSE_)[i]->setQuery(ps);
								seOrPe_[i] = true; // true = unpaired
							}
						} else if (ret.first) {
							break;
						}
					}
				}
				first = false;
			}
		}
#ifdef PER_THREAD_TIMING
		ss.str("");
		ss.clear();
		ss << "thread: " << tid << " cpu_changeovers: " << ncpu_changeovers << std::endl
		   << "thread: " << tid << " node_changeovers: " << nnuma_changeovers << std::endl;
		std::cout << ss.str();
#endif
	}

protected:
	uint32_t n_;     /// Number of aligners
	uint32_t qUpto_; /// Number of reads to align before stopping
	const AlignerFactory&                  alignSEFact_;
	const AlignerFactory&                  alignPEFact_;
	const PatternSourcePerThreadFactory&   patsrcFact_;
	std::vector<Aligner *>*                alignersSE_;
	std::vector<Aligner *>*                alignersPE_;
	bool *                                 seOrPe_;
	std::vector<PatternSourcePerThread *>* patsrcs_;
};

/**
 * An aligner for finding exact matches of unpaired reads.  Always
 * tries the forward-oriented version of the read before the reverse-
 * oriented read.
 */
template<typename TRangeSource>
class UnpairedAlignerV2 : public Aligner {
	typedef RangeSourceDriver<TRangeSource> TDriver;
public:
	UnpairedAlignerV2(
		EbwtSearchParams<String<Dna> >* params,
		TDriver* driver,
		RangeChaser<String<Dna> >* rchase,
		HitSink& sink,
		const HitSinkPerThreadFactory& sinkPtFactory,
		HitSinkPerThread* sinkPt,
		vector<String<Dna5> >& os,
		const BitPairReference* refs,
		bool rangeMode,
		bool verbose,
		bool quiet,
		int maxBts,
		bowtieChunkPool *pool,
		int *btCnt = NULL,
		AlignerMetrics *metrics = NULL) :
		Aligner(true, rangeMode),
		refs_(refs),
		doneFirst_(true),
		firstIsFw_(true),
		chase_(false),
		sinkPtFactory_(sinkPtFactory),
		sinkPt_(sinkPt),
		params_(params),
		rchase_(rchase),
		driver_(driver),
		verbose_(verbose),
		quiet_(quiet),
		maxBts_(maxBts),
		pool_(pool),
		btCnt_(btCnt),
		metrics_(metrics)
	{
		assert(pool_   != NULL);
		assert(sinkPt_ != NULL);
		assert(params_ != NULL);
		assert(driver_ != NULL);
	}

	virtual ~UnpairedAlignerV2() {
		delete driver_;  driver_  = NULL;
		delete params_;  params_  = NULL;
		delete rchase_;  rchase_  = NULL;
		delete[] btCnt_; btCnt_   = NULL;
		sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL;
	}

	/**
	 * Prepare this aligner for the next read.
	 */
	virtual void setQuery(PatternSourcePerThread* patsrc) {
		Aligner::setQuery(patsrc); // set fields & random seed
		if(metrics_ != NULL) {
			metrics_->nextRead(patsrc->bufa().patFw);
		}
		pool_->reset(&patsrc->bufa().name, (uint32_t)patsrc->rdid());
		if(patsrc->bufa().length() < 4) {
			if(!quiet_) {
				cerr << "Warning: Skipping read " << patsrc->bufa().name
				     << " because it is less than 4 characters long" << endl;
			}
			this->done = true;
			sinkPt_->finishRead(*patsrc_, true, true);
			return;
		}
		driver_->setQuery(patsrc, NULL);
		this->done = driver_->done;
		doneFirst_ = false;
		// Reset #-backtrack countdown
		if(btCnt_ != NULL) *btCnt_ = maxBts_;
		if(sinkPt_->setHits(patsrc->bufa().hitset)) {
			this->done = true;
			sinkPt_->finishRead(*patsrc_, true, true);
		}
		// Grab a bit from the pseudo-random seed to determine whether
		// to start with forward or reverse complement
		firstIsFw_ = ((patsrc->bufa().seed & 0x10) == 0);
		chase_ = false;
	}

	/**
	 * Helper for reporting an alignment.
	 */
	inline bool report(const Range& ra,
			TIndexOffU first,
			TIndexOffU second,
	                   uint32_t tlen)
	{
		bool ebwtFw = ra.ebwt->fw();
		params_->setFw(ra.fw);
		assert_eq(bufa_->color, color);
		return params_->reportHit(
				ra.fw ? (ebwtFw? bufa_->patFw    : bufa_->patFwRev) :
				        (ebwtFw? bufa_->patRc    : bufa_->patRcRev),
				ra.fw ? (ebwtFw? &bufa_->qual    : &bufa_->qualRev) :
				        (ebwtFw? &bufa_->qualRev : &bufa_->qual),
				&bufa_->name,
				bufa_->color,
				bufa_->primer,
				bufa_->trimc,
				colorExEnds,
				snpPhred,
				refs_,
				ebwtFw,
				ra.mms,                   // mismatch positions
				ra.refcs,                 // reference characters for mms
				ra.numMms,                // # mismatches
				make_pair(first, second), // position
				make_pair<TIndexOffU,TIndexOffU>(0, 0),          // (bogus) mate position
				true,                     // (bogus) mate orientation
				0,                        // (bogus) mate length
				make_pair(ra.top, ra.bot),// arrows
				tlen,                     // textlen
				alen_,                    // qlen
				ra.stratum,               // alignment stratum
				ra.cost,                  // cost, including qual penalty
				ra.bot - ra.top - 1,      // # other hits
				(uint32_t)patsrc_->rdid(),// pattern id
				bufa_->seed,              // pseudo-random seed
				0);                       // mate (0 = unpaired)
	}

	/**
	 * Advance the aligner.  Return true iff we're
	 * done with this read.
	 */
	virtual bool advance() {
		assert(!this->done);
		if(chase_) {
			assert(!rangeMode_);
			assert(driver_->foundRange);
			assert(!sinkPt_->irrelevantCost(driver_->range().cost));
			if(!rchase_->foundOff() && !rchase_->done) {
				rchase_->advance();
				return false;
			}
			if(rchase_->foundOff()) {
				this->done = report(driver_->range(), rchase_->off().first,
				                    rchase_->off().second, rchase_->tlen());
				rchase_->reset();
			} else {
				assert(rchase_->done);
				// Forget this range; keep looking for ranges
				chase_ = false;
				driver_->foundRange = false;
				this->done = driver_->done;
			}
		}
		// Still advancing a
		if(!this->done && !chase_) {
			assert(!driver_->done || driver_->foundRange);
			if(driver_->foundRange) {
				const Range& ra = driver_->range();
				assert(!sinkPt_->irrelevantCost(ra.cost));
				assert(ra.repOk());
				if(rangeMode_) {
					this->done = report(ra, ra.top, ra.bot, 0);
					driver_->foundRange = false;
				} else {
					rchase_->setTopBot(ra.top, ra.bot, alen_, rand_, ra.ebwt);
					if(rchase_->foundOff()) {
						this->done = report(
								ra, rchase_->off().first,
								rchase_->off().second, rchase_->tlen());
						rchase_->reset();
					}
					if(!rchase_->done && !sinkPt_->irrelevantCost(ra.cost)) {
						// Keep chasing this range
						chase_ = true;
					} else {
						driver_->foundRange = false;
					}
				}
			} else {
				this->done = sinkPt_->irrelevantCost(driver_->minCost);
				if(!this->done) {
					driver_->advance(ADV_COST_CHANGES);
				} else {
					// No longer necessarily true with chain input
					//assert(!sinkPt_->spanStrata());
				}
			}
			if(driver_->done && !driver_->foundRange && !chase_) {
				this->done = true;
			}
		}
		if(this->done) {
			sinkPt_->finishRead(*patsrc_, true, true);
		}
		return this->done;
	}

protected:

	// Reference sequences (needed for colorspace decoding)
	const BitPairReference* refs_;

	// Progress state
	bool doneFirst_;
	bool firstIsFw_;
	bool chase_;

	// Temporary HitSink; to be deleted
	const HitSinkPerThreadFactory& sinkPtFactory_;
	HitSinkPerThread* sinkPt_;

	// State for alignment
	EbwtSearchParams<String<Dna> >* params_;

	// State for getting alignments from ranges statefully
	RangeChaser<String<Dna> >* rchase_;

	// Range-finding state
	TDriver* driver_;

	bool verbose_; // be talkative
	bool quiet_; // don't print informational/warning info

	const int maxBts_;
	bowtieChunkPool *pool_;
	int *btCnt_;
	AlignerMetrics *metrics_;
};

/**
 * An aligner for finding paired alignments while operating entirely
 * within the Burrows-Wheeler domain.
 */
template<typename TRangeSource>
class PairedBWAlignerV1 : public Aligner {

	typedef std::pair<TIndexOffU,TIndexOffU> UPair;
	typedef std::vector<UPair> UPairVec;
	typedef std::vector<Range> TRangeVec;
	typedef RangeSourceDriver<TRangeSource> TDriver;
	typedef std::pair<uint64_t, uint64_t> TU64Pair;
	typedef std::set<TU64Pair> TSetPairs;

public:
	PairedBWAlignerV1(
		EbwtSearchParams<String<Dna> >* params,
		TDriver* driver1Fw, TDriver* driver1Rc,
		TDriver* driver2Fw, TDriver* driver2Rc,
		RefAligner<String<Dna5> >* refAligner,
		RangeChaser<String<Dna> >* rchase,
		HitSink& sink,
		const HitSinkPerThreadFactory& sinkPtFactory,
		HitSinkPerThread* sinkPt,
		bool fw1, bool fw2,
		uint32_t minInsert,
		uint32_t maxInsert,
		bool dontReconcile,
		uint32_t symCeiling,
		uint32_t mixedThresh,
		uint32_t mixedAttemptLim,
		const BitPairReference* refs,
		bool rangeMode,
		bool verbose,
		bool quiet,
		int maxBts,
		bowtieChunkPool *pool,
		int *btCnt) :
		Aligner(true, rangeMode),
		refs_(refs),
		patsrc_(NULL), qlen1_(0), qlen2_(0), doneFw_(true),
		doneFwFirst_(true),
		chase1Fw_(false), chase1Rc_(false),
		chase2Fw_(false), chase2Rc_(false),
		delayedChase1Fw_(false), delayedChase1Rc_(false),
		delayedChase2Fw_(false), delayedChase2Rc_(false),
		refAligner_(refAligner),
		sinkPtFactory_(sinkPtFactory),
		sinkPt_(sinkPt),
		params_(params),
		minInsert_(minInsert),
		maxInsert_(maxInsert),
		dontReconcile_(dontReconcile),
		symCeiling_(symCeiling),
		mixedThresh_(mixedThresh),
		mixedAttemptLim_(mixedAttemptLim),
		mixedAttempts_(0),
		fw1_(fw1), fw2_(fw2),
		rchase_(rchase),
		verbose_(verbose),
		quiet_(quiet),
		maxBts_(maxBts),
		pool_(pool),
		btCnt_(btCnt),
		driver1Fw_(driver1Fw), driver1Rc_(driver1Rc),
		offs1FwSz_(0), offs1RcSz_(0),
		driver2Fw_(driver2Fw), driver2Rc_(driver2Rc),
		offs2FwSz_(0), offs2RcSz_(0),

		chaseL_fw_       (fw1_ ? chase1Fw_        : chase1Rc_),
		chaseR_fw_       (fw2_ ? chase2Fw_        : chase2Rc_),
		delayedchaseL_fw_(fw1_ ? delayedChase1Fw_ : delayedChase1Rc_),
		delayedchaseR_fw_(fw2_ ? delayedChase2Fw_ : delayedChase2Rc_),
		drL_fw_          (fw1_ ? *driver1Fw_      : *driver1Rc_),
		drR_fw_          (fw2_ ? *driver2Fw_      : *driver2Rc_),
		offsLarr_fw_     (fw1_ ? offs1FwArr_      : offs1RcArr_),
		offsRarr_fw_     (fw2_ ? offs2FwArr_      : offs2RcArr_),
		rangesLarr_fw_   (fw1_ ? ranges1FwArr_    : ranges1RcArr_),
		rangesRarr_fw_   (fw2_ ? ranges2FwArr_    : ranges2RcArr_),
		offsLsz_fw_      (fw1_ ? offs1FwSz_       : offs1RcSz_),
		offsRsz_fw_      (fw2_ ? offs2FwSz_       : offs2RcSz_),

		chaseL_rc_       (fw2_ ? chase2Rc_        : chase2Fw_),
		chaseR_rc_       (fw1_ ? chase1Rc_        : chase1Fw_),
		delayedchaseL_rc_(fw2_ ? delayedChase2Rc_ : delayedChase2Fw_),
		delayedchaseR_rc_(fw1_ ? delayedChase1Rc_ : delayedChase1Fw_),
		drL_rc_          (fw2_ ? *driver2Rc_      : *driver2Fw_),
		drR_rc_          (fw1_ ? *driver1Rc_      : *driver1Fw_),
		offsLarr_rc_     (fw2_ ? offs2RcArr_      : offs2FwArr_),
		offsRarr_rc_     (fw1_ ? offs1RcArr_      : offs1FwArr_),
		rangesLarr_rc_   (fw2_ ? ranges2RcArr_    : ranges2FwArr_),
		rangesRarr_rc_   (fw1_ ? ranges1RcArr_    : ranges1FwArr_),
		offsLsz_rc_      (fw2_ ? offs2RcSz_       : offs2FwSz_),
		offsRsz_rc_      (fw1_ ? offs1RcSz_       : offs1FwSz_),

		chaseL_       (&chaseL_fw_),
		chaseR_       (&chaseR_fw_),
		delayedchaseL_(&delayedchaseL_fw_),
		delayedchaseR_(&delayedchaseR_fw_),
		drL_          (&drL_fw_),
		drR_          (&drR_fw_),
		offsLarr_     (offsLarr_fw_),
		offsRarr_     (offsRarr_fw_),
		rangesLarr_   (rangesLarr_fw_),
		rangesRarr_   (rangesRarr_fw_),
		offsLsz_      (&offsLsz_fw_),
		offsRsz_      (&offsRsz_fw_),
		donePair_     (&doneFw_),
		fwL_(fw1),
		fwR_(fw2),
		verbose2_(false)
	{
		assert(pool_      != NULL);
		assert(sinkPt_    != NULL);
		assert(params_    != NULL);
		assert(driver1Fw_ != NULL);
		assert(driver1Rc_ != NULL);
		assert(driver2Fw_ != NULL);
		assert(driver2Rc_ != NULL);
	}

	virtual ~PairedBWAlignerV1() {
		delete driver1Fw_; driver1Fw_ = NULL;
		delete driver1Rc_; driver1Rc_ = NULL;
		delete driver2Fw_; driver2Fw_ = NULL;
		delete driver2Rc_; driver2Rc_ = NULL;
		delete params_;    params_    = NULL;
		delete rchase_;    rchase_    = NULL;
		delete[] btCnt_;   btCnt_     = NULL;
		delete refAligner_; refAligner_ = NULL;
		sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL;
	}

	/**
	 * Prepare this aligner for the next read.
	 */
	virtual void setQuery(PatternSourcePerThread* patsrc) {
		Aligner::setQuery(patsrc); // set fields & random seed
		assert(!patsrc->bufb().empty());
		// Give all of the drivers pointers to the relevant read info
		patsrc_ = patsrc;
		pool_->reset(&patsrc->bufa().name, (uint32_t)patsrc->rdid());
		if(patsrc->bufa().length() < 4 || patsrc->bufb().length() < 4) {
			if(!quiet_) {
				cerr << "Warning: Skipping pair " << patsrc->bufa().name
					 << " because a mate is less than 4 characters long" << endl;
			}
			this->done = true;
			sinkPt_->finishRead(*patsrc_, true, true);
			return;
		}
		driver1Fw_->setQuery(patsrc, NULL);
		driver1Rc_->setQuery(patsrc, NULL);
		driver2Fw_->setQuery(patsrc, NULL);
		driver2Rc_->setQuery(patsrc, NULL);
		qlen1_ = patsrc_->bufa().length();
		qlen2_ = patsrc_->bufb().length();
		if(btCnt_ != NULL) (*btCnt_) = maxBts_;
		// Neither orientation is done
		doneFw_   = false;
		doneFwFirst_ = true;
		this->done   = false;
		// No ranges are being chased yet
		chase1Fw_ = false;
		chase1Rc_ = false;
		chase2Fw_ = false;
		chase2Rc_ = false;
		delayedChase1Fw_ = false;
		delayedChase1Rc_ = false;
		delayedChase2Fw_ = false;
		delayedChase2Rc_ = false;
		// Clear all intermediate ranges
		for(size_t i = 0; i < 32; i++) {
			offs1FwArr_[i].clear();   offs1RcArr_[i].clear();
			offs2FwArr_[i].clear();   offs2RcArr_[i].clear();
			ranges1FwArr_[i].clear(); ranges1RcArr_[i].clear();
			ranges2FwArr_[i].clear(); ranges2RcArr_[i].clear();
		}
		offs1FwSz_ = offs1RcSz_ = offs2FwSz_ = offs2RcSz_ = 0;
		chaseL_        = &chaseL_fw_;
		chaseR_        = &chaseR_fw_;
		delayedchaseL_ = &delayedchaseL_fw_;
		delayedchaseR_ = &delayedchaseR_fw_;
		drL_           = &drL_fw_;
		drR_           = &drR_fw_;
		offsLarr_      = offsLarr_fw_;
		offsRarr_      = offsRarr_fw_;
		rangesLarr_    = rangesLarr_fw_;
		rangesRarr_    = rangesRarr_fw_;
		offsLsz_       = &offsLsz_fw_;
		offsRsz_       = &offsRsz_fw_;
		donePair_      = &doneFw_;
		fwL_           = fw1_;
		fwR_           = fw2_;
		mixedAttempts_ = 0;
		pairs_fw_.clear();
		pairs_rc_.clear();
#ifndef NDEBUG
		allTopsL_fw_.clear();
		allTopsR_fw_.clear();
		allTopsL_rc_.clear();
		allTopsR_rc_.clear();
#endif
	}

	/**
	 * Advance the aligner by one memory op.  Return true iff we're
	 * done with this read.
	 *
	 * A call to this function does one of many things:
	 * 1. Advance a RangeSourceDriver and check if it found a new range
	 * 2. Advance a RowChaseDriver and check if it found a reference
	 *    offset for a an alignment in a range
	 */
	virtual bool advance() {
		assert(!this->done);
		if(doneFw_ && doneFwFirst_) {
			if(verbose2_) cout << "--" << endl;
			chaseL_        = &chaseL_rc_;
			chaseR_        = &chaseR_rc_;
			delayedchaseL_ = &delayedchaseL_rc_;
			delayedchaseR_ = &delayedchaseR_rc_;
			drL_           = &drL_rc_;
			drR_           = &drR_rc_;
			offsLarr_      = offsLarr_rc_;
			offsRarr_      = offsRarr_rc_;
			rangesLarr_    = rangesLarr_rc_;
			rangesRarr_    = rangesRarr_rc_;
			offsLsz_       = &offsLsz_rc_;
			offsRsz_       = &offsRsz_rc_;
			donePair_      = &this->done;
			fwL_           = !fw2_;
			fwR_           = !fw1_;
			doneFwFirst_   = false;
			mixedAttempts_ = 0;
		}
		bool chasing = *chaseL_ || *chaseR_;
		if(chasing && !rchase_->foundOff() && !rchase_->done) {
			rchase_->advance();
			return false;
		}
		advanceOrientation(!doneFw_);
		if(this->done) {
			if(verbose2_) cout << "----" << endl;
			sinkPt_->finishRead(*patsrc_, true, true);
		}
		return this->done;
	}

protected:

	/**
	 * Helper for reporting a pair of alignments.  As of now, we report
	 * a paired alignment by reporting two consecutive alignments, one
	 * for each mate.
	 */
	bool report(const Range& rL, // range for upstream mate
	            const Range& rR, // range for downstream mate
	            TIndexOffU first,  // ref idx
	            TIndexOffU upstreamOff, // offset for upstream mate
	            TIndexOffU dnstreamOff, // offset for downstream mate
	            TIndexOffU tlen, // length of ref
	            bool pairFw,   // whether the pair is being mapped to fw strand
	            bool ebwtFwL,
	            bool ebwtFwR)
	{
		assert(gAllowMateContainment || upstreamOff < dnstreamOff);
		TIndexOffU spreadL = rL.bot - rL.top;
		TIndexOffU spreadR = rR.bot - rR.top;
		TIndexOffU oms = min(spreadL, spreadR) - 1;
		Read* bufL = pairFw ? bufa_ : bufb_;
		Read* bufR = pairFw ? bufb_ : bufa_;
		TIndexOffU lenL = pairFw ? alen_ : blen_;
		TIndexOffU lenR = pairFw ? blen_ : alen_;
		bool ret;
		assert(!params_->sink().exceededOverThresh());
		params_->setFw(rL.fw);
		assert_eq(bufL->color, color);
		// Print upstream mate first
		ret = params_->reportHit(
				rL.fw ? (ebwtFwL?  bufL->patFw  :  bufL->patFwRev) :
					    (ebwtFwL?  bufL->patRc  :  bufL->patRcRev),
				rL.fw ? (ebwtFwL? &bufL->qual    : &bufL->qualRev) :
				        (ebwtFwL? &bufL->qualRev : &bufL->qual),
				&bufL->name,
				bufL->color,
				bufL->primer,
				bufL->trimc,
				colorExEnds,
				snpPhred,
				refs_,
				ebwtFwL,
				rL.mms,                       // mismatch positions
				rL.refcs,                     // reference characters for mms
				rL.numMms,                    // # mismatches
				make_pair(first, upstreamOff),// position
				make_pair(first, dnstreamOff),// mate position
				rR.fw,                        // mate orientation
				lenR,                         // mate length
				make_pair(rL.top, rL.bot),    // arrows
				tlen,                         // textlen
				lenL,                         // qlen
				rL.stratum,                   // alignment stratum
				rL.cost,                      // cost, including quality penalty
				oms,                          // # other hits
				bufL->patid,
				bufL->seed,
				pairFw ? 1 : 2);
		if(ret) {
			return true; // can happen when -m is set
		}
		params_->setFw(rR.fw);
		assert_eq(bufR->color, color);
		ret = params_->reportHit(
				rR.fw ? (ebwtFwR?  bufR->patFw  :  bufR->patFwRev) :
					    (ebwtFwR?  bufR->patRc  :  bufR->patRcRev),
				rR.fw ? (ebwtFwR? &bufR->qual    : &bufR->qualRev) :
				        (ebwtFwR? &bufR->qualRev : &bufR->qual),
				&bufR->name,
				bufR->color,
				bufR->primer,
				bufR->trimc,
				colorExEnds,
				snpPhred,
				refs_,
				ebwtFwR,
				rR.mms,                       // mismatch positions
				rR.refcs,                     // reference characters for mms
				rR.numMms,                    // # mismatches
				make_pair(first, dnstreamOff),// position
				make_pair(first, upstreamOff),// mate position
				rL.fw,                        // mate orientation
				lenL,                         // mate length
				make_pair(rR.top, rR.bot),    // arrows
				tlen,                         // textlen
				lenR,                         // qlen
				rR.stratum,                   // alignment stratum
				rR.cost,                      // cost, including quality penalty
				oms,                          // # other hits
				bufR->patid,
				bufR->seed,
				pairFw ? 2 : 1);
		return ret;
	}

	bool report(const Range& rL, // range for upstream mate
	            const Range& rR, // range for downstream mate
	            TIndexOffU first,  // ref idx
	            TIndexOffU upstreamOff, // offset for upstream mate
	            TIndexOffU dnstreamOff, // offset for downstream mate
	            TIndexOffU tlen, // length of ref
	            bool pairFw)   // whether the pair is being mapped to fw strand
	{
		return report(rL, rR, first, upstreamOff,
		              dnstreamOff, tlen,
		              pairFw, rL.ebwt->fw(), rR.ebwt->fw());
	}

	/**
	 * Given a vector of reference positions where one of the two mates
	 * (the "anchor" mate) has aligned, look directly at the reference
	 * sequence for instances where the other mate (the "outstanding"
	 * mate) aligns such that mating constraint is satisfied.
	 */
	bool resolveOutstandingInRef(const bool off1,
	                             const UPair& off,
	                             const TIndexOffU tlen,
	                             const Range& range)
	{
		assert(refs_->loaded());
		assert_lt(off.first, refs_->numRefs());
		// If matchRight is true, then we're trying to align the other
		// mate to the right of the already-aligned mate.  Otherwise,
		// to the left.
		bool matchRight = (off1 ? !doneFw_ : doneFw_);
		// Sequence and quals for mate to be matched
		bool fw = off1 ? fw2_ : fw1_; // whether outstanding mate is fw/rc
		if(doneFw_) fw = !fw;
		// 'seq' gets sequence of outstanding mate w/r/t the forward
		// reference strand
		const String<Dna5>& seq  = fw ? (off1 ? patsrc_->bufb().patFw   :
		                                        patsrc_->bufa().patFw)  :
		                                (off1 ? patsrc_->bufb().patRc   :
		                                        patsrc_->bufa().patRc);
		// 'seq' gets qualities of outstanding mate w/r/t the forward
		// reference strand
		const String<char>& qual = fw ? (off1 ? patsrc_->bufb().qual  :
		                                        patsrc_->bufa().qual) :
		                                (off1 ? patsrc_->bufb().qualRev  :
		                                        patsrc_->bufa().qualRev);
		uint32_t qlen = (uint32_t)seqan::length(seq);  // length of outstanding mate
		uint32_t alen = (off1 ? patsrc_->bufa().length() :
		                        patsrc_->bufb().length());
		int minins = minInsert_;
		int maxins = maxInsert_;
		// Let minins and maxins be the minimum and maximum insert
		// lengths once we account for the trimming applied to the
		// mates.  The idea is that the insert constraint placed by
		// the user applies to the raw reads, not the trimmed reads.
		if(fw1_) {
			minins = max<int>(0, minins - patsrc_->bufa().trimmed5);
			maxins = max<int>(0, maxins - patsrc_->bufa().trimmed5);
		} else {
			minins = max<int>(0, minins - patsrc_->bufa().trimmed3);
			maxins = max<int>(0, maxins - patsrc_->bufa().trimmed3);
		}
		if(fw2_) {
			minins = max<int>(0, minins - patsrc_->bufb().trimmed3);
			maxins = max<int>(0, maxins - patsrc_->bufb().trimmed3);
		} else {
			minins = max<int>(0, minins - patsrc_->bufb().trimmed5);
			maxins = max<int>(0, maxins - patsrc_->bufb().trimmed5);
		}
		// Sanity check minins and maxins
		assert_geq(minins, 0);
		assert_geq(maxins, 0);
		assert_geq(maxins, minins);
		// Don't even try if either of the mates is longer than the
		// maximum insert size.
		if((uint32_t)maxins <= max(qlen, alen)) {
			return false;
		}
		const TIndexOffU tidx = off.first;
		const TIndexOffU toff = off.second;
		// Set begin/end to be a range of all reference
		// positions that are legally permitted to be involved in
		// the alignment of the outstanding mate.
		//
		// Note that one of the constraints imposed on which positions
		// go into this range is that the opposite mate cannot be
		// contained entirely within the anchor mate, or vice versa.
		TIndexOffU begin, end;
		TIndexOffU insDiff = maxins - minins;
		if(matchRight) {
			end = toff + maxins;
			// Adding 1 disallows the opposite from starting at the
			// left-hand edge of the anchor mate.
			begin = toff + (gAllowMateContainment ? 0 : 1);
			// We can also add a bit more if qlen is less than alen,
			// since we're requiring that opposite not be contained
			// within anchor.
			if(!gAllowMateContainment && qlen < alen) {
				begin += alen-qlen;
			}
			if(end > insDiff + qlen) {
				begin = max<TIndexOffU>(begin, end - insDiff - qlen);
			}
			end = min<TIndexOffU>(refs_->approxLen(tidx), end);
			begin = min<TIndexOffU>(refs_->approxLen(tidx), begin);
		} else {
			if(toff + alen < (TIndexOffU)maxins) {
				begin = 0;
			} else {
				begin = toff + alen - maxins;
			}
			uint32_t mi = min<uint32_t>(alen, qlen);
			if(gAllowMateContainment) {
				end = toff + alen;
			} else {
				end = toff + mi - 1;
				end = min<TIndexOffU>(end, toff + alen - minins + qlen - 1);
				if(toff + alen + qlen < (uint32_t)minins + 1) end = 0;
			}
		}
		// Check if there's not enough space in the range to fit an
		// alignment for the outstanding mate.
		if(end - begin < qlen) return false;
		std::vector<Range> ranges;
		std::vector<TIndexOffU> offs;
		refAligner_->find(1, tidx, refs_, seq, qual, begin, end, ranges,
		                  offs, doneFw_ ? &pairs_rc_ : &pairs_fw_,
		                  toff, fw);
		assert_eq(ranges.size(), offs.size());
		for(size_t i = 0; i < ranges.size(); i++) {
			Range& r = ranges[i];
			// Fill in fields that aren't filled in by the RefAligner
			r.fw = fw;
			r.cost |= (r.stratum << 14);
			r.mate1 = !off1;
			const TIndexOffU result = offs[i];
			// NOTE: We have no idea what the BW range delimiting the
			// opposite hit is, because we were operating entirely in
			// reference space when we found it.  For now, we just copy
			// the known range's top and bot for now.
			r.top = range.top;
			r.bot = range.bot;
			bool ebwtLFw = matchRight ? range.ebwt->fw() : true;
			bool ebwtRFw = matchRight ? true : range.ebwt->fw();
			if(report(
				matchRight ? range : r, // range for upstream mate
				matchRight ? r : range, // range for downstream mate
				tidx,                   // ref idx
				matchRight ? toff : result, // upstream offset
				matchRight ? result : toff, // downstream offset
				tlen,       // length of ref
				!doneFw_,   // whether the pair is being mapped to fw strand
				ebwtLFw,
				ebwtRFw)) return true;
		}
		return false;
	}

	/**
	 * Advance paired-end alignment.
	 */
	void advanceOrientation(bool pairFw) {
		assert(!this->done);
		assert(!*donePair_);
		assert(!*chaseL_ || !*chaseR_);
		if(*chaseL_) {
			assert(!rangeMode_);
			assert(!*delayedchaseL_);
			assert(drL_->foundRange);
			assert(rchase_->foundOff() || rchase_->done);
			if(rchase_->foundOff()) {
				// Resolve this against the reference loci
				// determined for the other mate
				const bool overThresh = (*offsLsz_ + *offsRsz_) > mixedThresh_;
				if(!this->done && (overThresh || dontReconcile_)) {
					// Because the total size of both ranges exceeds
					// our threshold, we're now operating in "mixed
					// mode"
					const Range& r = drL_->range();
					assert(r.repOk());
					if(verbose_) cout << "Making an attempt to find the outstanding mate" << endl;
					this->done = resolveOutstandingInRef(
							pairFw, rchase_->off(),
					        r.ebwt->_plen[rchase_->off().first], r);
					if(++mixedAttempts_ > mixedAttemptLim_) {
						// Give up on this pair
						*donePair_ = true;
						return;
					}
				}
				rchase_->reset();
			} else {
				assert(rchase_->done);
				// Forget this range; keep looking for ranges
				*chaseL_ = false;
				drL_->foundRange = false;
				if(verbose_) cout << "Done with chase for first mate" << endl;
				if(*delayedchaseR_) {
					// Start chasing the delayed range
					if(verbose_) cout << "Resuming delayed chase for second mate" << endl;
					assert(drR_->foundRange);
					const Range& r = drR_->range();
					assert(r.repOk());
					TIndexOffU top = r.top;
					TIndexOffU bot = r.bot;
					uint32_t qlen = doneFw_? qlen1_ : qlen2_;
					rchase_->setTopBot(top, bot, qlen, rand_, r.ebwt);
					*chaseR_ = true;
					*delayedchaseR_ = false;
				}
			}
		} else if(*chaseR_) {
			assert(!rangeMode_);
			assert(!*delayedchaseR_);
			assert(drR_->foundRange);
			assert(rchase_->foundOff() || rchase_->done);
			if(rchase_->foundOff()) {
				// Resolve this against the reference loci
				// determined for the other mate
				const bool overThresh = (*offsLsz_ + *offsRsz_) > mixedThresh_;
				if(!this->done && (overThresh || dontReconcile_)) {
					// Because the total size of both ranges exceeds
					// our threshold, we're now operating in "mixed
					// mode"
					const Range& r = drR_->range();
					if(verbose_) cout << "Making an attempt to find the outstanding mate" << endl;
					this->done = resolveOutstandingInRef(
							!pairFw, rchase_->off(),
					        r.ebwt->_plen[rchase_->off().first], r);
					if(++mixedAttempts_ > mixedAttemptLim_) {
						// Give up on this pair
						*donePair_ = true;
						return;
					}
				}
				rchase_->reset();
			} else {
				assert(rchase_->done);
				// Forget this range; keep looking for ranges
				*chaseR_ = false;
				drR_->foundRange = false;
				if(verbose_) cout << "Done with chase for second mate" << endl;
				if(*delayedchaseL_) {
					// Start chasing the delayed range
					if(verbose_) cout << "Resuming delayed chase for first mate" << endl;
					assert(drL_->foundRange);
					const Range& r = drL_->range();
					assert(r.repOk());
					TIndexOffU top = r.top;
					TIndexOffU bot = r.bot;
					uint32_t qlen = doneFw_? qlen2_ : qlen1_;
					rchase_->setTopBot(top, bot, qlen, rand_, r.ebwt);
					*chaseL_ = true;
					*delayedchaseL_ = false;
				}
			}
		}
		if(!this->done && !*donePair_ && !*chaseL_ && !*chaseR_) {
			// Search for more ranges for whichever mate currently has
			// fewer candidate alignments
			if((*offsLsz_ < *offsRsz_ || drR_->done) && !drL_->done) {
				// If there are no more ranges for the other mate and
				// there are no candidate alignments either, then we're
				// not going to find a paired alignment in this
				// orientation.
				if(drR_->done && *offsRsz_ == 0) {
					// Give up on this orientation
					if(verbose_) cout << "Giving up on paired orientation " << (pairFw? "fw" : "rc") << " in mate 1" << endl;
					*donePair_ = true;
					if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << endl;
					return;
				}
				assert(!*delayedchaseL_);
				if(!drL_->foundRange) drL_->advance(ADV_FOUND_RANGE);
				if(drL_->foundRange) {
#ifndef NDEBUG
					{
						std::set<int64_t>& s = (pairFw ? allTopsL_fw_ : allTopsL_rc_);
						int64_t t = drL_->range().top + 1; // add 1 to avoid 0
						if(!drL_->range().ebwt->fw()) t = -t; // invert for bw index
						assert(s.find(t) == s.end());
						s.insert(t);
					}
#endif
					// Add the size of this range to the total for this mate
					*offsLsz_ += (drL_->range().bot - drL_->range().top);
					if(*offsRsz_ == 0 && (!dontReconcile_ || *offsLsz_ > 3)) {
						// Delay chasing this range; we delay to avoid
						// needlessly chasing rows in this range when
						// the other mate doesn't end up aligning
						// anywhere
						if(verbose_) cout << "Delaying a chase for first mate" << endl;
						*delayedchaseL_ = true;
					} else {
						// Start chasing this range
						if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << " " << drL_->range().top << endl;
						if(verbose_) cout << "Chasing a range for first mate" << endl;
						if(*offsLsz_ > symCeiling_ && *offsRsz_ > symCeiling_) {
							// Too many candidates for both mates; abort
							// without any more searching
							*donePair_ = true;
							return;
						}
						// If this is the first range for both mates,
						// choose the smaller range to chase down first
						if(*delayedchaseR_ && (*offsRsz_ < *offsLsz_)) {
							assert(drR_->foundRange);
							*delayedchaseR_ = false;
							*delayedchaseL_ = true;
							*chaseR_ = true;
							const Range& r = drR_->range();
							assert(r.repOk());
							uint32_t qlen = doneFw_? qlen1_ : qlen2_;
							rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt);
						} else {
							// Use Burrows-Wheeler for this pair (as
							// usual)
							*chaseL_ = true;
							const Range& r = drL_->range();
							uint32_t qlen = doneFw_? qlen2_ : qlen1_;
							rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt);
						}
					}
				}
			} else if(!drR_->done) {
				// If there are no more ranges for the other mate and
				// there are no candidate alignments either, then we're
				// not going to find a paired alignment in this
				// orientation.
				if(drL_->done && *offsLsz_ == 0) {
					// Give up on this orientation
					if(verbose_) cout << "Giving up on paired orientation " << (pairFw? "fw" : "rc") << " in mate 2" << endl;
					if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << endl;
					*donePair_ = true;
					return;
				}
				assert(!*delayedchaseR_);
				if(!drR_->foundRange) drR_->advance(ADV_FOUND_RANGE);
				if(drR_->foundRange) {
#ifndef NDEBUG
					{
						std::set<int64_t>& s = (pairFw ? allTopsR_fw_ : allTopsR_rc_);
						int64_t t = drR_->range().top + 1; // add 1 to avoid 0
						if(!drR_->range().ebwt->fw()) t = -t; // invert for bw index
						assert(s.find(t) == s.end());
						s.insert(t);
					}
#endif
					// Add the size of this range to the total for this mate
					*offsRsz_ += (drR_->range().bot - drR_->range().top);
					if(*offsLsz_ == 0 && (!dontReconcile_ || *offsRsz_ > 3)) {
						// Delay chasing this range; we delay to avoid
						// needlessly chasing rows in this range when
						// the other mate doesn't end up aligning
						// anywhere
						if(verbose_) cout << "Delaying a chase for second mate" << endl;
						*delayedchaseR_ = true;
					} else {
						// Start chasing this range
						if(verbose2_) cout << *offsLsz_ << " " << *offsRsz_ << " " << drR_->range().top << endl;
						if(verbose_) cout << "Chasing a range for second mate" << endl;
						if(*offsLsz_ > symCeiling_ && *offsRsz_ > symCeiling_) {
							// Too many candidates for both mates; abort
							// without any more searching
							*donePair_ = true;
							return;
						}
						// If this is the first range for both mates,
						// choose the smaller range to chase down first
						if(*delayedchaseL_ && *offsLsz_ < *offsRsz_) {
							assert(drL_->foundRange);
							*delayedchaseL_ = false;
							*delayedchaseR_ = true;
							*chaseL_ = true;
							const Range& r = drL_->range();
							assert(r.repOk());
							uint32_t qlen = doneFw_? qlen2_ : qlen1_;
							rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt);
						} else {
							// Use Burrows-Wheeler for this pair (as
							// usual)
							*chaseR_ = true;
							const Range& r = drR_->range();
							assert(r.repOk());
							uint32_t qlen = doneFw_? qlen1_ : qlen2_;
							rchase_->setTopBot(r.top, r.bot, qlen, rand_, r.ebwt);
						}
					}
				}
			} else {
				// Finished processing ranges for both mates
				assert(drL_->done && drR_->done);
				*donePair_ = true;
			}
		}
	}

	const BitPairReference* refs_;

	PatternSourcePerThread *patsrc_;
	uint32_t qlen1_;
	uint32_t qlen2_;

	// Progress state
	bool doneFw_;   // finished with forward orientation of both mates?
	bool doneFwFirst_;

	bool chase1Fw_;
	bool chase1Rc_;
	bool chase2Fw_;
	bool chase2Rc_;

	bool delayedChase1Fw_;
	bool delayedChase1Rc_;
	bool delayedChase2Fw_;
	bool delayedChase2Rc_;

	// For searching for outstanding mates
	RefAligner<String<Dna5> >* refAligner_;

	// Temporary HitSink; to be deleted
	const HitSinkPerThreadFactory& sinkPtFactory_;
	HitSinkPerThread* sinkPt_;

	// State for alignment
	EbwtSearchParams<String<Dna> >* params_;

	// Paired-end boundaries
	const uint32_t minInsert_;
	const uint32_t maxInsert_;

	// Don't attempt pairwise all-versus-all style of mate
	// reconciliation; just rely on mixed mode
	const bool dontReconcile_;

	// If both mates in a given orientation align >= symCeiling times,
	// then immediately give up
	const uint32_t symCeiling_;

	// If the total number of alignments for both mates in a given
	// orientation exceeds mixedThresh, then switch to mixed mode
	const uint32_t mixedThresh_;
	const uint32_t mixedAttemptLim_;
	uint32_t mixedAttempts_;

	// Orientation of upstream/downstream mates when aligning to
	// forward strand
	const bool fw1_;
	const bool fw2_;

	// State for getting alignments from ranges statefully
	RangeChaser<String<Dna> >* rchase_;

	// true -> be talkative
	bool verbose_;
	// true -> suppress warnings
	bool quiet_;

	int maxBts_;
	bowtieChunkPool *pool_;
	int *btCnt_;

	// Range-finding state for first mate
	TDriver*      driver1Fw_;
	TDriver*      driver1Rc_;
	UPairVec    offs1FwArr_[32];
	TRangeVec     ranges1FwArr_[32];
	uint32_t      offs1FwSz_; // total size of all ranges found in this category
	UPairVec    offs1RcArr_[32];
	TRangeVec     ranges1RcArr_[32];
	uint32_t      offs1RcSz_; // total size of all ranges found in this category

	// Range-finding state for second mate
	TDriver*      driver2Fw_;
	TDriver*      driver2Rc_;
	UPairVec    offs2FwArr_[32];
	TRangeVec     ranges2FwArr_[32];
	uint32_t      offs2FwSz_; // total size of all ranges found in this category
	UPairVec    offs2RcArr_[32];
	TRangeVec     ranges2RcArr_[32];
	uint32_t      offs2RcSz_; // total size of all ranges found in this category

	bool&       chaseL_fw_;
	bool&       chaseR_fw_;
	bool&       delayedchaseL_fw_;
	bool&       delayedchaseR_fw_;
	TDriver&    drL_fw_;
	TDriver&    drR_fw_;
	UPairVec* offsLarr_fw_;
	UPairVec* offsRarr_fw_;
	TRangeVec*  rangesLarr_fw_;
	TRangeVec*  rangesRarr_fw_;
	uint32_t&   offsLsz_fw_;
	uint32_t&   offsRsz_fw_;

	bool&       chaseL_rc_;
	bool&       chaseR_rc_;
	bool&       delayedchaseL_rc_;
	bool&       delayedchaseR_rc_;
	TDriver&    drL_rc_;
	TDriver&    drR_rc_;
	UPairVec* offsLarr_rc_;
	UPairVec* offsRarr_rc_;
	TRangeVec*  rangesLarr_rc_;
	TRangeVec*  rangesRarr_rc_;
	uint32_t&   offsLsz_rc_;
	uint32_t&   offsRsz_rc_;

	bool*       chaseL_;
	bool*       chaseR_;
	bool*       delayedchaseL_;
	bool*       delayedchaseR_;
	TDriver*    drL_;
	TDriver*    drR_;
	UPairVec* offsLarr_;
	UPairVec* offsRarr_;
	TRangeVec*  rangesLarr_;
	TRangeVec*  rangesRarr_;
	uint32_t*   offsLsz_;
	uint32_t*   offsRsz_;
	bool*       donePair_;
	bool        fwL_;
	bool        fwR_;

	/// For keeping track of paired alignments that have already been
	/// found for the forward and reverse-comp pair orientations
	TSetPairs   pairs_fw_;
	TSetPairs   pairs_rc_;

#ifndef NDEBUG
	std::set<int64_t> allTopsL_fw_;
	std::set<int64_t> allTopsR_fw_;
	std::set<int64_t> allTopsL_rc_;
	std::set<int64_t> allTopsR_rc_;
#endif

	bool verbose2_;
};

/**
 * Helper struct that holds a Range together with the coordinates where it al
 */
struct RangeWithCoords {
	Range r;
	UPair h;
};

/**
 * An aligner for finding paired alignments while operating entirely
 * within the Burrows-Wheeler domain.
 */
template<typename TRangeSource>
class PairedBWAlignerV2 : public Aligner {

	typedef std::pair<TIndexOffU,TIndexOffU> UPair;
	typedef std::vector<UPair> UPairVec;
	typedef std::vector<Range> TRangeVec;
	typedef RangeSourceDriver<TRangeSource> TDriver;
	typedef std::pair<uint64_t, uint64_t> TU64Pair;
	typedef std::set<TU64Pair> TSetPairs;

public:
	PairedBWAlignerV2(
		EbwtSearchParams<String<Dna> >* params,
		EbwtSearchParams<String<Dna> >* paramsSe1,
		EbwtSearchParams<String<Dna> >* paramsSe2,
		TDriver* driver,
		RefAligner<String<Dna5> >* refAligner,
		RangeChaser<String<Dna> >* rchase,
		HitSink& sink,
		const HitSinkPerThreadFactory& sinkPtFactory,
		HitSinkPerThread* sinkPt,
		HitSinkPerThread* sinkPtSe1,
		HitSinkPerThread* sinkPtSe2,
		bool fw1, bool fw2,
		uint32_t minInsert,
		uint32_t maxInsert,
		uint32_t mixedAttemptLim,
		const BitPairReference* refs,
		bool rangeMode,
		bool verbose,
		bool quiet,
		int maxBts,
		bowtieChunkPool *pool,
		int *btCnt) :
		Aligner(true, rangeMode),
		refs_(refs),
		patsrc_(NULL),
		qlen1_(0), qlen2_(0),
		chase_(false),
		donePe_(false),
		doneSe1_(false),
		doneSe2_(false),
		refAligner_(refAligner),
		sinkPtFactory_(sinkPtFactory),
		sinkPt_(sinkPt),
		sinkPtSe1_(sinkPtSe1),
		sinkPtSe2_(sinkPtSe2),
		params_(params),
		paramsSe1_(paramsSe1),
		paramsSe2_(paramsSe2),
		minInsert_(minInsert),
		maxInsert_(maxInsert),
		mixedAttemptLim_(mixedAttemptLim),
		mixedAttempts_(0),
		fw1_(fw1), fw2_(fw2),
		rchase_(rchase),
		driver_(driver),
		pool_(pool),
		verbose_(verbose),
		quiet_(quiet),
		maxBts_(maxBts),
		btCnt_(btCnt)
	{
		assert(sinkPt_ != NULL);
		assert(params_ != NULL);
		assert(driver_ != NULL);
	}

	virtual ~PairedBWAlignerV2() {
		delete driver_; driver_ = NULL;
		delete params_; params_ = NULL;
		if(paramsSe1_ != NULL) {
			delete paramsSe1_; paramsSe1_ = NULL;
			delete paramsSe2_; paramsSe2_ = NULL;
		}
		delete rchase_; rchase_ = NULL;
		delete[] btCnt_; btCnt_ = NULL;
		delete refAligner_; refAligner_ = NULL;
		sinkPtFactory_.destroy(sinkPt_); sinkPt_ = NULL;
		if(sinkPtSe1_ != NULL) {
			sinkPtFactory_.destroy(sinkPtSe1_); sinkPtSe1_ = NULL;
			sinkPtFactory_.destroy(sinkPtSe2_); sinkPtSe2_ = NULL;
		}
	}

	/**
	 * Prepare this aligner for the next read.
	 */
	virtual void setQuery(PatternSourcePerThread* patsrc) {
		Aligner::setQuery(patsrc); // set fields & random seed
		assert(!patsrc->bufb().empty());
		// Give all of the drivers pointers to the relevant read info
		patsrc_ = patsrc;
		pool_->reset(&patsrc->bufa().name, (uint32_t)patsrc->rdid());
		if(patsrc->bufa().length() < 4 || patsrc->bufb().length() < 4) {
			if(!quiet_) {
				cerr << "Warning: Skipping pair " << patsrc->bufa().name
				     << " because a mate is less than 4 characters long" << endl;
			}
			this->done = true;
			sinkPt_->finishRead(*patsrc_, true, true);
			return;
		}
		driver_->setQuery(patsrc, NULL);
		qlen1_ = patsrc_->bufa().length();
		qlen2_ = patsrc_->bufb().length();
		if(btCnt_ != NULL) (*btCnt_) = maxBts_;
		mixedAttempts_ = 0;
		// Neither orientation is done
		this->done = false;
		// No ranges are being chased yet
		chase_ = false;
		donePe_ = doneSe1_ = doneSe2_ = false;
		pairs_fw_.clear();
		pairs_rc_.clear();
	}

	/**
	 * Advance the aligner by one memory op.  Return true iff we're
	 * done with this read.
	 *
	 * A call to this function does one of many things:
	 * 1. Advance a RangeSourceDriver and check if it found a new range
	 * 2. Advance a RowChaseDriver and check if it found a reference
	 *    offset for a an alignment in a range
	 */
	virtual bool advance() {
		assert(!this->done);
		if(chase_) {
			assert(!rangeMode_); // chasing ranges
			if(!rchase_->foundOff() && !rchase_->done) {
				rchase_->advance();
				return false;
			}
			assert(rchase_->foundOff() || rchase_->done);
			if(rchase_->foundOff()) {
				const Range& r = driver_->range();
				assert(r.repOk());
				resolveOutstanding(
					rchase_->off(),
					r.ebwt->_plen[rchase_->off().first], r);
				rchase_->reset();
			} else {
				assert(rchase_->done);
				// Forget this range; keep looking for ranges
				chase_ = false;
				this->done = driver_->done;
			}
		}

		if(!this->done && !chase_) {
			// Search for more ranges for whichever mate currently has
			// fewer candidate alignments
			if(!driver_->done) {
				if(!this->done) {
					//
					// Check whether any of the PE/SE possibilities
					// have become impossible due to the minCost
					//
					if(!donePe_) {
						assert(!this->done);
						donePe_ = sinkPt_->irrelevantCost(driver_->minCost);
						if(donePe_ && (!sinkPt_->empty() || sinkPtSe1_ == NULL)) {
							// Paired-end alignment(s) were found, no
							// more will be found, and no unpaired
							// alignments are requested, so stop
							this->done = true;
						}
						if(donePe_ && sinkPtSe1_ != NULL) {
							// Note: removeMate affects minCost
							if(doneSe1_) driver_->removeMate(1);
							if(doneSe2_) driver_->removeMate(2);
						}
					}
					if(!this->done && sinkPtSe1_ != NULL) {
						if(!doneSe1_) {
							doneSe1_ = sinkPtSe1_->irrelevantCost(driver_->minCost);
							if(doneSe1_ && donePe_) driver_->removeMate(1);
						}
						if(!doneSe2_) {
							doneSe2_ = sinkPtSe2_->irrelevantCost(driver_->minCost);
							if(doneSe2_ && donePe_) driver_->removeMate(2);
						}
						// Do Se1 again, because removing Se2 may have
						// nudged minCost over the threshold
						if(!doneSe1_) {
							doneSe1_ = sinkPtSe1_->irrelevantCost(driver_->minCost);
							if(doneSe1_ && donePe_) driver_->removeMate(1);
						}
						if(doneSe1_ && doneSe2_) assert(donePe_);
						this->done = donePe_ && doneSe1_ && doneSe2_;
					}

					if(!this->done) {
						if(sinkPtSe1_ != NULL) {
							assert(doneSe1_ || !sinkPtSe1_->irrelevantCost(driver_->minCost));
							assert(doneSe2_ || !sinkPtSe2_->irrelevantCost(driver_->minCost));
						}
						assert(donePe_ || !sinkPt_->irrelevantCost(driver_->minCost));
						driver_->advance(ADV_COST_CHANGES);
					}
				}
				if(driver_->foundRange) {
					// Use Burrows-Wheeler for this pair (as usual)
					chase_ = true;
					driver_->foundRange = false;
					const Range& r = driver_->range();
					assert(r.repOk());
					rchase_->setTopBot(r.top, r.bot,
					                   r.mate1 ? qlen1_ : qlen2_,
					                   rand_, r.ebwt);
				}
			} else {
				this->done = true;
			}
		}

		if(this->done) {
			bool reportedPe = (sinkPt_->finishRead(*patsrc_, true, true) > 0);
			if(sinkPtSe1_ != NULL) {
				sinkPtSe1_->finishRead(*patsrc_, !reportedPe, false);
				sinkPtSe2_->finishRead(*patsrc_, !reportedPe, false);
			}
		}
		return this->done;
	}

protected:

	/**
	 * Helper for reporting a pair of alignments.  As of now, we report
	 * a paired alignment by reporting two consecutive alignments, one
	 * for each mate.
	 */
	bool report(const Range& rL, // range for upstream mate
	            const Range& rR, // range for downstream mate
	            TIndexOffU first,  // ref idx
	            TIndexOffU upstreamOff, // offset for upstream mate
	            TIndexOffU dnstreamOff, // offset for downstream mate
	            TIndexOffU tlen, // length of ref
	            bool pairFw,   // whether the pair is being mapped to fw strand
	            bool ebwtFwL,
	            bool ebwtFwR)
	{
		assert(gAllowMateContainment || upstreamOff < dnstreamOff);
		TIndexOffU spreadL = rL.bot - rL.top;
		TIndexOffU spreadR = rR.bot - rR.top;
		TIndexOffU oms = min(spreadL, spreadR) - 1;
		Read* bufL = pairFw ? bufa_ : bufb_;
		Read* bufR = pairFw ? bufb_ : bufa_;
		TIndexOffU lenL = pairFw ? alen_ : blen_;
		TIndexOffU lenR = pairFw ? blen_ : alen_;
		bool ret;
		assert(!params_->sink().exceededOverThresh());
		params_->setFw(rL.fw);
		assert_eq(bufL->color, color);
		// Print upstream mate first
		ret = params_->reportHit(
				rL.fw ? (ebwtFwL?  bufL->patFw  :  bufL->patFwRev) :
				        (ebwtFwL?  bufL->patRc  :  bufL->patRcRev),
				rL.fw ? (ebwtFwL? &bufL->qual    : &bufL->qualRev) :
				        (ebwtFwL? &bufL->qualRev : &bufL->qual),
				&bufL->name,
				bufL->color,
				bufL->primer,
				bufL->trimc,
				colorExEnds,
				snpPhred,
				refs_,
				ebwtFwL,
				rL.mms,                       // mismatch positions
				rL.refcs,                     // reference characters for mms
				rL.numMms,                    // # mismatches
				make_pair(first, upstreamOff),// position
				make_pair(first, dnstreamOff),// mate position
				rR.fw,                        // mate orientation
				lenR,                         // mate length
				make_pair(rL.top, rL.bot),    // arrows
				tlen,                         // textlen
				lenL,                         // qlen
				rL.stratum,                   // alignment stratum
				rL.cost,                      // cost, including quality penalty
				oms,                          // # other hits
				bufL->patid,
				bufL->seed,
				pairFw ? 1 : 2);
		if(ret) {
			return true; // can happen when -m is set
		}
		params_->setFw(rR.fw);
		assert_eq(bufR->color, color);
		ret = params_->reportHit(
				rR.fw ? (ebwtFwR?  bufR->patFw  :  bufR->patFwRev) :
				        (ebwtFwR?  bufR->patRc  :  bufR->patRcRev),
				rR.fw ? (ebwtFwR? &bufR->qual    : &bufR->qualRev) :
				        (ebwtFwR? &bufR->qualRev : &bufR->qual),
				&bufR->name,
				bufR->color,
				bufR->primer,
				bufR->trimc,
				colorExEnds,
				snpPhred,
				refs_,
				ebwtFwR,
				rR.mms,                       // mismatch positions
				rR.refcs,                     // reference characters for mms
				rR.numMms,                    // # mismatches
				make_pair(first, dnstreamOff),// position
				make_pair(first, upstreamOff),// mate position
				rL.fw,                        // mate orientation
				lenL,                         // mate length
				make_pair(rR.top, rR.bot),    // arrows
				tlen,                         // textlen
				lenR,                         // qlen
				rR.stratum,                   // alignment stratum
				rR.cost,                      // cost, including quality penalty
				oms,                          // # other hits
				bufR->patid,
				bufR->seed,
				pairFw ? 2 : 1);
		return ret;
	}

	/**
	 * Helper for reporting a pair of alignments.  As of now, we report
	 * a paired alignment by reporting two consecutive alignments, one
	 * for each mate.
	 */
	void reportSe(const Range& r, UPair h, uint32_t tlen) {
		EbwtSearchParams<String<Dna> >*params = (r.mate1 ? paramsSe1_ : paramsSe2_);
		assert(!(r.mate1 ? doneSe1_ : doneSe2_));
		params->setFw(r.fw);
		Read* buf = r.mate1 ? bufa_ : bufb_;
		bool ebwtFw = r.ebwt->fw();
		uint32_t len = r.mate1 ? alen_ : blen_;
		assert_eq(buf->color, color);
		// Print upstream mate first
		if(params->reportHit(
			r.fw ? (ebwtFw?  buf->patFw   :  buf->patFwRev) :
			       (ebwtFw?  buf->patRc   :  buf->patRcRev),
			r.fw ? (ebwtFw? &buf->qual    : &buf->qualRev) :
			       (ebwtFw? &buf->qualRev : &buf->qual),
			&buf->name,
			buf->color,
			buf->primer,
			buf->trimc,
			colorExEnds,
			snpPhred,
			refs_,
			ebwtFw,
			r.mms,                   // mismatch positions
			r.refcs,                 // reference characters for mms
			r.numMms,                // # mismatches
			h,                       // position
			make_pair(0, 0),         // (bogus) mate coords
			true,                    // (bogus) mate orientation
			0,                       // (bogus) mate length
			make_pair(r.top, r.bot), // arrows
			tlen,                    // textlen
			len,                     // qlen
			r.stratum,               // alignment stratum
			r.cost,                  // cost, including quality penalty
			r.bot - r.top - 1,       // # other hits
			buf->patid,
			buf->seed,
			0))
		{
			if(r.mate1) doneSe1_ = true;
			else        doneSe2_ = true;
			if(donePe_) driver_->removeMate(r.mate1 ? 1 : 2);
		}
	}

	void resolveOutstanding(const UPair& off,
	                        const TIndexOffU tlen,
	                        const Range& range)
	{
		assert(!this->done);
		if(!donePe_) {
			bool ret = resolveOutstandingInRef(off, tlen, range);
			if(++mixedAttempts_ > mixedAttemptLim_ || ret) {
				// Give up on this pair
				donePe_ = true;
				if(sinkPtSe1_ != NULL) {
					if(doneSe1_) driver_->removeMate(1);
					if(doneSe2_) driver_->removeMate(2);
				}
			}
			this->done = (donePe_ && (!sinkPt_->empty() || sinkPtSe1_ == NULL || (doneSe1_ && doneSe2_)));
		}
		if(!this->done && sinkPtSe1_ != NULL) {
			bool doneSe = (range.mate1 ? doneSe1_ : doneSe2_);
			if(!doneSe) {
				// Hold onto this single-end alignment in case we don't
				// find any paired alignments
				reportSe(range, off, tlen);
			}
			this->done = doneSe1_ && doneSe2_ && donePe_;
		}
	}

	/**
	 * Given a vector of reference positions where one of the two mates
	 * (the "anchor" mate) has aligned, look directly at the reference
	 * sequence for instances where the other mate (the "outstanding"
	 * mate) aligns such that mating constraint is satisfied.
	 *
	 * This function picks up to 'pick' anchors at random from the
	 * 'offs' array.  It returns the number that it actually picked.
	 */
	bool resolveOutstandingInRef(const UPair& off,
	                             const TIndexOffU tlen,
	                             const Range& range)
	{
		assert(!donePe_);
		assert(refs_->loaded());
		assert_lt(off.first, refs_->numRefs());
		// pairFw = true if the anchor indicates that the pair will
		// align in its forward orientation (i.e. with mate1 to the
		// left of mate2)
		bool pairFw = (range.mate1)? (range.fw == fw1_) : (range.fw == fw2_);
		// matchRight = true, if the opposite mate will be to the right
		// of the anchor mate
		bool matchRight = (pairFw ? range.mate1 : !range.mate1);
		// fw = orientation of the opposite mate
		bool fw = range.mate1 ? fw2_ : fw1_; // whether outstanding mate is fw/rc
		if(!pairFw) fw = !fw;
		// 'seq' = sequence for opposite mate
		const String<Dna5>& seq  =
			fw ? (range.mate1 ? patsrc_->bufb().patFw   :
		                        patsrc_->bufa().patFw)  :
		         (range.mate1 ? patsrc_->bufb().patRc   :
		                        patsrc_->bufa().patRc);
		// 'qual' = qualities for opposite mate
		const String<char>& qual =
			fw ? (range.mate1 ? patsrc_->bufb().qual  :
			                    patsrc_->bufa().qual) :
			     (range.mate1 ? patsrc_->bufb().qualRev :
			                    patsrc_->bufa().qualRev);
		uint32_t qlen = (uint32_t)seqan::length(seq);  // length of outstanding mate
		uint32_t alen = (range.mate1 ? patsrc_->bufa().length() :
		                               patsrc_->bufb().length());
		int minins = minInsert_;
		int maxins = maxInsert_;
		if(fw1_) {
			minins = max<int>(0, minins - patsrc_->bufa().trimmed5);
			maxins = max<int>(0, maxins - patsrc_->bufa().trimmed5);
		} else {
			minins = max<int>(0, minins - patsrc_->bufa().trimmed3);
			maxins = max<int>(0, maxins - patsrc_->bufa().trimmed3);
		}
		if(fw2_) {
			minins = max<int>(0, minins - patsrc_->bufb().trimmed3);
			maxins = max<int>(0, maxins - patsrc_->bufb().trimmed3);
		} else {
			minins = max<int>(0, minins - patsrc_->bufb().trimmed5);
			maxins = max<int>(0, maxins - patsrc_->bufb().trimmed5);
		}
		assert_geq(minins, 0);
		assert_geq(maxins, 0);
		// Don't even try if either of the mates is longer than the
		// maximum insert size.
		if((uint32_t)maxins <= max(qlen, alen)) {
			return false;
		}
		const TIndexOffU tidx = off.first;  // text id where anchor mate hit
		const TIndexOffU toff = off.second; // offset where anchor mate hit
		// Set begin/end to the range of reference positions where
		// outstanding mate may align while fulfilling insert-length
		// constraints.
		TIndexOffU begin, end;
		assert_geq(maxins, minins);
		TIndexOffU insDiff = maxins - minins;
		if(matchRight) {
			end = toff + maxins;
			// Adding 1 disallows the opposite from starting at the
			// left-hand edge of the anchor mate.
			begin = toff + (gAllowMateContainment ? 0 : 1);
			// We can also add a bit more if qlen is less than alen,
			// since we're requiring that opposite not be contained
			// within anchor.
			if(!gAllowMateContainment && qlen < alen) {
				begin += alen-qlen;
			}
			if(end > insDiff + qlen) {
				begin = max<TIndexOffU>(begin, end - insDiff - qlen);
			}
			end = min<TIndexOffU>(refs_->approxLen(tidx), end);
			begin = min<TIndexOffU>(refs_->approxLen(tidx), begin);
		} else {
			if(toff + alen < (TIndexOffU)maxins) {
				begin = 0;
			} else {
				begin = toff + alen - maxins;
			}
			uint32_t mi = min<uint32_t>(alen, qlen);
			if(gAllowMateContainment) {
				end = toff + alen - 1;
			} else {
				end = toff + mi - 1;
				end = min<TIndexOffU>(end, toff + alen - minins + qlen - 1);
				if(toff + alen + qlen < (TIndexOffU)minins + 1) end = 0;
			}
		}
		// Check if there's not enough space in the range to fit an
		// alignment for the outstanding mate.
		if(end - begin < qlen) return false;
		std::vector<Range> ranges;
		std::vector<TIndexOffU> offs;
		refAligner_->find(1, tidx, refs_, seq, qual, begin, end, ranges,
		                  offs, pairFw ? &pairs_fw_ : &pairs_rc_,
		                  toff, fw);
		assert_eq(ranges.size(), offs.size());
		for(size_t i = 0; i < ranges.size(); i++) {
			Range& r = ranges[i];
			r.fw = fw;
			r.cost |= (r.stratum << 14);
			r.mate1 = !range.mate1;
			const TIndexOffU result = offs[i];
			// Just copy the known range's top and bot for now
			r.top = range.top;
			r.bot = range.bot;
			bool ebwtLFw = matchRight ? range.ebwt->fw() : true;
			bool ebwtRFw = matchRight ? true : range.ebwt->fw();
			if(report(
				matchRight ? range : r, // range for upstream mate
				matchRight ? r : range, // range for downstream mate
				tidx,                   // ref idx
				matchRight ? toff : result, // upstream offset
				matchRight ? result : toff, // downstream offset
				tlen,       // length of ref
				pairFw,     // whether the pair is being mapped to fw strand
				ebwtLFw,
				ebwtRFw)) return true;
		}
		return false;
	}

	const BitPairReference* refs_;

	PatternSourcePerThread *patsrc_;
	uint32_t qlen1_, qlen2_;
	bool chase_;

	// true -> we're no longer shooting for paired-end alignments;
	// just collecting single-end ones
	bool donePe_, doneSe1_, doneSe2_;

	// For searching for outstanding mates
	RefAligner<String<Dna5> >* refAligner_;

	// Temporary HitSink; to be deleted
	const HitSinkPerThreadFactory& sinkPtFactory_;
	HitSinkPerThread* sinkPt_;
	HitSinkPerThread* sinkPtSe1_, * sinkPtSe2_;

	// State for alignment
	EbwtSearchParams<String<Dna> >* params_;
	// for single-end:
	EbwtSearchParams<String<Dna> >* paramsSe1_, * paramsSe2_;

	// Paired-end boundaries
	const uint32_t minInsert_;
	const uint32_t maxInsert_;

	const uint32_t mixedAttemptLim_;
	uint32_t mixedAttempts_;

	// Orientation of upstream/downstream mates when aligning to
	// forward strand
	const bool fw1_, fw2_;

	// State for getting alignments from ranges statefully
	RangeChaser<String<Dna> >* rchase_;

	// Range-finding state for first mate
	TDriver* driver_;

	// Pool for distributing chunks of best-first path descriptor memory
	bowtieChunkPool *pool_;

	bool verbose_;
	bool quiet_;

	int maxBts_; // maximum allowed # backtracks
	int *btCnt_; // current backtrack count

	/// For keeping track of paired alignments that have already been
	/// found for the forward and reverse-comp pair orientations
	TSetPairs pairs_fw_, pairs_rc_;
};

#endif /* ALIGNER_H_ */