1 // ***************************************************************************
2 // bamtools_convert.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 8 October 2011
6 // ---------------------------------------------------------------------------
7 // Converts between BAM and a number of other formats
8 // ***************************************************************************
10 #include "bamtools_convert.h"
12 #include <api/BamConstants.h>
13 #include <api/BamMultiReader.h>
14 #include <utils/bamtools_fasta.h>
15 #include <utils/bamtools_options.h>
16 #include <utils/bamtools_pileup_engine.h>
17 #include <utils/bamtools_utilities.h>
18 using namespace BamTools;
29 // ---------------------------------------------
30 // ConvertTool constants
32 // supported conversion format command-line names
33 static const string FORMAT_BED = "bed";
34 static const string FORMAT_FASTA = "fasta";
35 static const string FORMAT_FASTQ = "fastq";
36 static const string FORMAT_JSON = "json";
37 static const string FORMAT_SAM = "sam";
38 static const string FORMAT_PILEUP = "pileup";
39 static const string FORMAT_YAML = "yaml";
42 static const unsigned int FASTA_LINE_MAX = 50;
44 // ---------------------------------------------
45 // ConvertPileupFormatVisitor declaration
47 class ConvertPileupFormatVisitor : public PileupVisitor {
51 ConvertPileupFormatVisitor(const RefVector& references,
52 const string& fastaFilename,
53 const bool isPrintingMapQualities,
55 ~ConvertPileupFormatVisitor(void);
57 // PileupVisitor interface implementation
59 void Visit(const PileupPosition& pileupData);
65 bool m_isPrintingMapQualities;
67 RefVector m_references;
70 } // namespace BamTools
72 // ---------------------------------------------
73 // ConvertSettings implementation
75 struct ConvertTool::ConvertSettings {
84 bool HasFastaFilename;
85 bool IsOmittingSamHeader;
86 bool IsPrintingPileupMapQualities;
89 vector<string> InputFiles;
90 string OutputFilename;
103 , HasFastaFilename(false)
104 , IsOmittingSamHeader(false)
105 , IsPrintingPileupMapQualities(false)
106 , OutputFilename(Options::StandardOut())
111 // ---------------------------------------------
112 // ConvertToolPrivate implementation
114 struct ConvertTool::ConvertToolPrivate {
118 ConvertToolPrivate(ConvertTool::ConvertSettings* settings)
119 : m_settings(settings)
120 , m_out(cout.rdbuf())
123 ~ConvertToolPrivate(void) { }
131 void PrintBed(const BamAlignment& a);
132 void PrintFasta(const BamAlignment& a);
133 void PrintFastq(const BamAlignment& a);
134 void PrintJson(const BamAlignment& a);
135 void PrintSam(const BamAlignment& a);
136 void PrintYaml(const BamAlignment& a);
138 // special case - uses the PileupEngine
139 bool RunPileupConversion(BamMultiReader* reader);
143 ConvertTool::ConvertSettings* m_settings;
144 RefVector m_references;
148 bool ConvertTool::ConvertToolPrivate::Run(void) {
150 // ------------------------------------
151 // initialize conversion input/output
153 // set to default input if none provided
154 if ( !m_settings->HasInput )
155 m_settings->InputFiles.push_back(Options::StandardIn());
158 BamMultiReader reader;
159 if ( !reader.Open(m_settings->InputFiles) ) {
160 cerr << "bamtools convert ERROR: could not open input BAM file(s)... Aborting." << endl;
164 // if input is not stdin & a region is provided, look for index files
165 if ( m_settings->HasInput && m_settings->HasRegion ) {
166 if ( !reader.LocateIndexes() ) {
167 cerr << "bamtools convert ERROR: could not locate index file(s)... Aborting." << endl;
172 // retrieve reference data
173 m_references = reader.GetReferenceData();
175 // set region if specified
177 if ( m_settings->HasRegion ) {
178 if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
180 if ( reader.HasIndexes() ) {
181 if ( !reader.SetRegion(region) ) {
182 cerr << "bamtools convert ERROR: set region failed. Check that REGION describes a valid range" << endl;
189 cerr << "bamtools convert ERROR: could not parse REGION: " << m_settings->Region << endl;
190 cerr << "Check that REGION is in valid format (see documentation) and that the coordinates are valid"
197 // if output file given
199 if ( m_settings->HasOutput ) {
201 // open output file stream
202 outFile.open(m_settings->OutputFilename.c_str());
204 cerr << "bamtools convert ERROR: could not open " << m_settings->OutputFilename
205 << " for output" << endl;
209 // set m_out to file's streambuf
210 m_out.rdbuf(outFile.rdbuf());
213 // -------------------------------------
214 // do conversion based on format
216 bool convertedOk = true;
218 // pileup is special case
219 // conversion not done per alignment, like the other formats
220 if ( m_settings->Format == FORMAT_PILEUP )
221 convertedOk = RunPileupConversion(&reader);
226 bool formatError = false;
228 // set function pointer to proper conversion method
229 void (BamTools::ConvertTool::ConvertToolPrivate::*pFunction)(const BamAlignment&) = 0;
230 if ( m_settings->Format == FORMAT_BED ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintBed;
231 else if ( m_settings->Format == FORMAT_FASTA ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFasta;
232 else if ( m_settings->Format == FORMAT_FASTQ ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFastq;
233 else if ( m_settings->Format == FORMAT_JSON ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintJson;
234 else if ( m_settings->Format == FORMAT_SAM ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintSam;
235 else if ( m_settings->Format == FORMAT_YAML ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintYaml;
237 cerr << "bamtools convert ERROR: unrecognized format: " << m_settings->Format << endl;
238 cerr << "Please see documentation for list of supported formats " << endl;
243 // if format selected ok
244 if ( !formatError ) {
246 // if SAM format & not omitting header, print SAM header first
247 if ( (m_settings->Format == FORMAT_SAM) && !m_settings->IsOmittingSamHeader )
248 m_out << reader.GetHeaderText();
250 // iterate through file, doing conversion
252 while ( reader.GetNextAlignment(a) )
253 (this->*pFunction)(a);
255 // set flag for successful conversion
260 // ------------------------
263 if ( m_settings->HasOutput )
268 // ----------------------------------------------------------
269 // Conversion/output methods
270 // ----------------------------------------------------------
272 void ConvertTool::ConvertToolPrivate::PrintBed(const BamAlignment& a) {
274 // tab-delimited, 0-based half-open
275 // (e.g. a 50-base read aligned to pos 10 could have BED coordinates (10, 60) instead of BAM coordinates (10, 59) )
276 // <chromName> <chromStart> <chromEnd> <readName> <score> <strand>
278 m_out << m_references.at(a.RefID).RefName << "\t"
279 << a.Position << "\t"
280 << a.GetEndPosition() << "\t"
282 << a.MapQuality << "\t"
283 << (a.IsReverseStrand() ? "-" : "+") << endl;
286 // print BamAlignment in FASTA format
287 // N.B. - uses QueryBases NOT AlignedBases
288 void ConvertTool::ConvertToolPrivate::PrintFasta(const BamAlignment& a) {
290 // >BamAlignment.Name
291 // BamAlignment.QueryBases (up to FASTA_LINE_MAX bases per line)
294 // N.B. - QueryBases are reverse-complemented if aligned to reverse strand
297 m_out << ">" << a.Name << endl;
299 // handle reverse strand alignment - bases
300 string sequence = a.QueryBases;
301 if ( a.IsReverseStrand() )
302 Utilities::ReverseComplement(sequence);
304 // if sequence fits on single line
305 if ( sequence.length() <= FASTA_LINE_MAX )
306 m_out << sequence << endl;
308 // else split over multiple lines
312 size_t seqLength = sequence.length(); // handle reverse strand alignment - bases & qualitiesth();
314 // write subsequences to each line
315 while ( position < (seqLength - FASTA_LINE_MAX) ) {
316 m_out << sequence.substr(position, FASTA_LINE_MAX) << endl;
317 position += FASTA_LINE_MAX;
320 // write final subsequence
321 m_out << sequence.substr(position) << endl;
325 // print BamAlignment in FASTQ format
326 // N.B. - uses QueryBases NOT AlignedBases
327 void ConvertTool::ConvertToolPrivate::PrintFastq(const BamAlignment& a) {
329 // @BamAlignment.Name
330 // BamAlignment.QueryBases
332 // BamAlignment.Qualities
334 // N.B. - QueryBases are reverse-complemented (& Qualities reversed) if aligned to reverse strand .
335 // Name is appended "/1" or "/2" if paired-end, to reflect which mate this entry is.
337 // handle paired-end alignments
338 string name = a.Name;
340 name.append( (a.IsFirstMate() ? "/1" : "/2") );
342 // handle reverse strand alignment - bases & qualities
343 string qualities = a.Qualities;
344 string sequence = a.QueryBases;
345 if ( a.IsReverseStrand() ) {
346 Utilities::Reverse(qualities);
347 Utilities::ReverseComplement(sequence);
350 // write to output stream
351 m_out << "@" << name << endl
354 << qualities << endl;
357 // print BamAlignment in JSON format
358 void ConvertTool::ConvertToolPrivate::PrintJson(const BamAlignment& a) {
360 // write name & alignment flag
361 m_out << "{\"name\":\"" << a.Name << "\",\"alignmentFlag\":\"" << a.AlignmentFlag << "\",";
363 // write reference name
364 if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) )
365 m_out << "\"reference\":\"" << m_references[a.RefID].RefName << "\",";
367 // write position & map quality
368 m_out << "\"position\":" << a.Position+1 << ",\"mapQuality\":" << a.MapQuality << ",";
371 const vector<CigarOp>& cigarData = a.CigarData;
372 if ( !cigarData.empty() ) {
373 m_out << "\"cigar\":[";
374 vector<CigarOp>::const_iterator cigarBegin = cigarData.begin();
375 vector<CigarOp>::const_iterator cigarIter = cigarBegin;
376 vector<CigarOp>::const_iterator cigarEnd = cigarData.end();
377 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
378 const CigarOp& op = (*cigarIter);
379 if (cigarIter != cigarBegin)
381 m_out << "\"" << op.Length << op.Type << "\"";
386 // write mate reference name, mate position, & insert size
387 if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
388 m_out << "\"mate\":{"
389 << "\"reference\":\"" << m_references[a.MateRefID].RefName << "\","
390 << "\"position\":" << a.MatePosition+1
391 << ",\"insertSize\":" << a.InsertSize << "},";
395 if ( !a.QueryBases.empty() )
396 m_out << "\"queryBases\":\"" << a.QueryBases << "\",";
399 if ( !a.Qualities.empty() ) {
400 string::const_iterator s = a.Qualities.begin();
401 m_out << "\"qualities\":[" << static_cast<short>(*s) - 33;
403 for ( ; s != a.Qualities.end(); ++s )
404 m_out << "," << static_cast<short>(*s) - 33;
408 // write alignment's source BAM file
409 m_out << "\"filename\":" << a.Filename << ",";
412 const char* tagData = a.TagData.c_str();
413 const size_t tagDataLength = a.TagData.length();
415 if ( index < tagDataLength ) {
417 m_out << "\"tags\":{";
419 while ( index < tagDataLength ) {
425 m_out << "\"" << a.TagData.substr(index, 2) << "\":";
429 char type = a.TagData.at(index);
432 case (Constants::BAM_TAG_TYPE_ASCII) :
433 m_out << "\"" << tagData[index] << "\"";
437 case (Constants::BAM_TAG_TYPE_INT8) :
438 case (Constants::BAM_TAG_TYPE_UINT8) :
439 m_out << (int)tagData[index];
443 case (Constants::BAM_TAG_TYPE_INT16) :
444 m_out << BamTools::UnpackSignedShort(&tagData[index]);
445 index += sizeof(int16_t);
448 case (Constants::BAM_TAG_TYPE_UINT16) :
449 m_out << BamTools::UnpackUnsignedShort(&tagData[index]);
450 index += sizeof(uint16_t);
453 case (Constants::BAM_TAG_TYPE_INT32) :
454 m_out << BamTools::UnpackSignedInt(&tagData[index]);
455 index += sizeof(int32_t);
458 case (Constants::BAM_TAG_TYPE_UINT32) :
459 m_out << BamTools::UnpackUnsignedInt(&tagData[index]);
460 index += sizeof(uint32_t);
463 case (Constants::BAM_TAG_TYPE_FLOAT) :
464 m_out << BamTools::UnpackFloat(&tagData[index]);
465 index += sizeof(float);
468 case (Constants::BAM_TAG_TYPE_HEX) :
469 case (Constants::BAM_TAG_TYPE_STRING) :
471 while (tagData[index]) {
472 if (tagData[index] == '\"')
473 m_out << "\\\""; // escape for json
475 m_out << tagData[index];
483 if ( tagData[index] == '\0')
490 m_out << "}" << endl;
493 // print BamAlignment in SAM format
494 void ConvertTool::ConvertToolPrivate::PrintSam(const BamAlignment& a) {
497 // <QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> [ <TAG>:<VTYPE>:<VALUE> [...] ]
499 // write name & alignment flag
500 m_out << a.Name << "\t" << a.AlignmentFlag << "\t";
502 // write reference name
503 if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) )
504 m_out << m_references[a.RefID].RefName << "\t";
508 // write position & map quality
509 m_out << a.Position+1 << "\t" << a.MapQuality << "\t";
512 const vector<CigarOp>& cigarData = a.CigarData;
513 if ( cigarData.empty() ) m_out << "*\t";
515 vector<CigarOp>::const_iterator cigarIter = cigarData.begin();
516 vector<CigarOp>::const_iterator cigarEnd = cigarData.end();
517 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
518 const CigarOp& op = (*cigarIter);
519 m_out << op.Length << op.Type;
524 // write mate reference name, mate position, & insert size
525 if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
526 if ( a.MateRefID == a.RefID )
529 m_out << m_references[a.MateRefID].RefName << "\t";
530 m_out << a.MatePosition+1 << "\t" << a.InsertSize << "\t";
533 m_out << "*\t0\t0\t";
536 if ( a.QueryBases.empty() )
539 m_out << a.QueryBases << "\t";
542 if ( a.Qualities.empty() )
545 m_out << a.Qualities;
548 const char* tagData = a.TagData.c_str();
549 const size_t tagDataLength = a.TagData.length();
552 while ( index < tagDataLength ) {
555 string tagName = a.TagData.substr(index, 2);
556 m_out << "\t" << tagName << ":";
560 char type = a.TagData.at(index);
563 case (Constants::BAM_TAG_TYPE_ASCII) :
564 m_out << "A:" << tagData[index];
568 case (Constants::BAM_TAG_TYPE_INT8) :
569 case (Constants::BAM_TAG_TYPE_UINT8) :
570 m_out << "i:" << (int)tagData[index];
574 case (Constants::BAM_TAG_TYPE_INT16) :
575 m_out << "i:" << BamTools::UnpackSignedShort(&tagData[index]);
576 index += sizeof(int16_t);
579 case (Constants::BAM_TAG_TYPE_UINT16) :
580 m_out << "i:" << BamTools::UnpackUnsignedShort(&tagData[index]);
581 index += sizeof(uint16_t);
584 case (Constants::BAM_TAG_TYPE_INT32) :
585 m_out << "i:" << BamTools::UnpackSignedInt(&tagData[index]);
586 index += sizeof(int32_t);
589 case (Constants::BAM_TAG_TYPE_UINT32) :
590 m_out << "i:" << BamTools::UnpackUnsignedInt(&tagData[index]);
591 index += sizeof(uint32_t);
594 case (Constants::BAM_TAG_TYPE_FLOAT) :
595 m_out << "f:" << BamTools::UnpackFloat(&tagData[index]);
596 index += sizeof(float);
599 case (Constants::BAM_TAG_TYPE_HEX) :
600 case (Constants::BAM_TAG_TYPE_STRING) :
601 m_out << type << ":";
602 while (tagData[index]) {
603 m_out << tagData[index];
610 if ( tagData[index] == '\0')
617 // Print BamAlignment in YAML format
618 void ConvertTool::ConvertToolPrivate::PrintYaml(const BamAlignment& a) {
620 // write alignment name
621 m_out << "---" << endl;
622 m_out << a.Name << ":" << endl;
624 // write alignment data
625 m_out << " " << "AlndBases: " << a.AlignedBases << endl;
626 m_out << " " << "Qualities: " << a.Qualities << endl;
627 m_out << " " << "Name: " << a.Name << endl;
628 m_out << " " << "Length: " << a.Length << endl;
629 m_out << " " << "TagData: " << a.TagData << endl;
630 m_out << " " << "RefID: " << a.RefID << endl;
631 m_out << " " << "RefName: " << m_references[a.RefID].RefName << endl;
632 m_out << " " << "Position: " << a.Position << endl;
633 m_out << " " << "Bin: " << a.Bin << endl;
634 m_out << " " << "MapQuality: " << a.MapQuality << endl;
635 m_out << " " << "AlignmentFlag: " << a.AlignmentFlag << endl;
636 m_out << " " << "MateRefID: " << a.MateRefID << endl;
637 m_out << " " << "MatePosition: " << a.MatePosition << endl;
638 m_out << " " << "InsertSize: " << a.InsertSize << endl;
639 m_out << " " << "Filename: " << a.Filename << endl;
642 const vector<CigarOp>& cigarData = a.CigarData;
643 if ( !cigarData.empty() ) {
644 m_out << " " << "Cigar: ";
645 vector<CigarOp>::const_iterator cigarBegin = cigarData.begin();
646 vector<CigarOp>::const_iterator cigarIter = cigarBegin;
647 vector<CigarOp>::const_iterator cigarEnd = cigarData.end();
648 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
649 const CigarOp& op = (*cigarIter);
650 m_out << op.Length << op.Type;
656 bool ConvertTool::ConvertToolPrivate::RunPileupConversion(BamMultiReader* reader) {
658 // check for valid BamMultiReader
659 if ( reader == 0 ) return false;
661 // set up our pileup format 'visitor'
662 ConvertPileupFormatVisitor* v = new ConvertPileupFormatVisitor(m_references,
663 m_settings->FastaFilename,
664 m_settings->IsPrintingPileupMapQualities,
667 // set up PileupEngine
669 pileup.AddVisitor(v);
671 // iterate through data
673 while ( reader->GetNextAlignment(al) )
674 pileup.AddAlignment(al);
685 // ---------------------------------------------
686 // ConvertTool implementation
688 ConvertTool::ConvertTool(void)
690 , m_settings(new ConvertSettings)
693 // set program details
694 Options::SetProgramInfo("bamtools convert", "converts BAM to a number of other formats", "-format <FORMAT> [-in <filename> -in <filename> ...] [-out <filename>] [-region <REGION>] [format-specific options]");
697 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
698 Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts, Options::StandardIn());
699 Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutput, m_settings->OutputFilename, IO_Opts, Options::StandardOut());
700 Options::AddValueOption("-format", "FORMAT", "the output file format - see README for recognized formats", "", m_settings->HasFormat, m_settings->Format, IO_Opts);
701 Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance, and is used automatically if it exists. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, IO_Opts);
703 OptionGroup* PileupOpts = Options::CreateOptionGroup("Pileup Options");
704 Options::AddValueOption("-fasta", "FASTA filename", "FASTA reference file", "", m_settings->HasFastaFilename, m_settings->FastaFilename, PileupOpts);
705 Options::AddOption("-mapqual", "print the mapping qualities", m_settings->IsPrintingPileupMapQualities, PileupOpts);
707 OptionGroup* SamOpts = Options::CreateOptionGroup("SAM Options");
708 Options::AddOption("-noheader", "omit the SAM header from output", m_settings->IsOmittingSamHeader, SamOpts);
711 ConvertTool::~ConvertTool(void) {
720 int ConvertTool::Help(void) {
721 Options::DisplayHelp();
725 int ConvertTool::Run(int argc, char* argv[]) {
727 // parse command line arguments
728 Options::Parse(argc, argv, 1);
730 // initialize ConvertTool with settings
731 m_impl = new ConvertToolPrivate(m_settings);
733 // run ConvertTool, return success/fail
740 // ---------------------------------------------
741 // ConvertPileupFormatVisitor implementation
743 ConvertPileupFormatVisitor::ConvertPileupFormatVisitor(const RefVector& references,
744 const string& fastaFilename,
745 const bool isPrintingMapQualities,
749 , m_isPrintingMapQualities(isPrintingMapQualities)
751 , m_references(references)
753 // set up Fasta reader if file is provided
754 if ( !fastaFilename.empty() ) {
756 // check for FASTA index
757 string indexFilename = "";
758 if ( Utilities::FileExists(fastaFilename + ".fai") )
759 indexFilename = fastaFilename + ".fai";
762 if ( m_fasta.Open(fastaFilename, indexFilename) )
767 ConvertPileupFormatVisitor::~ConvertPileupFormatVisitor(void) {
768 // be sure to close Fasta reader
775 void ConvertPileupFormatVisitor::Visit(const PileupPosition& pileupData ) {
777 // skip if no alignments at this position
778 if ( pileupData.PileupAlignments.empty() ) return;
780 // retrieve reference name
781 const string& referenceName = m_references[pileupData.RefId].RefName;
782 const int& position = pileupData.Position;
784 // retrieve reference base from FASTA file, if one provided; otherwise default to 'N'
785 char referenceBase('N');
786 if ( m_hasFasta && (pileupData.Position < m_references[pileupData.RefId].RefLength) ) {
787 if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position, referenceBase ) ) {
788 cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file" << endl;
793 // get count of alleles at this position
794 const int numberAlleles = pileupData.PileupAlignments.size();
796 // -----------------------------------------------------------
797 // build strings based on alleles at this positionInAlignment
799 stringstream bases("");
800 stringstream baseQualities("");
801 stringstream mapQualities("");
803 // iterate over alignments at this pileup position
804 vector<PileupAlignment>::const_iterator pileupIter = pileupData.PileupAlignments.begin();
805 vector<PileupAlignment>::const_iterator pileupEnd = pileupData.PileupAlignments.end();
806 for ( ; pileupIter != pileupEnd; ++pileupIter ) {
807 const PileupAlignment pa = (*pileupIter);
808 const BamAlignment& ba = pa.Alignment;
810 // if beginning of read segment
811 if ( pa.IsSegmentBegin )
812 bases << '^' << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
814 // if current base is not a DELETION
815 if ( !pa.IsCurrentDeletion ) {
817 // get base at current position
818 char base = ba.QueryBases.at(pa.PositionInAlignment);
820 // if base matches reference
822 toupper(base) == toupper(referenceBase) ||
823 tolower(base) == tolower(referenceBase) )
825 base = ( ba.IsReverseStrand() ? ',' : '.' );
828 // mismatches reference
829 else base = ( ba.IsReverseStrand() ? tolower(base) : toupper(base) );
834 // if next position contains insertion
835 if ( pa.IsNextInsertion ) {
836 bases << '+' << pa.InsertionLength;
837 for (int i = 1; i <= pa.InsertionLength; ++i) {
838 char insertedBase = (char)ba.QueryBases.at(pa.PositionInAlignment + i);
839 bases << (ba.IsReverseStrand() ? (char)tolower(insertedBase) : (char)toupper(insertedBase) );
843 // if next position contains DELETION
844 else if ( pa.IsNextDeletion ) {
845 bases << '-' << pa.DeletionLength;
846 for (int i = 1; i <= pa.DeletionLength; ++i) {
847 char deletedBase('N');
848 if ( m_hasFasta && (pileupData.Position+i < m_references[pileupData.RefId].RefLength) ) {
849 if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position+i, deletedBase ) ) {
850 cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file" << endl;
854 bases << (ba.IsReverseStrand() ? (char)tolower(deletedBase) : (char)toupper(deletedBase) );
859 // otherwise, DELETION
862 // if end of read segment
863 if ( pa.IsSegmentEnd )
866 // store current base quality
867 baseQualities << ba.Qualities.at(pa.PositionInAlignment);
869 // save alignment map quality if desired
870 if ( m_isPrintingMapQualities )
871 mapQualities << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
874 // ----------------------
878 // <refName> <1-based pos> <refBase> <numberAlleles> <bases> <qualities> [mapQuals]
880 const string TAB = "\t";
881 *m_out << referenceName << TAB
882 << position + 1 << TAB
883 << referenceBase << TAB
884 << numberAlleles << TAB
885 << bases.str() << TAB
886 << baseQualities.str() << TAB
887 << mapQualities.str() << endl;