protected void doPaired() {
IoUtil.assertFileIsWritable(SECOND_END_FASTQ);
IoUtil.assertFileIsWritable(FRAGMENT_FASTQ);
final SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT));
final FastqWriter writer1 = FastqWriterFactoryInstance().newWriter(FASTQ);
final FastqWriter writer2 = FastqWriterFactoryInstance().newWriter(SECOND_END_FASTQ);
final FastqWriter fragWriter = FastqWriterFactoryInstance().newWriter(FRAGMENT_FASTQ);
final Map<String,SAMRecord> firstSeenMates = new HashMap<String,SAMRecord>();
final Set<String> failedReadNames = new HashSet<String>();
try {
for (final SAMRecord currentRecord : reader ) {
final String currentReadName = currentRecord.getReadName() ;
final SAMRecord firstRecord = firstSeenMates.get(currentReadName);
// Skip non-PF reads as necessary
if (currentRecord.getReadFailsVendorQualityCheckFlag() && !INCLUDE_NON_PF_READS) {
if (currentRecord.getReadPairedFlag()) {
failedReadNames.add(currentReadName);
// if this record failed QC, but we were already holding its mate...
if (firstRecord != null) {
firstSeenMates.remove(currentReadName);
notifyOrphan(currentReadName);
writeRecord(firstRecord, null, fragWriter);
}
}
continue;
}
if (currentRecord.getReadPairedFlag()) {
// if this reads mate already failed QC...
if (failedReadNames.contains(currentReadName)) {
notifyOrphan(currentReadName);
writeRecord(currentRecord, null, fragWriter);
continue;
}
if (firstRecord == null) {
firstSeenMates.put(currentReadName, currentRecord) ;
}
else {
assertPairedMates(firstRecord, currentRecord);
if (currentRecord.getFirstOfPairFlag()) {
writeRecord(currentRecord, 1, writer1);
writeRecord(firstRecord, 2, writer2);
}
else {
writeRecord(firstRecord, 1, writer1);
writeRecord(currentRecord, 2, writer2);
}
firstSeenMates.remove(currentReadName);
}
} else {
writeRecord(currentRecord, null, fragWriter);
}
}
if (firstSeenMates.size() > 0) {
// are we ignoring these.
if (IGNORE_ORPHAN_MATES == false)
throw new PicardException("Found "+firstSeenMates.size()+" reads with flags that indicated they were paired, but no mates were seen.");
for (final SAMRecord currentRecord : firstSeenMates.values()) {
writeRecord(currentRecord, null, fragWriter);
}
}
} finally {
// Flush as much as possible.
writer1.close();
writer2.close();
fragWriter.close();
reader.close();
}
}