/// <summary>
/// Sort and merge multiple SAM objects
/// </summary>
/// <param name="sortedIndexes">Sorted Indexes of SAM object.</param>
/// <param name="fstemp">Temporary tream to write alignments.</param>
/// <param name="formatter">Format aligned sequences in BAM format.</param>
/// <param name="sequenceAlignmentMaps">List of SAM objects to be merged.</param>
private void WriteMergeFile(IList<IList<BAMSortedIndex>> sortedIndexes, FileStream fstemp, BAMFormatter formatter, IList<SequenceAlignmentMap> sequenceAlignmentMaps)
{
List<SAMAlignedSequence> alignedSeqs = new List<SAMAlignedSequence>();
int[] sortedIndex = new int[sequenceAlignmentMaps.Count];
for (int i = 0; i < sortedIndexes.Count; i++)
{
BAMSortedIndex bamSortedIndex = sortedIndexes[i].ElementAt(sortedIndex[i]);
if (bamSortedIndex != null)
{
if (bamSortedIndex.MoveNext())
{
alignedSeqs.Add(sequenceAlignmentMaps[i].QuerySequences[bamSortedIndex.Current]);
}
else
{
alignedSeqs.Add(null);
}
}
else
{
alignedSeqs.Add(null);
}
}
int smallestIndex = -1;
do
{
for (int index = 0; index < alignedSeqs.Count; index++)
{
if (alignedSeqs[index] != null)
{
if (smallestIndex == -1)
{
smallestIndex = index;
}
else
{
if (0 < string.Compare(alignedSeqs[smallestIndex].RName, alignedSeqs[index].RName, StringComparison.OrdinalIgnoreCase))
{
smallestIndex = index;
}
else if (alignedSeqs[smallestIndex].RName.Equals(alignedSeqs[index].RName))
{
if (alignedSeqs[smallestIndex].Pos > alignedSeqs[index].Pos)
{
smallestIndex = index;
}
}
}
}
}
if (smallestIndex > -1)
{
SAMAlignedSequence alignSeqTowrite = alignedSeqs[smallestIndex];
if (sortedIndexes[smallestIndex].ElementAt(sortedIndex[smallestIndex]).MoveNext())
{
int nextIndex = sortedIndexes[smallestIndex].ElementAt(sortedIndex[smallestIndex]).Current;
alignedSeqs[smallestIndex] = sequenceAlignmentMaps[smallestIndex].QuerySequences[nextIndex];
}
else
{
sortedIndex[smallestIndex]++;
if (sortedIndex[smallestIndex] < sortedIndexes[smallestIndex].Count &&
sortedIndexes[smallestIndex].ElementAt(sortedIndex[smallestIndex]).MoveNext())
{
int nextIndex = sortedIndexes[smallestIndex].ElementAt(sortedIndex[smallestIndex]).Current;
alignedSeqs[smallestIndex] = sequenceAlignmentMaps[smallestIndex].QuerySequences[nextIndex];
}
else
{
alignedSeqs[smallestIndex] = null;
smallestIndex = -1;
}
}
formatter.WriteAlignedSequence(header, alignSeqTowrite, fstemp);
}
} while (!alignedSeqs.All(a => a == null));
}