IOUtil.assertFileIsWritable(OUTPUT);
final SAMFileReader in = new SAMFileReader(INPUT);
ReferenceSequenceFile reference = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE);
SAMSequenceDictionary refDict = reference.getSequenceDictionary();
if (refDict == null) {
log.error("No reference sequence dictionary found. Aborting. You can create a sequence dictionary for the reference fasta using CreateSequenceDictionary.jar.");
in.close();
return 1;
}
printDictionary("SAM/BAM file", in.getFileHeader().getSequenceDictionary());
printDictionary("Reference", refDict);
Map<Integer, Integer> newOrder = buildSequenceDictionaryMap(refDict, in.getFileHeader().getSequenceDictionary());
// has to be after we create the newOrder
SAMFileHeader outHeader = in.getFileHeader().clone();
outHeader.setSequenceDictionary(refDict);
log.info("Writing reads...");
if (in.hasIndex()) {
final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(outHeader, true, OUTPUT);
// write the reads in contig order
for (final SAMSequenceRecord contig : refDict.getSequences() ) {
final SAMRecordIterator it = in.query(contig.getSequenceName(), 0, 0, false);
writeReads(out, it, newOrder, contig.getSequenceName());
}
// don't forget the unmapped reads
writeReads( out, in.queryUnmapped(), newOrder, "unmapped" );