SAMFileWriter writer, boolean isPairedEnd,
List<Feature> regions, int minMappingQuality) throws IOException {
System.out.println("sam: " + inputSam);
SAMFileReader reader = new SAMFileReader(new File(inputSam));
reader.setValidationStringency(ValidationStringency.SILENT);
output1 = new FastqOutputFile();
output1.init(outputFastq);
int lineCnt = 0;
this.regionTracker = new RegionTracker(regions, reader.getFileHeader());
for (SAMRecord read : reader) {
if (SAMRecordUtils.isPrimary(read) && (!SAMRecordUtils.isFiltered(isPairedEnd, read))) {
// These tags can be lengthy, so remove them.
// TODO: Improve the way this is handled
read.setAttribute("XA", null);
read.setAttribute("OQ", null);
read.setAttribute("MD", null);
read.setAttribute("BQ", null);
int yx = 0;
boolean isAmbiguous = !read.getReadUnmappedFlag() && read.getMappingQuality() == 0;
if ((!read.getReadFailsVendorQualityCheckFlag()) && (!isAmbiguous)) {
// Calculate the number of mismatches to reference for this read.
if (c2r != null) {
try {
yx = SAMRecordUtils.getEditDistance(read, c2r);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error for read: " + read.getSAMString());
throw e;
}
} else {
yx = read.getReadLength();
}
read.setAttribute("YX", yx);
}
boolean offTargetFiltered = false;
if (yx > 0 && !read.getReadUnmappedFlag() && read.getMappingQuality() < MIN_OFF_TARGET_MAPQ && !regionTracker.isInRegion(read)) {
read.setAttribute("YR", 2);
offTargetFiltered = true;
// System.out.println("Filtering off target: " + read.getSAMString());
}
if ((yx > 0 && !offTargetFiltered && read.getMappingQuality() >= minMappingQuality) || (read.getReadUnmappedFlag())) {
if ((!read.getReadUnmappedFlag()) && (!regionTracker.isInRegion(read))) {
read.setAttribute("YR", 1);
}
// Eligible for realignment, output FASTQ record
output1.write(samReadToFastqRecord(read, c2r));
} else if (writer != null) {
// Either xactly matches reference or failed vendor QC or low mapq, so
// output directly to final BAM
writer.addAlignment(read);
}
}
lineCnt++;
if ((lineCnt % 1000000) == 0) {
System.out.println("record: " + lineCnt);
}
}
output1.close();
reader.close();
}