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" );
out.close();