map.put(id, new ExposedByteArrayOutputStream());
}
DataWriterFactory f = new DataWriterFactory();
ExposedByteArrayOutputStream bitBAOS = new ExposedByteArrayOutputStream();
DefaultBitOutputStream bos = new DefaultBitOutputStream(bitBAOS);
Slice slice = new Slice();
slice.nofRecords = records.size();
int[] seqIds = new int[fileHeader.getSequenceDictionary().size()];
int minAlStart = Integer.MAX_VALUE;
int maxAlEnd = SAMRecord.NO_ALIGNMENT_START;
for (CramRecord r : records) {
if (r.sequenceId != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX)
seqIds[r.sequenceId]++;
int alStart = r.getAlignmentStart();
if (alStart != SAMRecord.NO_ALIGNMENT_START) {
minAlStart = Math.min(alStart, minAlStart);
maxAlEnd = Math.max(r.calcualteAlignmentEnd(), maxAlEnd);
}
slice.bases += r.getReadLength();
}
int seqId = SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX;
boolean singleSeqId = true;
for (int i = 0; i < seqIds.length && singleSeqId; i++) {
if (seqIds[i] > 0) {
seqId = i++;
for (; i < seqIds.length && singleSeqId; i++) {
if (seqIds[i] > 0)
singleSeqId = false;
}
}
}
if (!singleSeqId)
throw new RuntimeException("Multiref slices are not supported.");
slice.sequenceId = seqId;
if (minAlStart == Integer.MAX_VALUE) {
slice.alignmentStart = SAMRecord.NO_ALIGNMENT_START;
slice.alignmentSpan = 0;
} else {
slice.alignmentStart = minAlStart;
slice.alignmentSpan = maxAlEnd - minAlStart;
}
Writer writer = f.buildWriter(bos, map, h, slice.sequenceId);
int prevAlStart = slice.alignmentStart;
for (CramRecord r : records) {
r.alignmentStartOffsetFromPreviousRecord = r.getAlignmentStart()
- prevAlStart;
prevAlStart = r.getAlignmentStart();
writer.write(r);
}
slice.contentType = slice.alignmentSpan > -1 ? BlockContentType.MAPPED_SLICE
: BlockContentType.RESERVED;
bos.close();
slice.coreBlock = new Block();
slice.coreBlock.method = BlockCompressionMethod.RAW.ordinal();
slice.coreBlock.setRawContent(bitBAOS.toByteArray());
slice.coreBlock.contentType = BlockContentType.CORE;