]> git.donarmstrong.com Git - bamtools.git/blob - src/toolkit/bamtools_convert.cpp
1de3a3115e8cb8d9a1eda81adf8b2429a5ade8fa
[bamtools.git] / src / toolkit / bamtools_convert.cpp
1 // ***************************************************************************
2 // bamtools_convert.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 26 September 2012
6 // ---------------------------------------------------------------------------
7 // Converts between BAM and a number of other formats
8 // ***************************************************************************
9
10 #include "bamtools_convert.h"
11
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;
19
20 #include <fstream>
21 #include <iostream>
22 #include <sstream>
23 #include <string>
24 #include <vector>
25 using namespace std;
26   
27 namespace BamTools { 
28   
29 // ---------------------------------------------
30 // ConvertTool constants
31
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";
40
41 // other constants
42 static const unsigned int FASTA_LINE_MAX = 50;
43
44 // ---------------------------------------------
45 // ConvertPileupFormatVisitor declaration
46
47 class ConvertPileupFormatVisitor : public PileupVisitor {
48
49     // ctor & dtor
50     public:
51         ConvertPileupFormatVisitor(const RefVector& references,
52                                    const string& fastaFilename,
53                                    const bool isPrintingMapQualities,
54                                    ostream* out);
55         ~ConvertPileupFormatVisitor(void);
56
57     // PileupVisitor interface implementation
58     public:
59         void Visit(const PileupPosition& pileupData);
60
61     // data members
62     private:
63         Fasta     m_fasta;
64         bool      m_hasFasta;
65         bool      m_isPrintingMapQualities;
66         ostream*  m_out;
67         RefVector m_references;
68 };
69     
70 } // namespace BamTools
71   
72 // ---------------------------------------------
73 // ConvertSettings implementation
74
75 struct ConvertTool::ConvertSettings {
76
77     // flag
78     bool HasInput;
79     bool HasOutput;
80     bool HasFormat;
81     bool HasRegion;
82
83     // pileup flags
84     bool HasFastaFilename;
85     bool IsOmittingSamHeader;
86     bool IsPrintingPileupMapQualities;
87     
88     // options
89     vector<string> InputFiles;
90     string OutputFilename;
91     string Format;
92     string Region;
93     
94     // pileup options
95     string FastaFilename;
96
97     // constructor
98     ConvertSettings(void)
99         : HasInput(false)
100         , HasOutput(false)
101         , HasFormat(false)
102         , HasRegion(false)
103         , HasFastaFilename(false)
104         , IsOmittingSamHeader(false)
105         , IsPrintingPileupMapQualities(false)
106         , OutputFilename(Options::StandardOut())
107         , FastaFilename("")
108     { } 
109 };    
110
111 // ---------------------------------------------
112 // ConvertToolPrivate implementation  
113   
114 struct ConvertTool::ConvertToolPrivate {
115   
116     // ctor & dtor
117     public:
118         ConvertToolPrivate(ConvertTool::ConvertSettings* settings)
119             : m_settings(settings)
120             , m_out(cout.rdbuf())
121         { }
122
123         ~ConvertToolPrivate(void) { }
124     
125     // interface
126     public:
127         bool Run(void);
128         
129     // internal methods
130     private:
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);
137         
138         // special case - uses the PileupEngine
139         bool RunPileupConversion(BamMultiReader* reader);
140         
141     // data members
142     private: 
143         ConvertTool::ConvertSettings* m_settings;
144         RefVector m_references;
145         ostream m_out;
146 };
147
148 bool ConvertTool::ConvertToolPrivate::Run(void) {
149  
150     // ------------------------------------
151     // initialize conversion input/output
152         
153     // set to default input if none provided
154     if ( !m_settings->HasInput ) 
155         m_settings->InputFiles.push_back(Options::StandardIn());
156     
157     // open input files
158     BamMultiReader reader;
159     if ( !reader.Open(m_settings->InputFiles) ) {
160         cerr << "bamtools convert ERROR: could not open input BAM file(s)... Aborting." << endl;
161         return false;
162     }
163
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;
168             return false;
169         }
170     }
171
172     // retrieve reference data
173     m_references = reader.GetReferenceData();
174
175     // set region if specified
176     BamRegion region;
177     if ( m_settings->HasRegion ) {
178         if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
179
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;
183                     reader.Close();
184                     return false;
185                 }
186             }
187
188         } else {
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"
191                  << endl;
192             reader.Close();
193             return false;
194         }
195     }
196         
197     // if output file given
198     ofstream outFile;
199     if ( m_settings->HasOutput ) {
200       
201         // open output file stream
202         outFile.open(m_settings->OutputFilename.c_str());
203         if ( !outFile ) {
204             cerr << "bamtools convert ERROR: could not open " << m_settings->OutputFilename
205                  << " for output" << endl;
206             return false; 
207         }
208         
209         // set m_out to file's streambuf
210         m_out.rdbuf(outFile.rdbuf()); 
211     }
212     
213     // -------------------------------------
214     // do conversion based on format
215     
216      bool convertedOk = true;
217     
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);
222     
223     // all other formats
224     else {
225     
226         bool formatError = false;
227         
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;
236         else { 
237             cerr << "bamtools convert ERROR: unrecognized format: " << m_settings->Format << endl;
238             cerr << "Please see documentation for list of supported formats " << endl;
239             formatError = true;
240             convertedOk = false;
241         }
242         
243         // if format selected ok
244         if ( !formatError ) {
245         
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();
249             
250             // iterate through file, doing conversion
251             BamAlignment a;
252             while ( reader.GetNextAlignment(a) )
253                 (this->*pFunction)(a);
254             
255             // set flag for successful conversion
256             convertedOk = true;
257         }
258     }
259     
260     // ------------------------
261     // clean up & exit
262     reader.Close();
263     if ( m_settings->HasOutput )
264         outFile.close();
265     return convertedOk;   
266 }
267
268 // ----------------------------------------------------------
269 // Conversion/output methods
270 // ----------------------------------------------------------
271
272 void ConvertTool::ConvertToolPrivate::PrintBed(const BamAlignment& a) { 
273   
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>
277
278     m_out << m_references.at(a.RefID).RefName << "\t"
279           << a.Position << "\t"
280           << a.GetEndPosition() << "\t"
281           << a.Name << "\t"
282           << a.MapQuality << "\t"
283           << (a.IsReverseStrand() ? "-" : "+") << endl;
284 }
285
286 // print BamAlignment in FASTA format
287 // N.B. - uses QueryBases NOT AlignedBases
288 void ConvertTool::ConvertToolPrivate::PrintFasta(const BamAlignment& a) { 
289     
290     // >BamAlignment.Name
291     // BamAlignment.QueryBases (up to FASTA_LINE_MAX bases per line)
292     // ...
293     //
294     // N.B. - QueryBases are reverse-complemented if aligned to reverse strand
295   
296     // print header
297     m_out << ">" << a.Name << endl;
298     
299     // handle reverse strand alignment - bases 
300     string sequence = a.QueryBases;
301     if ( a.IsReverseStrand() )
302         Utilities::ReverseComplement(sequence);
303     
304     // if sequence fits on single line
305     if ( sequence.length() <= FASTA_LINE_MAX )
306         m_out << sequence << endl;
307     
308     // else split over multiple lines
309     else {
310       
311         size_t position = 0;
312         size_t seqLength = sequence.length(); // handle reverse strand alignment - bases & qualitiesth();
313         
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;
318         }
319         
320         // write final subsequence
321         m_out << sequence.substr(position) << endl;
322     }
323 }
324
325 // print BamAlignment in FASTQ format
326 // N.B. - uses QueryBases NOT AlignedBases
327 void ConvertTool::ConvertToolPrivate::PrintFastq(const BamAlignment& a) { 
328   
329     // @BamAlignment.Name
330     // BamAlignment.QueryBases
331     // +
332     // BamAlignment.Qualities
333     //
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.
336   
337     // handle paired-end alignments
338     string name = a.Name;
339     if ( a.IsPaired() )
340         name.append( (a.IsFirstMate() ? "/1" : "/2") );
341   
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);
348     }
349   
350     // write to output stream
351     m_out << "@" << name << endl
352           << sequence    << endl
353           << "+"         << endl
354           << qualities   << endl;
355 }
356
357 // print BamAlignment in JSON format
358 void ConvertTool::ConvertToolPrivate::PrintJson(const BamAlignment& a) {
359   
360     // write name & alignment flag
361     m_out << "{\"name\":\"" << a.Name << "\",\"alignmentFlag\":\"" << a.AlignmentFlag << "\",";
362     
363     // write reference name
364     if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) ) 
365         m_out << "\"reference\":\"" << m_references[a.RefID].RefName << "\",";
366     
367     // write position & map quality
368     m_out << "\"position\":" << a.Position+1 << ",\"mapQuality\":" << a.MapQuality << ",";
369     
370     // write CIGAR
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)
380                 m_out << ",";
381             m_out << "\"" << op.Length << op.Type << "\"";
382         }
383         m_out << "],";
384     }
385     
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 << "},";
392     }
393     
394     // write sequence
395     if ( !a.QueryBases.empty() ) 
396         m_out << "\"queryBases\":\"" << a.QueryBases << "\",";
397     
398     // write qualities
399     if ( !a.Qualities.empty() && a.Qualities.at(0) != (char)0xFF ) {
400         string::const_iterator s = a.Qualities.begin();
401         m_out << "\"qualities\":[" << static_cast<short>(*s) - 33;
402         ++s;
403         for ( ; s != a.Qualities.end(); ++s )
404             m_out << "," << static_cast<short>(*s) - 33;
405         m_out << "],";
406     }
407     
408     // write alignment's source BAM file
409     m_out << "\"filename\":" << a.Filename << ",";
410
411     // write tag data
412     const char* tagData = a.TagData.c_str();
413     const size_t tagDataLength = a.TagData.length();
414     size_t index = 0;
415     if ( index < tagDataLength ) {
416
417         m_out << "\"tags\":{";
418         
419         while ( index < tagDataLength ) {
420
421             if ( index > 0 )
422                 m_out << ",";
423             
424             // write tag name
425             m_out << "\"" << a.TagData.substr(index, 2) << "\":";
426             index += 2;
427             
428             // get data type
429             char type = a.TagData.at(index);
430             ++index;
431             switch ( type ) {
432                 case (Constants::BAM_TAG_TYPE_ASCII) :
433                     m_out << "\"" << tagData[index] << "\"";
434                     ++index; 
435                     break;
436                 
437                 case (Constants::BAM_TAG_TYPE_INT8) :
438                     m_out << (int8_t)tagData[index];
439                     ++index;
440                     break;
441
442                 case (Constants::BAM_TAG_TYPE_UINT8) :
443                     m_out << (uint8_t)tagData[index];
444                     ++index; 
445                     break;
446                 
447                 case (Constants::BAM_TAG_TYPE_INT16) :
448                     m_out << BamTools::UnpackSignedShort(&tagData[index]);
449                     index += sizeof(int16_t);
450                     break;
451
452                 case (Constants::BAM_TAG_TYPE_UINT16) :
453                     m_out << BamTools::UnpackUnsignedShort(&tagData[index]);
454                     index += sizeof(uint16_t);
455                     break;
456                     
457                 case (Constants::BAM_TAG_TYPE_INT32) :
458                     m_out << BamTools::UnpackSignedInt(&tagData[index]);
459                     index += sizeof(int32_t);
460                     break;
461
462                 case (Constants::BAM_TAG_TYPE_UINT32) :
463                     m_out << BamTools::UnpackUnsignedInt(&tagData[index]);
464                     index += sizeof(uint32_t);
465                     break;
466
467                 case (Constants::BAM_TAG_TYPE_FLOAT) :
468                     m_out << BamTools::UnpackFloat(&tagData[index]);
469                     index += sizeof(float);
470                     break;
471                 
472                 case (Constants::BAM_TAG_TYPE_HEX)    :
473                 case (Constants::BAM_TAG_TYPE_STRING) :
474                     m_out << "\""; 
475                     while (tagData[index]) {
476                         if (tagData[index] == '\"')
477                             m_out << "\\\""; // escape for json
478                         else
479                             m_out << tagData[index];
480                         ++index;
481                     }
482                     m_out << "\""; 
483                     ++index; 
484                     break;      
485             }
486             
487             if ( tagData[index] == '\0') 
488                 break;
489         }
490
491         m_out << "}";
492     }
493
494     m_out << "}" << endl;
495 }
496
497 // print BamAlignment in SAM format
498 void ConvertTool::ConvertToolPrivate::PrintSam(const BamAlignment& a) {
499   
500     // tab-delimited
501     // <QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> [ <TAG>:<VTYPE>:<VALUE> [...] ]
502   
503     // write name & alignment flag
504     m_out << a.Name << "\t" << a.AlignmentFlag << "\t";
505     
506     // write reference name
507     if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) ) 
508         m_out << m_references[a.RefID].RefName << "\t";
509     else 
510         m_out << "*\t";
511     
512     // write position & map quality
513     m_out << a.Position+1 << "\t" << a.MapQuality << "\t";
514     
515     // write CIGAR
516     const vector<CigarOp>& cigarData = a.CigarData;
517     if ( cigarData.empty() ) m_out << "*\t";
518     else {
519         vector<CigarOp>::const_iterator cigarIter = cigarData.begin();
520         vector<CigarOp>::const_iterator cigarEnd  = cigarData.end();
521         for ( ; cigarIter != cigarEnd; ++cigarIter ) {
522             const CigarOp& op = (*cigarIter);
523             m_out << op.Length << op.Type;
524         }
525         m_out << "\t";
526     }
527     
528     // write mate reference name, mate position, & insert size
529     if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
530         if ( a.MateRefID == a.RefID )
531             m_out << "=\t";
532         else
533             m_out << m_references[a.MateRefID].RefName << "\t";
534         m_out << a.MatePosition+1 << "\t" << a.InsertSize << "\t";
535     } 
536     else
537         m_out << "*\t0\t0\t";
538     
539     // write sequence
540     if ( a.QueryBases.empty() )
541         m_out << "*\t";
542     else
543         m_out << a.QueryBases << "\t";
544     
545     // write qualities
546     if ( a.Qualities.empty() || (a.Qualities.at(0) == (char)0xFF) )
547         m_out << "*";
548     else
549         m_out << a.Qualities;
550     
551     // write tag data
552     const char* tagData = a.TagData.c_str();
553     const size_t tagDataLength = a.TagData.length();
554     
555     size_t index = 0;
556     while ( index < tagDataLength ) {
557
558         // write tag name   
559         string tagName = a.TagData.substr(index, 2);
560         m_out << "\t" << tagName << ":";
561         index += 2;
562         
563         // get data type
564         char type = a.TagData.at(index);
565         ++index;
566         switch ( type ) {
567             case (Constants::BAM_TAG_TYPE_ASCII) :
568                 m_out << "A:" << tagData[index];
569                 ++index;
570                 break;
571
572             case (Constants::BAM_TAG_TYPE_INT8)  :
573                 m_out << "i:" << (int8_t)tagData[index];
574                 ++index;
575                 break;
576
577             case (Constants::BAM_TAG_TYPE_UINT8) :
578                 m_out << "i:" << (uint8_t)tagData[index];
579                 ++index;
580                 break;
581
582             case (Constants::BAM_TAG_TYPE_INT16) :
583                 m_out << "i:" << BamTools::UnpackSignedShort(&tagData[index]);
584                 index += sizeof(int16_t);
585                 break;
586
587             case (Constants::BAM_TAG_TYPE_UINT16) :
588                 m_out << "i:" << BamTools::UnpackUnsignedShort(&tagData[index]);
589                 index += sizeof(uint16_t);
590                 break;
591
592             case (Constants::BAM_TAG_TYPE_INT32) :
593                 m_out << "i:" << BamTools::UnpackSignedInt(&tagData[index]);
594                 index += sizeof(int32_t);
595                 break;
596
597             case (Constants::BAM_TAG_TYPE_UINT32) :
598                 m_out << "i:" << BamTools::UnpackUnsignedInt(&tagData[index]);
599                 index += sizeof(uint32_t);
600                 break;
601
602             case (Constants::BAM_TAG_TYPE_FLOAT) :
603                 m_out << "f:" << BamTools::UnpackFloat(&tagData[index]);
604                 index += sizeof(float);
605                 break;
606
607             case (Constants::BAM_TAG_TYPE_HEX)    :
608             case (Constants::BAM_TAG_TYPE_STRING) :
609                 m_out << type << ":";
610                 while (tagData[index]) {
611                     m_out << tagData[index];
612                     ++index;
613                 }
614                 ++index;
615                 break;
616         }
617
618         if ( tagData[index] == '\0') 
619             break;
620     }
621
622     m_out << endl;
623 }
624
625 // Print BamAlignment in YAML format
626 void ConvertTool::ConvertToolPrivate::PrintYaml(const BamAlignment& a) {
627
628     // write alignment name
629     m_out << "---" << endl;
630     m_out << a.Name << ":" << endl;
631
632     // write alignment data
633     m_out << "   " << "AlndBases: "     << a.AlignedBases << endl;
634     m_out << "   " << "Qualities: "     << a.Qualities << endl;
635     m_out << "   " << "Name: "          << a.Name << endl;
636     m_out << "   " << "Length: "        << a.Length << endl;
637     m_out << "   " << "TagData: "       << a.TagData << endl;
638     m_out << "   " << "RefID: "         << a.RefID << endl;
639     m_out << "   " << "RefName: "       << m_references[a.RefID].RefName << endl;
640     m_out << "   " << "Position: "      << a.Position << endl;
641     m_out << "   " << "Bin: "           << a.Bin << endl;
642     m_out << "   " << "MapQuality: "    << a.MapQuality << endl;
643     m_out << "   " << "AlignmentFlag: " << a.AlignmentFlag << endl;
644     m_out << "   " << "MateRefID: "     << a.MateRefID << endl;
645     m_out << "   " << "MatePosition: "  << a.MatePosition << endl;
646     m_out << "   " << "InsertSize: "    << a.InsertSize << endl;
647     m_out << "   " << "Filename: "      << a.Filename << endl;
648
649     // write Cigar data
650     const vector<CigarOp>& cigarData = a.CigarData;
651     if ( !cigarData.empty() ) {
652         m_out << "   " <<  "Cigar: ";
653         vector<CigarOp>::const_iterator cigarBegin = cigarData.begin();
654         vector<CigarOp>::const_iterator cigarIter  = cigarBegin;
655         vector<CigarOp>::const_iterator cigarEnd   = cigarData.end();
656         for ( ; cigarIter != cigarEnd; ++cigarIter ) {
657             const CigarOp& op = (*cigarIter);
658             m_out << op.Length << op.Type;
659         }
660         m_out << endl;
661     }
662 }
663
664 bool ConvertTool::ConvertToolPrivate::RunPileupConversion(BamMultiReader* reader) {
665   
666     // check for valid BamMultiReader
667     if ( reader == 0 ) return false;
668   
669     // set up our pileup format 'visitor'
670     ConvertPileupFormatVisitor* v = new ConvertPileupFormatVisitor(m_references, 
671                                                                    m_settings->FastaFilename,
672                                                                    m_settings->IsPrintingPileupMapQualities, 
673                                                                    &m_out);
674
675     // set up PileupEngine
676     PileupEngine pileup;
677     pileup.AddVisitor(v);
678     
679     // iterate through data
680     BamAlignment al;
681     while ( reader->GetNextAlignment(al) )
682         pileup.AddAlignment(al);
683     pileup.Flush();
684     
685     // clean up
686     delete v;
687     v = 0;
688     
689     // return success
690     return true;
691 }       
692
693 // ---------------------------------------------
694 // ConvertTool implementation
695
696 ConvertTool::ConvertTool(void)
697     : AbstractTool()
698     , m_settings(new ConvertSettings)
699     , m_impl(0)
700 {
701     // set program details
702     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]");
703     
704     // set up options 
705     OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
706     Options::AddValueOption("-in",     "BAM filename", "the input BAM file(s)", "", m_settings->HasInput,   m_settings->InputFiles,     IO_Opts, Options::StandardIn());
707     Options::AddValueOption("-out",    "BAM filename", "the output BAM file",   "", m_settings->HasOutput,  m_settings->OutputFilename, IO_Opts, Options::StandardOut());
708     Options::AddValueOption("-format", "FORMAT", "the output file format - see README for recognized formats", "", m_settings->HasFormat, m_settings->Format, IO_Opts);
709     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);
710     
711     OptionGroup* PileupOpts = Options::CreateOptionGroup("Pileup Options");
712     Options::AddValueOption("-fasta", "FASTA filename", "FASTA reference file", "", m_settings->HasFastaFilename, m_settings->FastaFilename, PileupOpts);
713     Options::AddOption("-mapqual", "print the mapping qualities", m_settings->IsPrintingPileupMapQualities, PileupOpts);
714     
715     OptionGroup* SamOpts = Options::CreateOptionGroup("SAM Options");
716     Options::AddOption("-noheader", "omit the SAM header from output", m_settings->IsOmittingSamHeader, SamOpts);
717 }
718
719 ConvertTool::~ConvertTool(void) {
720
721     delete m_settings;
722     m_settings = 0;
723     
724     delete m_impl;
725     m_impl = 0;
726 }
727
728 int ConvertTool::Help(void) {
729     Options::DisplayHelp();
730     return 0;
731 }
732
733 int ConvertTool::Run(int argc, char* argv[]) {
734   
735     // parse command line arguments
736     Options::Parse(argc, argv, 1);
737     
738     // initialize ConvertTool with settings
739     m_impl = new ConvertToolPrivate(m_settings);
740     
741     // run ConvertTool, return success/fail
742     if ( m_impl->Run() ) 
743         return 0;
744     else 
745         return 1;
746 }
747
748 // ---------------------------------------------
749 // ConvertPileupFormatVisitor implementation
750
751 ConvertPileupFormatVisitor::ConvertPileupFormatVisitor(const RefVector& references, 
752                                                        const string& fastaFilename,
753                                                        const bool isPrintingMapQualities,
754                                                        ostream* out)
755     : PileupVisitor()
756     , m_hasFasta(false)
757     , m_isPrintingMapQualities(isPrintingMapQualities)
758     , m_out(out)
759     , m_references(references)
760
761     // set up Fasta reader if file is provided
762     if ( !fastaFilename.empty() ) {
763       
764         // check for FASTA index
765         string indexFilename = "";
766         if ( Utilities::FileExists(fastaFilename + ".fai") ) 
767             indexFilename = fastaFilename + ".fai";
768       
769         // open FASTA file
770         if ( m_fasta.Open(fastaFilename, indexFilename) ) 
771             m_hasFasta = true;
772     }
773 }
774
775 ConvertPileupFormatVisitor::~ConvertPileupFormatVisitor(void) { 
776     // be sure to close Fasta reader
777     if ( m_hasFasta ) {
778         m_fasta.Close();
779         m_hasFasta = false;
780     }
781 }
782
783 void ConvertPileupFormatVisitor::Visit(const PileupPosition& pileupData ) {
784   
785     // skip if no alignments at this position
786     if ( pileupData.PileupAlignments.empty() ) return;
787   
788     // retrieve reference name
789     const string& referenceName = m_references[pileupData.RefId].RefName;
790     const int& position   = pileupData.Position;
791     
792     // retrieve reference base from FASTA file, if one provided; otherwise default to 'N'
793     char referenceBase('N');
794     if ( m_hasFasta && (pileupData.Position < m_references[pileupData.RefId].RefLength) ) {
795         if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position, referenceBase ) ) {
796             cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file" << endl;
797             return;
798         }
799     }
800     
801     // get count of alleles at this position
802     const int numberAlleles = pileupData.PileupAlignments.size();
803     
804     // -----------------------------------------------------------
805     // build strings based on alleles at this positionInAlignment
806     
807     stringstream bases("");
808     stringstream baseQualities("");
809     stringstream mapQualities("");
810     
811     // iterate over alignments at this pileup position
812     vector<PileupAlignment>::const_iterator pileupIter = pileupData.PileupAlignments.begin();
813     vector<PileupAlignment>::const_iterator pileupEnd  = pileupData.PileupAlignments.end();
814     for ( ; pileupIter != pileupEnd; ++pileupIter ) {
815         const PileupAlignment pa = (*pileupIter);
816         const BamAlignment& ba = pa.Alignment;
817         
818         // if beginning of read segment
819         if ( pa.IsSegmentBegin )
820             bases << '^' << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
821         
822         // if current base is not a DELETION
823         if ( !pa.IsCurrentDeletion ) {
824           
825             // get base at current position
826             char base = ba.QueryBases.at(pa.PositionInAlignment);
827             
828             // if base matches reference
829             if ( base == '=' || 
830                  toupper(base) == toupper(referenceBase) ||
831                  tolower(base) == tolower(referenceBase) ) 
832             {
833                 base = ( ba.IsReverseStrand() ? ',' : '.' );
834             }
835             
836             // mismatches reference
837             else base = ( ba.IsReverseStrand() ? tolower(base) : toupper(base) );
838             
839             // store base
840             bases << base;
841           
842             // if next position contains insertion
843             if ( pa.IsNextInsertion ) {
844                 bases << '+' << pa.InsertionLength;
845                 for (int i = 1; i <= pa.InsertionLength; ++i) {
846                     char insertedBase = (char)ba.QueryBases.at(pa.PositionInAlignment + i);
847                     bases << (ba.IsReverseStrand() ? (char)tolower(insertedBase) : (char)toupper(insertedBase) );
848                 }
849             }
850             
851             // if next position contains DELETION
852             else if ( pa.IsNextDeletion ) {
853                 bases << '-' << pa.DeletionLength;
854                 for (int i = 1; i <= pa.DeletionLength; ++i) {
855                     char deletedBase('N');
856                     if ( m_hasFasta && (pileupData.Position+i < m_references[pileupData.RefId].RefLength) ) {
857                         if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position+i, deletedBase ) ) {
858                             cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file" << endl;
859                             return;
860                         }
861                     }
862                     bases << (ba.IsReverseStrand() ? (char)tolower(deletedBase) : (char)toupper(deletedBase) );
863                 }
864             }
865         }
866         
867         // otherwise, DELETION
868         else bases << '*';
869         
870         // if end of read segment
871         if ( pa.IsSegmentEnd )
872             bases << '$';
873         
874         // store current base quality
875         baseQualities << ba.Qualities.at(pa.PositionInAlignment);
876         
877         // save alignment map quality if desired
878         if ( m_isPrintingMapQualities )
879             mapQualities << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
880     }
881     
882     // ----------------------
883     // print results 
884     
885     // tab-delimited
886     // <refName> <1-based pos> <refBase> <numberAlleles> <bases> <qualities> [mapQuals]
887     
888     const string TAB = "\t";
889     *m_out << referenceName       << TAB 
890            << position + 1        << TAB 
891            << referenceBase       << TAB 
892            << numberAlleles       << TAB 
893            << bases.str()         << TAB 
894            << baseQualities.str() << TAB
895            << mapQualities.str()  << endl;
896 }