]> git.donarmstrong.com Git - bamtools.git/blob - src/toolkit/bamtools_convert.cpp
Merge branch 'master' of http://github.com/pezmaster31/bamtools
[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 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 23 September 2010
7 // ---------------------------------------------------------------------------
8 // Converts between BAM and a number of other formats
9 // ***************************************************************************
10
11 #include <fstream>
12 #include <iostream>
13 #include <sstream>
14 #include <string>
15 #include <vector>
16 #include "bamtools_convert.h"
17 #include "bamtools_fasta.h"
18 #include "bamtools_options.h"
19 #include "bamtools_pileup_engine.h"
20 #include "bamtools_utilities.h"
21 #include "BGZF.h"
22 #include "BamMultiReader.h"
23 using namespace std;
24 using namespace BamTools;
25   
26 namespace BamTools { 
27   
28     // ---------------------------------------------
29     // ConvertTool constants
30   
31     // supported conversion format command-line names
32     static const string FORMAT_BED      = "bed";
33     static const string FORMAT_BEDGRAPH = "bedgraph";
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_WIGGLE   = "wig";
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     // flags
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         ~ConvertToolPrivate(void);
120     
121     // interface
122     public:
123         bool Run(void);
124         
125     // internal methods
126     private:
127         void PrintBed(const BamAlignment& a);
128         void PrintBedGraph(const BamAlignment& a);
129         void PrintFasta(const BamAlignment& a);
130         void PrintFastq(const BamAlignment& a);
131         void PrintJson(const BamAlignment& a);
132         void PrintSam(const BamAlignment& a);
133         void PrintWiggle(const BamAlignment& a);
134         
135         // special case - uses the PileupEngine
136         bool RunPileupConversion(BamMultiReader* reader);
137         
138     // data members
139     private: 
140         ConvertTool::ConvertSettings* m_settings;
141         RefVector m_references;
142         ostream m_out;
143 };
144
145 ConvertTool::ConvertToolPrivate::ConvertToolPrivate(ConvertTool::ConvertSettings* settings)
146     : m_settings(settings)
147     , m_out(cout.rdbuf()) // default output to cout
148 { }
149
150 ConvertTool::ConvertToolPrivate::~ConvertToolPrivate(void) { }
151
152 bool ConvertTool::ConvertToolPrivate::Run(void) {
153  
154     // ------------------------------------
155     // initialize conversion input/output
156         
157     // set to default input if none provided
158     if ( !m_settings->HasInput ) 
159         m_settings->InputFiles.push_back(Options::StandardIn());
160     
161     // open input files
162     BamMultiReader reader;
163     reader.Open(m_settings->InputFiles);
164     m_references = reader.GetReferenceData();
165
166     // set region if specified
167     BamRegion region;
168     if ( m_settings->HasRegion ) {
169         if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
170             if ( !reader.SetRegion(region) ) {
171                 cerr << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
172                 return false;
173             }
174         } else {
175             cerr << "Could not parse REGION: " << m_settings->Region << endl;
176             return false;
177         }
178     }
179         
180     // if output file given
181     ofstream outFile;
182     if ( m_settings->HasOutput ) {
183       
184         // open output file stream
185         outFile.open(m_settings->OutputFilename.c_str());
186         if ( !outFile ) {
187             cerr << "Could not open " << m_settings->OutputFilename << " for output" << endl; 
188             return false; 
189         }
190         
191         // set m_out to file's streambuf
192         m_out.rdbuf(outFile.rdbuf()); 
193     }
194     
195     // -------------------------------------
196     // do conversion based on format
197     
198      bool convertedOk = true;
199     
200     // pileup is special case
201     // conversion not done per alignment, like the other formats
202     if ( m_settings->Format == FORMAT_PILEUP )
203         convertedOk = RunPileupConversion(&reader);
204     
205     // all other formats
206     else {
207     
208         bool formatError = false;
209         
210         // set function pointer to proper conversion method
211         void (BamTools::ConvertTool::ConvertToolPrivate::*pFunction)(const BamAlignment&) = 0;
212         if      ( m_settings->Format == FORMAT_BED )      pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintBed;
213         else if ( m_settings->Format == FORMAT_BEDGRAPH ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintBedGraph;
214         else if ( m_settings->Format == FORMAT_FASTA )    pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFasta;
215         else if ( m_settings->Format == FORMAT_FASTQ )    pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFastq;
216         else if ( m_settings->Format == FORMAT_JSON )     pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintJson;
217         else if ( m_settings->Format == FORMAT_SAM )      pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintSam;
218         else if ( m_settings->Format == FORMAT_WIGGLE )   pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintWiggle;
219         else { 
220             cerr << "Unrecognized format: " << m_settings->Format << endl;
221             cerr << "Please see help|README (?) for details on supported formats " << endl;
222             formatError = true;
223             convertedOk = false;
224         }
225         
226         // if format selected ok
227         if ( !formatError ) {
228         
229             // if SAM format & not omitting header, print SAM header first
230             if ( (m_settings->Format == FORMAT_SAM) && !m_settings->IsOmittingSamHeader ) 
231                 m_out << reader.GetHeaderText();
232             
233             // iterate through file, doing conversion
234             BamAlignment a;
235             while ( reader.GetNextAlignment(a) ) 
236               (this->*pFunction)(a);
237             
238             // set flag for successful conversion
239             convertedOk = true;
240         }
241     }
242     
243     // ------------------------
244     // clean up & exit
245     
246     reader.Close();
247     if ( m_settings->HasOutput ) outFile.close();
248     return convertedOk;   
249 }
250
251 // ----------------------------------------------------------
252 // Conversion/output methods
253 // ----------------------------------------------------------
254
255 void ConvertTool::ConvertToolPrivate::PrintBed(const BamAlignment& a) { 
256   
257     // tab-delimited, 0-based half-open 
258     // (e.g. a 50-base read aligned to pos 10 could have BED coordinates (10, 60) instead of BAM coordinates (10, 59) )
259     // <chromName> <chromStart> <chromEnd> <readName> <score> <strand>
260
261     m_out << m_references.at(a.RefID).RefName << "\t"
262           << a.Position << "\t"
263           << a.GetEndPosition() + 1 << "\t"
264           << a.Name << "\t"
265           << a.MapQuality << "\t"
266           << (a.IsReverseStrand() ? "-" : "+") << endl;
267 }
268
269 void ConvertTool::ConvertToolPrivate::PrintBedGraph(const BamAlignment& a) { 
270     ; 
271 }
272
273 // print BamAlignment in FASTA format
274 // N.B. - uses QueryBases NOT AlignedBases
275 void ConvertTool::ConvertToolPrivate::PrintFasta(const BamAlignment& a) { 
276     
277     // >BamAlignment.Name
278     // BamAlignment.QueryBases (up to FASTA_LINE_MAX bases per line)
279     // ...
280     //
281     // N.B. - QueryBases are reverse-complemented if aligned to reverse strand
282   
283     // print header
284     m_out << "> " << a.Name << endl;
285     
286     // handle reverse strand alignment - bases 
287     string sequence = a.QueryBases;
288     if ( a.IsReverseStrand() )
289         Utilities::ReverseComplement(sequence);
290     
291     // if sequence fits on single line
292     if ( sequence.length() <= FASTA_LINE_MAX )
293         m_out << sequence << endl;
294     
295     // else split over multiple lines
296     else {
297       
298         size_t position = 0;
299         size_t seqLength = sequence.length(); // handle reverse strand alignment - bases & qualitiesth();
300         
301         // write subsequences to each line
302         while ( position < (seqLength - FASTA_LINE_MAX) ) {
303             m_out << sequence.substr(position, FASTA_LINE_MAX) << endl;
304             position += FASTA_LINE_MAX;
305         }
306         
307         // write final subsequence
308         m_out << sequence.substr(position) << endl;
309     }
310 }
311
312 // print BamAlignment in FASTQ format
313 // N.B. - uses QueryBases NOT AlignedBases
314 void ConvertTool::ConvertToolPrivate::PrintFastq(const BamAlignment& a) { 
315   
316     // @BamAlignment.Name
317     // BamAlignment.QueryBases
318     // +
319     // BamAlignment.Qualities
320     //
321     // N.B. - QueryBases are reverse-complemented (& Qualities reversed) if aligned to reverse strand .
322     //        Name is appended "/1" or "/2" if paired-end, to reflect which mate this entry is.
323   
324     // handle paired-end alignments
325     string name = a.Name;
326     if ( a.IsPaired() )
327         name.append( (a.IsFirstMate() ? "/1" : "/2") );
328   
329     // handle reverse strand alignment - bases & qualities
330     string qualities = a.Qualities;
331     string sequence  = a.QueryBases;
332     if ( a.IsReverseStrand() ) {
333         Utilities::Reverse(qualities);
334         Utilities::ReverseComplement(sequence);
335     }
336   
337     // write to output stream
338     m_out << "@" << name << endl
339           << sequence    << endl
340           << "+"         << endl
341           << qualities   << endl;
342 }
343
344 // print BamAlignment in JSON format
345 void ConvertTool::ConvertToolPrivate::PrintJson(const BamAlignment& a) {
346   
347     // write name & alignment flag
348     m_out << "{\"name\":\"" << a.Name << "\",\"alignmentFlag\":\"" << a.AlignmentFlag << "\",";
349     
350     // write reference name
351     if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) ) 
352         m_out << "\"reference\":\"" << m_references[a.RefID].RefName << "\",";
353     
354     // write position & map quality
355     m_out << "\"position\":" << a.Position+1 << ",\"mapQuality\":" << a.MapQuality << ",";
356     
357     // write CIGAR
358     const vector<CigarOp>& cigarData = a.CigarData;
359     if ( !cigarData.empty() ) {
360         m_out << "\"cigar\":[";
361         vector<CigarOp>::const_iterator cigarBegin = cigarData.begin();
362         vector<CigarOp>::const_iterator cigarIter = cigarBegin;
363         vector<CigarOp>::const_iterator cigarEnd  = cigarData.end();
364         for ( ; cigarIter != cigarEnd; ++cigarIter ) {
365             const CigarOp& op = (*cigarIter);
366             if (cigarIter != cigarBegin) m_out << ",";
367             m_out << "\"" << op.Length << op.Type << "\"";
368         }
369         m_out << "],";
370     }
371     
372     // write mate reference name, mate position, & insert size
373     if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
374         m_out << "\"mate\":{"
375               << "\"reference\":\"" << m_references[a.MateRefID].RefName << "\","
376               << "\"position\":" << a.MatePosition+1
377               << ",\"insertSize\":" << a.InsertSize << "},";
378     }
379     
380     // write sequence
381     if ( !a.QueryBases.empty() ) 
382         m_out << "\"queryBases\":\"" << a.QueryBases << "\",";
383     
384     // write qualities
385     if ( !a.Qualities.empty() ) {
386         string::const_iterator s = a.Qualities.begin();
387         m_out << "\"qualities\":[" << static_cast<short>(*s) - 33;
388         ++s;
389         for (; s != a.Qualities.end(); ++s) {
390             m_out << "," << static_cast<short>(*s) - 33;
391         }
392         m_out << "],";
393     }
394     
395     // write tag data
396     const char* tagData = a.TagData.c_str();
397     const size_t tagDataLength = a.TagData.length();
398     size_t index = 0;
399     if (index < tagDataLength) {
400
401         m_out << "\"tags\":{";
402         
403         while ( index < tagDataLength ) {
404
405             if (index > 0)
406                 m_out << ",";
407             
408             // write tag name
409             m_out << "\"" << a.TagData.substr(index, 2) << "\":";
410             index += 2;
411             
412             // get data type
413             char type = a.TagData.at(index);
414             ++index;
415             
416             switch (type) {
417                 case('A') : 
418                     m_out << "\"" << tagData[index] << "\"";
419                     ++index; 
420                     break;
421                 
422                 case('C') : 
423                     m_out << (int)tagData[index]; 
424                     ++index; 
425                     break;
426                 
427                 case('c') : 
428                     m_out << (int)tagData[index];
429                     ++index; 
430                     break;
431                 
432                 case('S') : 
433                     m_out << BgzfData::UnpackUnsignedShort(&tagData[index]); 
434                     index += 2; 
435                     break;
436                     
437                 case('s') : 
438                     m_out << BgzfData::UnpackSignedShort(&tagData[index]);
439                     index += 2; 
440                     break;
441                 
442                 case('I') : 
443                     m_out << BgzfData::UnpackUnsignedInt(&tagData[index]);
444                     index += 4; 
445                     break;
446                 
447                 case('i') : 
448                     m_out << BgzfData::UnpackSignedInt(&tagData[index]);
449                     index += 4; 
450                     break;
451                 
452                 case('f') : 
453                     m_out << BgzfData::UnpackFloat(&tagData[index]);
454                     index += 4; 
455                     break;
456                 
457                 case('d') : 
458                     m_out << BgzfData::UnpackDouble(&tagData[index]);
459                     index += 8; 
460                     break;
461                 
462                 case('Z') :
463                 case('H') : 
464                     m_out << "\""; 
465                     while (tagData[index]) {
466                         m_out << tagData[index];
467                         ++index;
468                     }
469                     m_out << "\""; 
470                     ++index; 
471                     break;      
472             }
473             
474             if ( tagData[index] == '\0') 
475                 break;
476         }
477
478         m_out << "}";
479     }
480
481     m_out << "}" << endl;
482 }
483
484 // print BamAlignment in SAM format
485 void ConvertTool::ConvertToolPrivate::PrintSam(const BamAlignment& a) {
486   
487     // tab-delimited
488     // <QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> [ <TAG>:<VTYPE>:<VALUE> [...] ]
489   
490     // write name & alignment flag
491     m_out << a.Name << "\t" << a.AlignmentFlag << "\t";
492     
493     // write reference name
494     if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) ) 
495         m_out << m_references[a.RefID].RefName << "\t";
496     else 
497         m_out << "*\t";
498     
499     // write position & map quality
500     m_out << a.Position+1 << "\t" << a.MapQuality << "\t";
501     
502     // write CIGAR
503     const vector<CigarOp>& cigarData = a.CigarData;
504     if ( cigarData.empty() ) m_out << "*\t";
505     else {
506         vector<CigarOp>::const_iterator cigarIter = cigarData.begin();
507         vector<CigarOp>::const_iterator cigarEnd  = cigarData.end();
508         for ( ; cigarIter != cigarEnd; ++cigarIter ) {
509             const CigarOp& op = (*cigarIter);
510             m_out << op.Length << op.Type;
511         }
512         m_out << "\t";
513     }
514     
515     // write mate reference name, mate position, & insert size
516     if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
517         if ( a.MateRefID == a.RefID ) m_out << "=\t";
518         else m_out << m_references[a.MateRefID].RefName << "\t";
519         m_out << a.MatePosition+1 << "\t" << a.InsertSize << "\t";
520     } 
521     else m_out << "*\t0\t0\t";
522     
523     // write sequence
524     if ( a.QueryBases.empty() ) m_out << "*\t";
525     else m_out << a.QueryBases << "\t";
526     
527     // write qualities
528     if ( a.Qualities.empty() ) m_out << "*";
529     else m_out << a.Qualities;
530     
531     // write tag data
532     const char* tagData = a.TagData.c_str();
533     const size_t tagDataLength = a.TagData.length();
534     
535     size_t index = 0;
536     while ( index < tagDataLength ) {
537
538         // write tag name   
539         string tagName = a.TagData.substr(index, 2);
540         m_out << "\t" << tagName << ":";
541         index += 2;
542         
543         // get data type
544         char type = a.TagData.at(index);
545         ++index;
546         switch (type) {
547             case('A') : 
548                 m_out << "A:" << tagData[index]; 
549                 ++index; 
550                 break;
551             
552             case('C') : 
553                 m_out << "i:" << (int)tagData[index]; 
554                 ++index; 
555                 break;
556             
557             case('c') : 
558                 m_out << "i:" << (int)tagData[index];
559                 ++index; 
560                 break;
561             
562             case('S') : 
563                 m_out << "i:" << BgzfData::UnpackUnsignedShort(&tagData[index]);
564                 index += 2; 
565                 break;
566                 
567             case('s') : 
568                 m_out << "i:" << BgzfData::UnpackSignedShort(&tagData[index]);
569                 index += 2; 
570                 break;
571             
572             case('I') :
573                 m_out << "i:" << BgzfData::UnpackUnsignedInt(&tagData[index]);
574                 index += 4; 
575                 break;
576             
577             case('i') : 
578                 m_out << "i:" << BgzfData::UnpackSignedInt(&tagData[index]);
579                 index += 4; 
580                 break;
581             
582             case('f') : 
583                 m_out << "f:" << BgzfData::UnpackFloat(&tagData[index]);
584                 index += 4; 
585                 break;
586             
587             case('d') : 
588                 m_out << "d:" << BgzfData::UnpackDouble(&tagData[index]);
589                 index += 8; 
590                 break;
591             
592             case('Z') :
593             case('H') : 
594                 m_out << type << ":";
595                 while (tagData[index]) {
596                     m_out << tagData[index];
597                     ++index;
598                 }
599                 ++index; 
600                 break;      
601         }
602
603         if ( tagData[index] == '\0') 
604             break;
605     }
606
607     m_out << endl;
608 }
609
610 void ConvertTool::ConvertToolPrivate::PrintWiggle(const BamAlignment& a) { 
611     ; 
612 }
613
614 bool ConvertTool::ConvertToolPrivate::RunPileupConversion(BamMultiReader* reader) {
615   
616     // check for valid BamMultiReader
617     if ( reader == 0 ) return false;
618   
619     // set up our pileup format 'visitor'
620     ConvertPileupFormatVisitor* v = new ConvertPileupFormatVisitor(m_references, 
621                                                                    m_settings->FastaFilename,
622                                                                    m_settings->IsPrintingPileupMapQualities, 
623                                                                    &m_out);
624
625     // set up PileupEngine
626     PileupEngine pileup;
627     pileup.AddVisitor(v);
628     
629     // iterate through data
630     BamAlignment al;
631     while ( reader->GetNextAlignment(al) )
632         pileup.AddAlignment(al);
633     pileup.Flush();
634     
635     // clean up
636     delete v;
637     v = 0;
638     
639     // return success
640     return true;
641 }       
642
643 // ---------------------------------------------
644 // ConvertTool implementation
645
646 ConvertTool::ConvertTool(void)
647     : AbstractTool()
648     , m_settings(new ConvertSettings)
649     , m_impl(0)
650 {
651     // set program details
652     Options::SetProgramInfo("bamtools convert", "converts BAM to a number of other formats", "-format <FORMAT> [-in <filename> -in <filename> ...] [-out <filename>] [other options]");
653     
654     // set up options 
655     OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
656     Options::AddValueOption("-in",     "BAM filename", "the input BAM file(s)", "", m_settings->HasInput,   m_settings->InputFiles,     IO_Opts, Options::StandardIn());
657     Options::AddValueOption("-out",    "BAM filename", "the output BAM file",   "", m_settings->HasOutput,  m_settings->OutputFilename, IO_Opts, Options::StandardOut());
658     Options::AddValueOption("-format", "FORMAT", "the output file format - see README for recognized formats", "", m_settings->HasFormat, m_settings->Format, IO_Opts);
659    
660     OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
661     Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance, and is read automatically if it exists as <filename>.bai. See \'bamtools help index\' for more  details on creating one", "", m_settings->HasRegion, m_settings->Region, FilterOpts);
662     
663     OptionGroup* PileupOpts = Options::CreateOptionGroup("Pileup Options");
664     Options::AddValueOption("-fasta", "FASTA filename", "FASTA reference file", "", m_settings->HasFastaFilename, m_settings->FastaFilename, PileupOpts, "");
665     Options::AddOption("-mapqual", "print the mapping qualities", m_settings->IsPrintingPileupMapQualities, PileupOpts);
666     
667     OptionGroup* SamOpts = Options::CreateOptionGroup("SAM Options");
668     Options::AddOption("-noheader", "omit the SAM header from output", m_settings->IsOmittingSamHeader, SamOpts);
669 }
670
671 ConvertTool::~ConvertTool(void) {
672     delete m_settings;
673     m_settings = 0;
674     
675     delete m_impl;
676     m_impl = 0;
677 }
678
679 int ConvertTool::Help(void) {
680     Options::DisplayHelp();
681     return 0;
682 }
683
684 int ConvertTool::Run(int argc, char* argv[]) {
685   
686     // parse command line arguments
687     Options::Parse(argc, argv, 1);
688     
689     // run internal ConvertTool implementation, return success/fail
690     m_impl = new ConvertToolPrivate(m_settings);
691     
692     if ( m_impl->Run() ) 
693         return 0;
694     else 
695         return 1;
696 }
697
698 // ---------------------------------------------
699 // ConvertPileupFormatVisitor implementation
700
701 ConvertPileupFormatVisitor::ConvertPileupFormatVisitor(const RefVector& references, 
702                                                        const string& fastaFilename,
703                                                        const bool isPrintingMapQualities,
704                                                        ostream* out)
705     : PileupVisitor()
706     , m_hasFasta(false)
707     , m_isPrintingMapQualities(isPrintingMapQualities)
708     , m_out(out)
709     , m_references(references)
710
711     // set up Fasta reader if file is provided
712     if ( !fastaFilename.empty() ) {
713       
714         // check for FASTA index
715         string indexFilename = "";
716         if ( Utilities::FileExists(fastaFilename + ".fai") ) 
717             indexFilename = fastaFilename + ".fai";
718       
719         // open FASTA file
720         if ( m_fasta.Open(fastaFilename, indexFilename) ) 
721             m_hasFasta = true;
722     }
723 }
724
725 ConvertPileupFormatVisitor::~ConvertPileupFormatVisitor(void) { 
726     // be sure to close Fasta reader
727     if ( m_hasFasta ) {
728         m_fasta.Close();
729         m_hasFasta = false;
730     }
731 }
732
733 void ConvertPileupFormatVisitor::Visit(const PileupPosition& pileupData ) {
734   
735     // skip if no alignments at this position
736     if ( pileupData.PileupAlignments.empty() ) return;
737   
738     // retrieve reference name
739     const string& referenceName = m_references[pileupData.RefId].RefName;
740     const int& position   = pileupData.Position;
741     
742     // retrieve reference base from FASTA file, if one provided; otherwise default to 'N'
743     char referenceBase('N');
744     if ( m_hasFasta && (pileupData.Position < m_references[pileupData.RefId].RefLength) ) {
745         if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position, referenceBase ) ) {
746             cerr << "Pileup error : Could not read reference base from FASTA file" << endl;
747             return;
748         }
749     }
750     
751     // get count of alleles at this position
752     const int numberAlleles = pileupData.PileupAlignments.size();
753     
754     // -----------------------------------------------------------
755     // build strings based on alleles at this positionInAlignment
756     
757     stringstream bases("");
758     stringstream baseQualities("");
759     stringstream mapQualities("");
760     
761     // iterate over alignments at this pileup position
762     vector<PileupAlignment>::const_iterator pileupIter = pileupData.PileupAlignments.begin();
763     vector<PileupAlignment>::const_iterator pileupEnd  = pileupData.PileupAlignments.end();
764     for ( ; pileupIter != pileupEnd; ++pileupIter ) {
765         const PileupAlignment pa = (*pileupIter);
766         const BamAlignment& ba = pa.Alignment;
767         
768         // if beginning of read segment
769         if ( pa.IsSegmentBegin )
770             bases << '^' << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
771         
772         // if current base is not a DELETION
773         if ( !pa.IsCurrentDeletion ) {
774           
775             // get base at current position
776             char base = ba.QueryBases.at(pa.PositionInAlignment);
777             
778             // if base matches reference
779             if ( base == '=' || 
780                  toupper(base) == toupper(referenceBase) ||
781                  tolower(base) == tolower(referenceBase) ) 
782             {
783                 base = (ba.IsReverseStrand() ? ',' : '.' );
784             }
785             
786             // mismatches reference
787             else base = (ba.IsReverseStrand() ? tolower(base) : toupper(base) );
788             
789             // store base
790             bases << base;
791           
792             // if next position contains insertion
793             if ( pa.IsNextInsertion ) {
794                 bases << '+' << pa.InsertionLength;
795                 for (int i = 1; i <= pa.InsertionLength; ++i) {
796                     char insertedBase = (char)ba.QueryBases.at(pa.PositionInAlignment + i);
797                     bases << (ba.IsReverseStrand() ? (char)tolower(insertedBase) : (char)toupper(insertedBase) );
798                 }
799             }
800             
801             // if next position contains DELETION
802             else if ( pa.IsNextDeletion ) {
803                 bases << '-' << pa.DeletionLength;
804                 for (int i = 1; i <= pa.DeletionLength; ++i) {
805                     char deletedBase('N');
806                     if ( m_hasFasta && (pileupData.Position+i < m_references[pileupData.RefId].RefLength) ) {
807                         if ( !m_fasta.GetBase(pileupData.RefId, pileupData.Position+i, deletedBase ) ) {
808                             cerr << "Pileup error : Could not read reference base from FASTA file" << endl;
809                             return;
810                         }
811                     }
812                     bases << (ba.IsReverseStrand() ? (char)tolower(deletedBase) : (char)toupper(deletedBase) );
813                 }
814             }
815         }
816         
817         // otherwise, DELETION
818         else bases << '*';
819         
820         // if end of read segment
821         if ( pa.IsSegmentEnd ) bases << '$';
822         
823         // store current base quality
824         baseQualities << ba.Qualities.at(pa.PositionInAlignment);
825         
826         // save alignment map quality if desired
827         if ( m_isPrintingMapQualities )
828             mapQualities << ( ((int)ba.MapQuality > 93) ? (char)126 : (char)((int)ba.MapQuality+33) );
829     }
830     
831     // ----------------------
832     // print results 
833     
834     // tab-delimited
835     // <refName> <1-based pos> <refBase> <numberAlleles> <bases> <qualities> [mapQuals]
836     
837     const string TAB = "\t";
838     *m_out << referenceName       << TAB 
839            << position + 1        << TAB 
840            << referenceBase       << TAB 
841            << numberAlleles       << TAB 
842            << bases.str()         << TAB 
843            << baseQualities.str() << TAB
844            << mapQualities.str()  << endl;
845 }