]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.cpp
Merge remote-tracking branch 'mothur/master'
[mothur.git] / makecontigscommand.cpp
1 //
2 //  makecontigscommand.cpp
3 //  Mothur
4 //
5 //  Created by Sarah Westcott on 5/15/12.
6 //  Copyright (c) 2012 Schloss Lab. All rights reserved.
7 //
8
9 #include "makecontigscommand.h"
10
11 //**********************************************************************************************************************
12 vector<string> MakeContigsCommand::setParameters(){     
13         try {
14                 CommandParameter pfastq("ffastq", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "fastqGroup","fasta-qfile",false,false,true); parameters.push_back(pfastq);
15         CommandParameter prfastq("rfastq", "InputTypes", "", "", "none", "none", "fastqGroup","fasta-qfile",false,false,true); parameters.push_back(prfastq);
16         CommandParameter pfasta("ffasta", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "fastaGroup","fasta",false,false,true); parameters.push_back(pfasta);
17         CommandParameter prfasta("rfasta", "InputTypes", "", "", "none", "none", "none","fastaGroup",false,false,true); parameters.push_back(prfasta);
18         CommandParameter pfqual("fqfile", "InputTypes", "", "", "none", "none", "qfileGroup","",false,false,true); parameters.push_back(pfqual);
19         CommandParameter prqual("rqfile", "InputTypes", "", "", "none", "none", "qfileGroup","",false,false,true); parameters.push_back(prqual);
20         CommandParameter pfile("file", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "none","fasta-qfile",false,false,true); parameters.push_back(pfile);
21         CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none","group",false,false,true); parameters.push_back(poligos);
22                 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(ppdiffs);
23                 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(pbdiffs);
24 //        CommandParameter pldiffs("ldiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pldiffs);
25 //              CommandParameter psdiffs("sdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(psdiffs);
26         CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(ptdiffs);
27
28         CommandParameter palign("align", "Multiple", "needleman-gotoh", "needleman", "", "", "","",false,false); parameters.push_back(palign);
29         CommandParameter pallfiles("allfiles", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pallfiles);
30                 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "","",false,false); parameters.push_back(pmatch);
31                 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "","",false,false); parameters.push_back(pmismatch);
32                 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "","",false,false); parameters.push_back(pgapopen);
33                 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "","",false,false); parameters.push_back(pgapextend);
34         CommandParameter pthreshold("insert", "Number", "", "25", "", "", "","",false,false); parameters.push_back(pthreshold);
35         CommandParameter pdeltaq("deltaq", "Number", "", "6", "", "", "","",false,false); parameters.push_back(pdeltaq);
36                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
37         CommandParameter pformat("format", "Multiple", "sanger-illumina-solexa-illumina1.8+", "illumina1.8+", "", "", "","",false,false,true); parameters.push_back(pformat);
38                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
39                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
40                 
41                 vector<string> myArray;
42                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "MakeContigsCommand", "setParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 string MakeContigsCommand::getHelpString(){     
52         try {
53                 string helpString = "";
54                 helpString += "The make.contigs command reads a file, forward fastq file and a reverse fastq file or forward fasta and reverse fasta files and outputs new fasta.  It will also provide new quality files if the fastq or file parameter is used.\n";
55         helpString += "If an oligos file is provided barcodes and primers will be trimmed, and a group file will be created.\n";
56                 helpString += "The make.contigs command parameters are file, ffastq, rfastq, ffasta, rfasta, fqfile, rqfile, oligos, format, tdiffs, bdiffs, pdiffs, align, match, mismatch, gapopen, gapextend, insert, deltaq, allfiles and processors.\n";
57                 helpString += "The ffastq and rfastq, file, or ffasta and rfasta parameters are required.\n";
58         helpString += "The file parameter is 2 column file containing the forward fastq files in the first column and their matching reverse fastq files in the second column.  Mothur will process each pair and create a combined fasta and report file with all the sequences.\n";
59         helpString += "The ffastq and rfastq parameters are used to provide a forward fastq and reverse fastq file to process.  If you provide one, you must provide the other.\n";
60         helpString += "The ffasta and rfasta parameters are used to provide a forward fasta and reverse fasta file to process.  If you provide one, you must provide the other.\n";
61         helpString += "The fqfile and rqfile parameters are used to provide a forward quality and reverse quality files to process with the ffasta and rfasta parameters.  If you provide one, you must provide the other.\n";
62                 helpString += "The format parameter is used to indicate whether your sequences are sanger, solexa, illumina1.8+ or illumina, default=illumina1.8+.\n";
63         helpString += "The align parameter allows you to specify the alignment method to use.  Your options are: gotoh and needleman. The default is needleman.\n";
64         helpString += "The tdiffs parameter is used to specify the total number of differences allowed in the sequence. The default is pdiffs + bdiffs + sdiffs + ldiffs.\n";
65                 helpString += "The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n";
66                 helpString += "The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n";
67         //helpString += "The ldiffs parameter is used to specify the number of differences allowed in the linker. The default is 0.\n";
68                 //helpString += "The sdiffs parameter is used to specify the number of differences allowed in the spacer. The default is 0.\n";
69                 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
70                 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n";
71         helpString += "The deltaq parameter allows you to specify the delta allowed between quality scores of a mismatched base.  For example in the overlap, if deltaq=5 and in the alignment seqA, pos 200 has a quality score of 30 and the same position in seqB has a quality score of 20, you take the base from seqA (30-20 >= 5).  If the quality score in seqB is 28 then the base in the consensus will be an N (30-28<5) The default is 6.\n";
72                 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
73                 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n";
74         helpString += "The insert parameter allows you to set a quality scores threshold. In the case where we are trying to decide whether to keep a base or remove it because the base is compared to a gap in the other fragment, if the base has a quality score below the threshold we eliminate it. Default=25.\n";
75         helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
76         helpString += "The allfiles parameter will create separate group and fasta file for each grouping. The default is F.\n";
77         helpString += "The make.contigs command should be in the following format: \n";
78                 helpString += "make.contigs(ffastq=yourForwardFastqFile, rfastq=yourReverseFastqFile, align=yourAlignmentMethod) \n";
79                 helpString += "Note: No spaces between parameter labels (i.e. ffastq), '=' and parameters (i.e.yourForwardFastqFile).\n";
80                 return helpString;
81         }
82         catch(exception& e) {
83                 m->errorOut(e, "MakeContigsCommand", "getHelpString");
84                 exit(1);
85         }
86 }
87 //**********************************************************************************************************************
88 string MakeContigsCommand::getOutputPattern(string type) {
89     try {
90         string pattern = "";
91         
92         if (type == "fasta") {  pattern = "[filename],[tag],contigs.fasta"; } 
93         else if (type == "group") {  pattern = "[filename],[tag],contigs.groups"; }
94         else if (type == "report") {  pattern = "[filename],[tag],contigs.report"; }
95         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
96         
97         return pattern;
98     }
99     catch(exception& e) {
100         m->errorOut(e, "MakeContigsCommand", "getOutputPattern");
101         exit(1);
102     }
103 }
104 //**********************************************************************************************************************
105 MakeContigsCommand::MakeContigsCommand(){       
106         try {
107                 abort = true; calledHelp = true; 
108                 setParameters();
109                 vector<string> tempOutNames;
110                 outputTypes["fasta"] = tempOutNames;
111         outputTypes["group"] = tempOutNames;
112         outputTypes["report"] = tempOutNames;
113         }
114         catch(exception& e) {
115                 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
116                 exit(1);
117         }
118 }
119 //**********************************************************************************************************************
120 MakeContigsCommand::MakeContigsCommand(string option)  {
121         try {
122                 abort = false; calledHelp = false;   
123         
124                 //allow user to run help
125                 if(option == "help") { help(); abort = true; calledHelp = true; }
126                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
127                 
128                 else {
129                         vector<string> myArray = setParameters();
130                         
131                         OptionParser parser(option);
132                         map<string, string> parameters = parser.getParameters(); 
133                         
134                         ValidParameters validParameter("pairwise.seqs");
135                         map<string, string>::iterator it;
136                         
137                         //check to make sure all parameters are valid for command
138                         for (it = parameters.begin(); it != parameters.end(); it++) { 
139                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
140                         }
141                         
142                         //initialize outputTypes
143                         vector<string> tempOutNames;
144                         outputTypes["fasta"] = tempOutNames;
145             outputTypes["report"] = tempOutNames;
146             outputTypes["group"] = tempOutNames;
147                         
148             
149                         //if the user changes the input directory command factory will send this info to us in the output parameter 
150                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
151                         if (inputDir == "not found"){   inputDir = "";          }
152                         else { 
153                                 string path;
154                 it = parameters.find("ffastq");
155                                 //user has given a template file
156                                 if(it != parameters.end()){ 
157                                         path = m->hasPath(it->second);
158                                         //if the user has not given a path then, add inputdir. else leave path alone.
159                                         if (path == "") {       parameters["ffastq"] = inputDir + it->second;           }
160                                 }
161                 
162                 it = parameters.find("rfastq");
163                                 //user has given a template file
164                                 if(it != parameters.end()){ 
165                                         path = m->hasPath(it->second);
166                                         //if the user has not given a path then, add inputdir. else leave path alone.
167                                         if (path == "") {       parameters["rfastq"] = inputDir + it->second;           }
168                                 }
169                 
170                 it = parameters.find("ffasta");
171                                 //user has given a template file
172                                 if(it != parameters.end()){ 
173                                         path = m->hasPath(it->second);
174                                         //if the user has not given a path then, add inputdir. else leave path alone.
175                                         if (path == "") {       parameters["ffasta"] = inputDir + it->second;           }
176                                 }
177                 
178                 it = parameters.find("rfasta");
179                                 //user has given a template file
180                                 if(it != parameters.end()){ 
181                                         path = m->hasPath(it->second);
182                                         //if the user has not given a path then, add inputdir. else leave path alone.
183                                         if (path == "") {       parameters["rfasta"] = inputDir + it->second;           }
184                                 }
185                 
186                 it = parameters.find("fqfile");
187                                 //user has given a template file
188                                 if(it != parameters.end()){ 
189                                         path = m->hasPath(it->second);
190                                         //if the user has not given a path then, add inputdir. else leave path alone.
191                                         if (path == "") {       parameters["fqfile"] = inputDir + it->second;           }
192                                 }
193                 
194                 it = parameters.find("rqfile");
195                                 //user has given a template file
196                                 if(it != parameters.end()){ 
197                                         path = m->hasPath(it->second);
198                                         //if the user has not given a path then, add inputdir. else leave path alone.
199                                         if (path == "") {       parameters["rqfile"] = inputDir + it->second;           }
200                                 }
201                 
202                 it = parameters.find("file");
203                                 //user has given a template file
204                                 if(it != parameters.end()){ 
205                                         path = m->hasPath(it->second);
206                                         //if the user has not given a path then, add inputdir. else leave path alone.
207                                         if (path == "") {       parameters["file"] = inputDir + it->second;             }
208                                 }
209                 
210                 it = parameters.find("oligos");
211                                 //user has given a template file
212                                 if(it != parameters.end()){ 
213                                         path = m->hasPath(it->second);
214                                         //if the user has not given a path then, add inputdir. else leave path alone.
215                                         if (path == "") {       parameters["oligos"] = inputDir + it->second;           }
216                                 }
217             }
218             
219             ffastqfile = validParameter.validFile(parameters, "ffastq", true);
220                         if (ffastqfile == "not open") {  abort = true; }        
221                         else if (ffastqfile == "not found") { ffastqfile = ""; }
222                         
223                         rfastqfile = validParameter.validFile(parameters, "rfastq", true);
224                         if (rfastqfile == "not open") {  abort = true; }        
225                         else if (rfastqfile == "not found") { rfastqfile = "";  }
226             
227             ffastafile = validParameter.validFile(parameters, "ffasta", true);
228                         if (ffastafile == "not open") {  abort = true; }        
229                         else if (ffastafile == "not found") { ffastafile = ""; }
230                         
231                         rfastafile = validParameter.validFile(parameters, "rfasta", true);
232                         if (rfastafile == "not open") {  abort = true; }        
233                         else if (rfastafile == "not found") { rfastafile = "";  }
234             
235             fqualfile = validParameter.validFile(parameters, "fqfile", true);
236                         if (fqualfile == "not open") {  abort = true; } 
237                         else if (fqualfile == "not found") { fqualfile = ""; }
238                         
239                         rqualfile = validParameter.validFile(parameters, "rqfile", true);
240                         if (rqualfile == "not open") {  abort = true; } 
241                         else if (rqualfile == "not found") { rqualfile = "";  }
242             
243             file = validParameter.validFile(parameters, "file", true);
244                         if (file == "not open") {  abort = true; }      
245                         else if (file == "not found") { file = "";  }
246             
247             //provide at least
248             if ((file == "") && (ffastafile == "") && (ffastqfile == "")) { abort = true; m->mothurOut("[ERROR]: The file, ffastq and rfastq or ffasta and rfasta parameters are required.\n"); }
249             if ((file != "") && ((ffastafile != "") || (ffastqfile != ""))) { abort = true; m->mothurOut("[ERROR]: The file, ffastq and rfastq or ffasta and rfasta parameters are required.\n"); }
250             if ((ffastqfile != "") && (rfastqfile == "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the ffastq, you must provide a rfastq file.\n"); }
251             if ((ffastqfile == "") && (rfastqfile != "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the rfastq, you must provide a ffastq file.\n"); }
252             if ((ffastafile != "") && (rfastafile == "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the ffasta, you must provide a rfasta file.\n"); }
253             if ((ffastafile == "") && (rfastafile != "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the rfasta, you must provide a ffasta file.\n"); }
254             if ((fqualfile != "") && (rqualfile == "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the fqfile, you must provide a rqfile file.\n"); }
255             if ((fqualfile == "") && (rqualfile != "")) {  abort = true; m->mothurOut("[ERROR]: If you provide use the rqfile, you must provide a fqfile file.\n"); }
256             if (((fqualfile != "") || (rqualfile != "")) && ((ffastafile == "") || (rfastafile == ""))) {
257                 abort = true; m->mothurOut("[ERROR]: If you provide use the rqfile or fqfile file, you must provide the ffasta and rfasta parameters.\n");
258             }
259             
260             oligosfile = validParameter.validFile(parameters, "oligos", true);
261                         if (oligosfile == "not found")      {   oligosfile = "";        }
262                         else if(oligosfile == "not open")   {   abort = true;       } 
263                         else {   m->setOligosFile(oligosfile);          }
264             
265             //if the user changes the output directory command factory will send this info to us in the output parameter 
266                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
267                  outputDir = ""; 
268             }
269                         
270
271                         //check for optional parameter and set defaults
272                         // ...at some point should added some additional type checking...
273                         string temp;
274                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
275                         m->mothurConvert(temp, match);  
276                         
277                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
278                         m->mothurConvert(temp, misMatch);  
279             if (misMatch > 0) { m->mothurOut("[ERROR]: mismatch must be negative.\n"); abort=true; }
280                         
281                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
282                         m->mothurConvert(temp, gapOpen);  
283             if (gapOpen > 0) { m->mothurOut("[ERROR]: gapopen must be negative.\n"); abort=true; }
284                         
285                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
286                         m->mothurConvert(temp, gapExtend); 
287             if (gapExtend > 0) { m->mothurOut("[ERROR]: gapextend must be negative.\n"); abort=true; }
288                         
289             temp = validParameter.validFile(parameters, "insert", false);       if (temp == "not found"){       temp = "25";                    }
290                         m->mothurConvert(temp, insert); 
291             if ((insert < 0) || (insert > 40)) { m->mothurOut("[ERROR]: insert must be between 0 and 40.\n"); abort=true; }
292
293             temp = validParameter.validFile(parameters, "deltaq", false);       if (temp == "not found"){       temp = "6";                     }
294                         m->mothurConvert(temp, deltaq);
295             
296                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
297                         m->setProcessors(temp);
298                         m->mothurConvert(temp, processors);
299             
300             temp = validParameter.validFile(parameters, "bdiffs", false);               if (temp == "not found") { temp = "0"; }
301                         m->mothurConvert(temp, bdiffs);
302                         
303                         temp = validParameter.validFile(parameters, "pdiffs", false);           if (temp == "not found") { temp = "0"; }
304                         m->mothurConvert(temp, pdiffs);
305             
306   //          temp = validParameter.validFile(parameters, "ldiffs", false);             if (temp == "not found") { temp = "0"; }
307 //                      m->mothurConvert(temp, ldiffs);
308             ldiffs = 0;
309             
310  //           temp = validParameter.validFile(parameters, "sdiffs", false);             if (temp == "not found") { temp = "0"; }
311  //           m->mothurConvert(temp, sdiffs);
312             sdiffs = 0;
313                         
314                         temp = validParameter.validFile(parameters, "tdiffs", false);           if (temp == "not found") { int tempTotal = pdiffs + bdiffs;  temp = toString(tempTotal); }
315                         m->mothurConvert(temp, tdiffs);
316                         
317                         if(tdiffs == 0){        tdiffs = bdiffs + pdiffs;       }  //+ ldiffs + sdiffs;
318
319             temp = validParameter.validFile(parameters, "allfiles", false);             if (temp == "not found") { temp = "F"; }
320                         allFiles = m->isTrue(temp);
321                         
322                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }
323                         if ((align != "needleman") && (align != "gotoh")) { m->mothurOut(align + " is not a valid alignment method. Options are needleman or gotoh. I will use needleman."); m->mothurOutEndLine(); align = "needleman"; }
324             
325             format = validParameter.validFile(parameters, "format", false);             if (format == "not found"){     format = "illumina1.8+";        }
326             
327             if ((format != "sanger") && (format != "illumina") && (format != "illumina1.8+") && (format != "solexa"))  { 
328                                 m->mothurOut(format + " is not a valid format. Your format choices are sanger, solexa, illumina1.8+ and illumina, aborting." ); m->mothurOutEndLine();
329                                 abort=true;
330                         }
331             
332             //fill convert table - goes from solexa to sanger. Used fq_all2std.pl as a reference.
333             for (int i = -64; i < 65; i++) { 
334                 char temp = (char) ((int)(33 + 10*log(1+pow(10,(i/10.0)))/log(10)+0.499));
335                 convertTable.push_back(temp);
336             }
337         }
338                 
339         }
340         catch(exception& e) {
341                 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
342                 exit(1);
343         }
344 }
345 //**********************************************************************************************************************
346 int MakeContigsCommand::execute(){
347         try {
348                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
349         
350         //read ffastq and rfastq files creating fasta and qual files.
351         //this function will create a forward and reverse, fasta and qual files for each processor.
352         //files has an entry for each processor. files[i][0] = forwardFasta, files[i][1] = forwardQual, files[i][2] = reverseFasta, files[i][3] = reverseQual.  filesToProcess is for each filepair in the file parameter file.  for ffastq and rfastq this will be size 1.
353         unsigned long int numReads = 0;
354         int start = time(NULL);
355         longestBase = 1000;
356         m->mothurOut("Reading fastq data...\n"); 
357         vector < vector< vector<string> > > filesToProcess = preProcessData(numReads);
358         m->mothurOut("Done.\n");
359        
360         if (m->control_pressed) { return 0; }
361         
362         map<string, string> cvars;
363         string compOutputDir = outputDir;
364         if (outputDir == "") { compOutputDir = m->hasPath(file); }
365         cvars["[filename]"] = compOutputDir + m->getRootName(m->getSimpleName(file));
366         cvars["[tag]"] = "";
367         string compositeGroupFile = getOutputFileName("group",cvars);
368         cvars["[tag]"] = "trim";
369         string compositeFastaFile = getOutputFileName("fasta",cvars);
370         cvars["[tag]"] = "scrap";
371         string compositeScrapFastaFile = getOutputFileName("fasta",cvars);
372         cvars["[tag]"] = "";
373         string compositeMisMatchFile = getOutputFileName("report",cvars);
374         
375         if (filesToProcess.size() > 1) { //clear files for append below
376             ofstream outCTFasta, outCTQual, outCSFasta, outCSQual, outCMisMatch;
377             m->openOutputFile(compositeFastaFile, outCTFasta); outCTFasta.close();
378             m->openOutputFile(compositeScrapFastaFile, outCSFasta); outCSFasta.close();
379             m->openOutputFile(compositeMisMatchFile, outCMisMatch); outCMisMatch.close();
380             outputNames.push_back(compositeFastaFile); outputTypes["fasta"].push_back(compositeFastaFile);
381             outputNames.push_back(compositeMisMatchFile); outputTypes["report"].push_back(compositeMisMatchFile);
382             outputNames.push_back(compositeScrapFastaFile); outputTypes["fasta"].push_back(compositeScrapFastaFile);
383         }
384         
385         for (int l = 0; l < filesToProcess.size(); l++) {
386             
387             m->mothurOut("\n>>>>>\tProcessing " + filesToProcess[l][0][0] + " (file " + toString(l+1) + " of " + toString(filesToProcess.size()) + ")\t<<<<<\n");
388             
389             vector<vector<string> > fastaFileNames;
390             createGroup = false;
391             string outputGroupFileName;
392             map<string, string> variables; 
393             string thisOutputDir = outputDir;
394             if (outputDir == "") {  thisOutputDir = m->hasPath(filesToProcess[l][0][0]); }
395             variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(filesToProcess[l][0][0]));
396             variables["[tag]"] = "";
397             if(oligosfile != ""){
398                 createGroup = getOligos(fastaFileNames, variables["[filename]"]);
399                 if (createGroup) { 
400                     outputGroupFileName = getOutputFileName("group",variables);
401                     outputNames.push_back(outputGroupFileName); outputTypes["group"].push_back(outputGroupFileName);
402                 }
403             }
404             
405             variables["[tag]"] = "trim";
406             string outFastaFile = getOutputFileName("fasta",variables);
407             variables["[tag]"] = "scrap";
408             string outScrapFastaFile = getOutputFileName("fasta",variables);
409             variables["[tag]"] = "";
410             string outMisMatchFile = getOutputFileName("report",variables);
411             outputNames.push_back(outFastaFile); outputTypes["fasta"].push_back(outFastaFile);
412             outputNames.push_back(outScrapFastaFile); outputTypes["fasta"].push_back(outScrapFastaFile);
413             outputNames.push_back(outMisMatchFile); outputTypes["report"].push_back(outMisMatchFile);
414             
415             m->mothurOut("Making contigs...\n"); 
416             createProcesses(filesToProcess[l], outFastaFile, outScrapFastaFile, outMisMatchFile, fastaFileNames);
417             m->mothurOut("Done.\n");
418             
419             //remove temp fasta and qual files
420             for (int i = 0; i < processors; i++) { for(int j = 0; j < filesToProcess[l][i].size(); j++) { m->mothurRemove(filesToProcess[l][i][j]); }  }
421             
422             if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {    m->mothurRemove(outputNames[i]); }  return 0; }
423             
424             if(allFiles){
425                 map<string, string> uniqueFastaNames;// so we don't add the same groupfile multiple times
426                 map<string, string>::iterator it;
427                 set<string> namesToRemove;
428                 for(int i=0;i<fastaFileNames.size();i++){
429                     for(int j=0;j<fastaFileNames[0].size();j++){
430                         if (fastaFileNames[i][j] != "") {
431                             if (namesToRemove.count(fastaFileNames[i][j]) == 0) {
432                                 if(m->isBlank(fastaFileNames[i][j])){
433                                     m->mothurRemove(fastaFileNames[i][j]);
434                                     namesToRemove.insert(fastaFileNames[i][j]);
435                                 }else{  
436                                     it = uniqueFastaNames.find(fastaFileNames[i][j]);
437                                     if (it == uniqueFastaNames.end()) { 
438                                         uniqueFastaNames[fastaFileNames[i][j]] = barcodeNameVector[i];  
439                                     }   
440                                 }
441                             }
442                         }
443                     }
444                 }
445                 
446                 //remove names for outputFileNames, just cleans up the output
447                 vector<string> outputNames2;
448                 for(int i = 0; i < outputNames.size(); i++) { if (namesToRemove.count(outputNames[i]) == 0) { outputNames2.push_back(outputNames[i]); } }
449                 outputNames = outputNames2;
450                 
451                 for (it = uniqueFastaNames.begin(); it != uniqueFastaNames.end(); it++) {
452                     ifstream in;
453                     m->openInputFile(it->first, in);
454                     
455                     ofstream out;
456                     string thisGroupName = thisOutputDir + m->getRootName(m->getSimpleName(it->first));
457                     thisGroupName += getOutputFileName("group",variables); outputNames.push_back(thisGroupName); outputTypes["group"].push_back(thisGroupName); 
458                     m->openOutputFile(thisGroupName, out);
459                     
460                     while (!in.eof()){
461                         if (m->control_pressed) { break; }
462                         
463                         Sequence currSeq(in); m->gobble(in);
464                         out << currSeq.getName() << '\t' << it->second << endl;  
465                     }
466                     in.close();
467                     out.close();
468                 }
469             }
470             
471             if (createGroup) {
472                 ofstream outGroup;
473                 m->openOutputFile(outputGroupFileName, outGroup);
474                 for (map<string, string>::iterator itGroup = groupMap.begin(); itGroup != groupMap.end(); itGroup++) {
475                     outGroup << itGroup->first << '\t' << itGroup->second << endl;
476                 }
477                 outGroup.close();
478             }
479             
480             if (filesToProcess.size() > 1) { //merge into large combo files
481                 if (createGroup) {  
482                     if (l == 0) { 
483                         ofstream outCGroup;
484                         m->openOutputFile(compositeGroupFile, outCGroup); outCGroup.close();
485                         outputNames.push_back(compositeGroupFile); outputTypes["group"].push_back(compositeGroupFile);
486                     }
487                     m->appendFiles(outputGroupFileName, compositeGroupFile);  
488                 }
489                 m->appendFiles(outMisMatchFile, compositeMisMatchFile);
490                 m->appendFiles(outFastaFile, compositeFastaFile);
491                 m->appendFiles(outScrapFastaFile, compositeScrapFastaFile);
492             }
493         }
494         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to process " + toString(numReads) + " sequences.\n");
495         
496         if (m->control_pressed) {       for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]); } return 0;    }
497         
498                 //output group counts
499                 m->mothurOutEndLine();
500                 int total = 0;
501                 if (groupCounts.size() != 0) {  m->mothurOut("Group count: \n");  }
502                 for (map<string, int>::iterator it = groupCounts.begin(); it != groupCounts.end(); it++) {
503             total += it->second; m->mothurOut(it->first + "\t" + toString(it->second)); m->mothurOutEndLine(); 
504                 }
505                 if (total != 0) { m->mothurOut("Total of all groups is " + toString(total)); m->mothurOutEndLine(); }
506                 
507                 if (m->control_pressed) {       for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]); } return 0;    }
508         
509         string currentFasta = "";
510                 itTypes = outputTypes.find("fasta");
511                 if (itTypes != outputTypes.end()) {
512                         if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
513                 }
514         
515         string currentGroup = "";
516                 itTypes = outputTypes.find("group");
517                 if (itTypes != outputTypes.end()) {
518                         if ((itTypes->second).size() != 0) { currentGroup = (itTypes->second)[0]; m->setGroupFile(currentGroup); }
519                 }
520                 
521         //output files created by command
522                 m->mothurOutEndLine();
523                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
524                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
525                 m->mothurOutEndLine();
526
527         return 0;
528     }
529         catch(exception& e) {
530                 m->errorOut(e, "MakeContigsCommand", "execute");
531                 exit(1);
532         }
533 }
534 //**********************************************************************************************************************
535 vector< vector< vector<string> > > MakeContigsCommand::preProcessData(unsigned long int& numReads) {
536         try {
537         vector< vector< vector<string> > > filesToProcess;
538         
539         if (ffastqfile != "") { //reading one file
540             vector< vector<string> > files = readFastqFiles(numReads, ffastqfile, rfastqfile); 
541             //adjust for really large processors or really small files
542             if (numReads == 0) {  m->mothurOut("[ERROR]: no good reads.\n"); m->control_pressed = true; }
543             if (numReads < processors) { 
544                 for (int i = numReads; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
545                 files.resize(numReads);
546                 processors = numReads; 
547             }
548             filesToProcess.push_back(files);
549         }else if (file != "") { //reading multiple files
550             //return only valid pairs
551             vector< vector<string> > filePairsToProcess = readFileNames(file);
552             
553             if (m->control_pressed) { return filesToProcess; }
554             
555             if (filePairsToProcess.size() != 0) {
556                 for (int i = 0; i < filePairsToProcess.size(); i++) {
557                     
558                     if (m->control_pressed) { for (int l = 0; l < filesToProcess.size(); l++) { for (int k = 0; k < filesToProcess[l].size(); k++) { for(int j = 0; j < filesToProcess[l][k].size(); j++) { m->mothurRemove(filesToProcess[l][k][j]); } filesToProcess[l][k].clear(); } return filesToProcess; } }
559                     
560                     unsigned long int thisFilesReads;
561                     vector< vector<string> > files = readFastqFiles(thisFilesReads, filePairsToProcess[i][0], filePairsToProcess[i][1]); 
562                     
563                     //adjust for really large processors or really small files
564                     if (thisFilesReads < processors) { 
565                         m->mothurOut("[ERROR]: " + filePairsToProcess[i][0] + " has less than " + toString(processors) + " good reads, skipping\n"); 
566                         for (int k = 0; k < files.size(); k++) { for(int j = 0; j < files[k].size(); j++) { m->mothurRemove(files[k][j]); } files[k].clear(); }
567                     }else {
568                         filesToProcess.push_back(files);
569                         numReads += thisFilesReads;
570                     }
571                 }
572                 //all files are bad
573                 if (numReads == 0) {  m->control_pressed = true; }
574             }
575         }else if (ffastafile != "") {
576             vector< vector<string> > files = readFastaFiles(numReads, ffastafile, rfastafile);
577             //adjust for really large processors or really small files
578             if (numReads == 0) {  m->mothurOut("[ERROR]: no good reads.\n"); m->control_pressed = true; }
579             if (numReads < processors) { 
580                 for (int i = numReads; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
581                 files.resize(numReads);
582                 processors = numReads; 
583             }
584             filesToProcess.push_back(files);
585         }else { m->control_pressed = true; } //should not get here
586         
587         return filesToProcess;
588     }
589         catch(exception& e) {
590                 m->errorOut(e, "MakeContigsCommand", "preProcessData");
591                 exit(1);
592         }
593 }
594 //**********************************************************************************************************************
595 int MakeContigsCommand::createProcesses(vector< vector<string> > files, string outputFasta, string outputScrapFasta, string outputMisMatches, vector<vector<string> > fastaFileNames) {
596         try {
597                 int num = 0;
598                 vector<int> processIDS;
599 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
600                 int process = 0;
601                 
602                 //loop through and create all the processes you want
603                 while (process != processors-1) {
604                         int pid = fork();
605                         
606                         if (pid > 0) {
607                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
608                                 process++;
609                         }else if (pid == 0){
610                 vector<vector<string> > tempFASTAFileNames = fastaFileNames;
611                 
612                                 if(allFiles){
613                                         ofstream temp;
614                     
615                                         for(int i=0;i<tempFASTAFileNames.size();i++){
616                                                 for(int j=0;j<tempFASTAFileNames[i].size();j++){
617                                                         if (tempFASTAFileNames[i][j] != "") {
618                                                                 tempFASTAFileNames[i][j] += toString(getpid()) + ".temp";
619                                                                 m->openOutputFile(tempFASTAFileNames[i][j], temp);                      temp.close();
620                                                         }
621                                                 }
622                                         }
623                                 }
624
625                                 num = driver(files[process], 
626                              outputFasta + toString(getpid()) + ".temp", 
627                              outputScrapFasta + toString(getpid()) + ".temp", 
628                              outputMisMatches + toString(getpid()) + ".temp",
629                              tempFASTAFileNames, process);
630                                 
631                                 //pass groupCounts to parent
632                 ofstream out;
633                 string tempFile = toString(getpid()) + ".num.temp";
634                 m->openOutputFile(tempFile, out);
635                 out << num << endl;
636                                 if(createGroup){
637                                         out << groupCounts.size() << endl;
638                                         
639                                         for (map<string, int>::iterator it = groupCounts.begin(); it != groupCounts.end(); it++) {
640                                                 out << it->first << '\t' << it->second << endl;
641                                         }
642                     
643                     out << groupMap.size() << endl;
644                     for (map<string, string>::iterator it = groupMap.begin(); it != groupMap.end(); it++) {
645                                                 out << it->first << '\t' << it->second << endl;
646                                         }
647                                 }
648                 out.close();
649                                 
650                                 exit(0);
651                         }else { 
652                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
653                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
654                                 exit(0);
655                         }
656                 }
657                 
658         ofstream temp;
659                 m->openOutputFile(outputFasta, temp);           temp.close();
660         m->openOutputFile(outputScrapFasta, temp);              temp.close();
661                 
662                 //do my part
663                 num = driver(files[processors-1], outputFasta, outputScrapFasta,  outputMisMatches, fastaFileNames, processors-1);
664                 
665                 //force parent to wait until all the processes are done
666                 for (int i=0;i<processIDS.size();i++) { 
667                         int temp = processIDS[i];
668                         wait(&temp);
669                 }
670         
671                 for (int i = 0; i < processIDS.size(); i++) {
672             ifstream in;
673             string tempFile = toString(processIDS[i]) + ".num.temp";
674             m->openInputFile(tempFile, in);
675             int tempNum;
676             in >> tempNum; num += tempNum; m->gobble(in);
677             
678                         if(createGroup){
679                                 string group;
680                                 in >> tempNum; m->gobble(in);
681                                 
682                                 if (tempNum != 0) {
683                                         for (int j = 0; j < tempNum; j++) { 
684                         int groupNum;
685                                                 in >> group >> groupNum; m->gobble(in);
686                         
687                                                 map<string, int>::iterator it = groupCounts.find(group);
688                                                 if (it == groupCounts.end()) {  groupCounts[group] = groupNum; }
689                                                 else { groupCounts[it->first] += groupNum; }
690                                         }
691                                 }
692                 in >> tempNum; m->gobble(in);
693                 if (tempNum != 0) {
694                                         for (int j = 0; j < tempNum; j++) { 
695                         string group, seqName;
696                                                 in >> seqName >> group; m->gobble(in);
697                         
698                                                 map<string, string>::iterator it = groupMap.find(seqName);
699                                                 if (it == groupMap.end()) {     groupMap[seqName] = group; }
700                                                 else { m->mothurOut("[ERROR]: " + seqName + " is in your fasta file more than once. Sequence names must be unique. please correct.\n");  }
701                                         }
702                                 }
703                         }
704             in.close(); m->mothurRemove(tempFile);
705         }
706     #else
707         
708         //////////////////////////////////////////////////////////////////////////////////////////////////////
709                 //Windows version shared memory, so be careful when passing variables through the contigsData struct. 
710                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
711                 //////////////////////////////////////////////////////////////////////////////////////////////////////
712                 
713                 vector<contigsData*> pDataArray; 
714                 DWORD   dwThreadIdArray[processors-1];
715                 HANDLE  hThreadArray[processors-1]; 
716                 
717                 //Create processor worker threads.
718                 for( int h=0; h<processors-1; h++ ){
719                         string extension = "";
720                         if (h != 0) { extension = toString(h) + ".temp"; processIDS.push_back(h); }
721             vector<vector<string> > tempFASTAFileNames = fastaFileNames;
722                         
723             if(allFiles){
724                 ofstream temp;
725                 
726                 for(int i=0;i<tempFASTAFileNames.size();i++){
727                     for(int j=0;j<tempFASTAFileNames[i].size();j++){
728                         if (tempFASTAFileNames[i][j] != "") {
729                             tempFASTAFileNames[i][j] += extension;
730                             m->openOutputFile(tempFASTAFileNames[i][j], temp);                  temp.close();
731                         }
732                     }
733                 }
734             }
735
736                                   
737                         contigsData* tempcontig = new contigsData(files[h], (outputFasta + extension), (outputScrapFasta + extension), (outputMisMatches + extension), align, m, match, misMatch, gapOpen, gapExtend, insert, deltaq, barcodes, primers, tempFASTAFileNames, barcodeNameVector, primerNameVector, pdiffs, bdiffs, tdiffs, createGroup, allFiles, h);
738                         pDataArray.push_back(tempcontig);
739             
740                         hThreadArray[h] = CreateThread(NULL, 0, MyContigsThreadFunction, pDataArray[h], 0, &dwThreadIdArray[h]);   
741                 }
742         
743         vector<vector<string> > tempFASTAFileNames = fastaFileNames;
744
745         if(allFiles){
746             ofstream temp;
747             string extension = toString(processors-1) + ".temp";
748             
749             for(int i=0;i<tempFASTAFileNames.size();i++){
750                 for(int j=0;j<tempFASTAFileNames[i].size();j++){
751                     if (tempFASTAFileNames[i][j] != "") {
752                         tempFASTAFileNames[i][j] += extension;
753                         m->openOutputFile(tempFASTAFileNames[i][j], temp);                      temp.close();
754                     }
755                 }
756             }
757         }
758
759                 //parent do my part
760                 ofstream temp;
761                 m->openOutputFile(outputFasta, temp);           temp.close();
762         m->openOutputFile(outputScrapFasta, temp);              temp.close();
763         
764         //do my part
765         processIDS.push_back(processors-1);
766                 num = driver(files[processors-1], (outputFasta+ toString(processors-1) + ".temp"),  (outputScrapFasta+ toString(processors-1) + ".temp"),  (outputMisMatches+ toString(processors-1) + ".temp"), tempFASTAFileNames, processors-1);     
767         
768                 //Wait until all threads have terminated.
769                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
770                 
771                 //Close all thread handles and free memory allocations.
772                 for(int i=0; i < pDataArray.size(); i++){
773                         num += pDataArray[i]->count;
774             if (!pDataArray[i]->done) {
775                 m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of sequences assigned to it, quitting. \n"); m->control_pressed = true; 
776             }
777             for (map<string, int>::iterator it = pDataArray[i]->groupCounts.begin(); it != pDataArray[i]->groupCounts.end(); it++) {
778                 map<string, int>::iterator it2 = groupCounts.find(it->first);
779                 if (it2 == groupCounts.end()) { groupCounts[it->first] = it->second; }
780                 else { groupCounts[it->first] += it->second; }
781             }
782             for (map<string, string>::iterator it = pDataArray[i]->groupMap.begin(); it != pDataArray[i]->groupMap.end(); it++) {
783                 map<string, string>::iterator it2 = groupMap.find(it->first);
784                 if (it2 == groupMap.end()) {    groupMap[it->first] = it->second; }
785                 else { m->mothurOut("[ERROR]: " + it->first + " is in your fasta file more than once. Sequence names must be unique. please correct.\n");  }
786             }
787             CloseHandle(hThreadArray[i]);
788                         delete pDataArray[i];
789         }
790                                 
791     #endif      
792         
793         for (int i = 0; i < processIDS.size(); i++) {
794                         m->appendFiles((outputFasta + toString(processIDS[i]) + ".temp"), outputFasta);
795                         m->mothurRemove((outputFasta + toString(processIDS[i]) + ".temp"));
796                         
797                         m->appendFiles((outputScrapFasta + toString(processIDS[i]) + ".temp"), outputScrapFasta);
798                         m->mothurRemove((outputScrapFasta + toString(processIDS[i]) + ".temp"));
799             
800             m->appendFiles((outputMisMatches + toString(processIDS[i]) + ".temp"), outputMisMatches);
801                         m->mothurRemove((outputMisMatches + toString(processIDS[i]) + ".temp"));
802             
803             if(allFiles){
804                                 for(int j=0;j<fastaFileNames.size();j++){
805                                         for(int k=0;k<fastaFileNames[j].size();k++){
806                                                 if (fastaFileNames[j][k] != "") {
807                                                         m->appendFiles((fastaFileNames[j][k] + toString(processIDS[i]) + ".temp"), fastaFileNames[j][k]);
808                                                         m->mothurRemove((fastaFileNames[j][k] + toString(processIDS[i]) + ".temp"));
809                                                 }
810                                         }
811                                 }
812                         }
813                 }
814                 
815                 return num;
816         }
817         catch(exception& e) {
818                 m->errorOut(e, "MakeContigsCommand", "createProcesses");
819                 exit(1);
820         }
821 }
822 //**********************************************************************************************************************
823 int MakeContigsCommand::driver(vector<string> files, string outputFasta, string outputScrapFasta, string outputMisMatches, vector<vector<string> > fastaFileNames, int process){
824     try {
825         
826         Alignment* alignment;
827         if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }
828                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }
829         
830         int num = 0;
831         string thisffastafile = files[0];
832         string thisfqualfile = files[1];
833         string thisrfastafile = files[2];
834         string thisrqualfile = files[3];
835         
836         if (m->debug) {  m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
837         
838         ifstream inFFasta, inRFasta, inFQual, inRQual;
839         ofstream outFasta, outMisMatch, outScrapFasta;
840         m->openInputFile(thisffastafile, inFFasta);
841         m->openInputFile(thisrfastafile, inRFasta);
842         if (thisfqualfile != "") {
843             m->openInputFile(thisfqualfile, inFQual);
844             m->openInputFile(thisrqualfile, inRQual);
845         }
846         m->openOutputFile(outputFasta, outFasta);
847         m->openOutputFile(outputScrapFasta, outScrapFasta);
848         m->openOutputFile(outputMisMatches, outMisMatch);
849         if (process == 0) { outMisMatch << "Name\tLength\tOverlap_Length\tOverlap_Start\tOverlap_End\tMisMatches\tNum_Ns\n";  }
850         
851         TrimOligos trimOligos(pdiffs, bdiffs, 0, 0, primers, barcodes);
852         
853         while ((!inFFasta.eof()) && (!inRFasta.eof())) {
854             
855             if (m->control_pressed) { break; }
856             
857             int success = 1;
858             string trashCode = "";
859             int currentSeqsDiffs = 0;
860
861             //read seqs and quality info
862             Sequence fSeq(inFFasta); m->gobble(inFFasta);
863             Sequence rSeq(inRFasta); m->gobble(inRFasta);
864             QualityScores* fQual = NULL; QualityScores* rQual = NULL;
865             if (thisfqualfile != "") {
866                 fQual = new QualityScores(inFQual); m->gobble(inFQual);
867                 rQual = new QualityScores(inRQual); m->gobble(inRQual);
868             }
869             
870             int barcodeIndex = 0;
871             int primerIndex = 0;
872             
873             if(barcodes.size() != 0){
874                 if (thisfqualfile != "") {
875                     success = trimOligos.stripBarcode(fSeq, rSeq, *fQual, *rQual, barcodeIndex);
876                 }else {
877                     success = trimOligos.stripBarcode(fSeq, rSeq, barcodeIndex);
878                 }
879                 if(success > bdiffs)            {       trashCode += 'b';       }
880                 else{ currentSeqsDiffs += success;  }
881             }
882             
883             if(primers.size() != 0){
884                 if (thisfqualfile != "") {
885                     success = trimOligos.stripForward(fSeq, rSeq, *fQual, *rQual, primerIndex);
886                 }else {
887                     success = trimOligos.stripForward(fSeq, rSeq, primerIndex);
888                 }
889                 if(success > pdiffs)            {       trashCode += 'f';       }
890                 else{ currentSeqsDiffs += success;  }
891             }
892             
893             if (currentSeqsDiffs > tdiffs)      {       trashCode += 't';   }
894             
895             //flip the reverse reads
896             rSeq.reverseComplement();
897             if (thisfqualfile != "") { rQual->flipQScores(); }
898
899             //pairwise align
900             alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
901             map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
902             map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
903             fSeq.setAligned(alignment->getSeqAAln());
904             rSeq.setAligned(alignment->getSeqBAln());
905             int length = fSeq.getAligned().length();
906             
907             //traverse alignments merging into one contiguous seq
908             string contig = "";
909             int numMismatches = 0;
910             string seq1 = fSeq.getAligned();
911             string seq2 = rSeq.getAligned();
912             vector<int> scores1, scores2; 
913             if (thisfqualfile != "") {
914                 scores1 = fQual->getQualityScores();
915                 scores2 = rQual->getQualityScores();
916                 delete fQual; delete rQual;
917             }
918             
919             // if (num < 5) {  cout << fSeq.getStartPos() << '\t' << fSeq.getEndPos() << '\t' << rSeq.getStartPos() << '\t' << rSeq.getEndPos() << endl; }
920             int overlapStart = fSeq.getStartPos();
921             int seq2Start = rSeq.getStartPos();
922             //bigger of the 2 starting positions is the location of the overlapping start
923             if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
924                 overlapStart = seq2Start; 
925                 for (int i = 0; i < overlapStart; i++) { contig += seq1[i];  }
926             }else { //seq1 starts later so take from 0 to overlapStart from seq2
927                 for (int i = 0; i < overlapStart; i++) {  contig += seq2[i]; }
928             }
929             
930             int seq1End = fSeq.getEndPos();
931             int seq2End = rSeq.getEndPos();
932             int overlapEnd = seq1End;
933             if (seq2End < overlapEnd) { overlapEnd = seq2End; }  //smallest end position is where overlapping ends
934             
935             int oStart = contig.length();
936             for (int i = overlapStart; i < overlapEnd; i++) {
937                 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
938                     contig += seq1[i];
939                 }else if (((seq1[i] == '.') || (seq1[i] == '-')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //seq1 is a gap and seq2 is a base, choose seq2, unless quality score for base is below insert. In that case eliminate base
940                     if (thisfqualfile != "") {
941                         if (scores2[BBaseMap[i]] < insert) { } //
942                         else { contig += seq2[i];  }
943                     }else { contig += seq2[i]; } //with no quality info, then we keep it?
944                 }else if (((seq2[i] == '.') || (seq2[i] == '-')) && ((seq1[i] != '-') && (seq1[i] != '.'))) { //seq2 is a gap and seq1 is a base, choose seq1, unless quality score for base is below insert. In that case eliminate base
945                     if (thisfqualfile != "") {
946                         if (scores1[ABaseMap[i]] < insert) { } //
947                         else { contig += seq1[i];  }
948                     }else { contig += seq1[i]; } //with no quality info, then we keep it?
949                 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
950                     if (thisfqualfile != "") {
951                         if (abs(scores1[ABaseMap[i]] - scores2[BBaseMap[i]]) >= deltaq) { //is the difference in qual scores >= deltaq, if yes choose base with higher score
952                             char c = seq1[i];
953                             if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { c = seq2[i]; }
954                             contig += c;
955                         }else { //if no, base becomes n
956                             contig += 'N';
957                         }
958                         numMismatches++;
959                     }else { numMismatches++; } //cant decide, so eliminate and mark as mismatch
960                 }else { //should never get here
961                     m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
962                 }
963             }
964             int oend = contig.length();
965             if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
966                 for (int i = overlapEnd; i < length; i++) { contig += seq2[i];  }
967             }else { //seq2 ends before seq1 so take from overlap to length from seq1
968                 for (int i = overlapEnd; i < length; i++) {  contig += seq1[i]; }
969             }
970             
971             if(trashCode.length() == 0){
972                 bool ignore = false;
973                 
974                 if (m->debug) { m->mothurOut(fSeq.getName()); }
975                 
976                 if (createGroup) {
977                     if(barcodes.size() != 0){
978                         string thisGroup = barcodeNameVector[barcodeIndex];
979                         if (primers.size() != 0) { 
980                             if (primerNameVector[primerIndex] != "") { 
981                                 if(thisGroup != "") {
982                                     thisGroup += "." + primerNameVector[primerIndex]; 
983                                 }else {
984                                     thisGroup = primerNameVector[primerIndex]; 
985                                 }
986                             } 
987                         }
988                         
989                         if (m->debug) { m->mothurOut(", group= " + thisGroup + "\n"); }
990                         
991                         int pos = thisGroup.find("ignore");
992                         if (pos == string::npos) {
993                             groupMap[fSeq.getName()] = thisGroup; 
994                         
995                             map<string, int>::iterator it = groupCounts.find(thisGroup);
996                             if (it == groupCounts.end()) {      groupCounts[thisGroup] = 1; }
997                             else { groupCounts[it->first] ++; }
998                         }else { ignore = true; }
999                         
1000                     }
1001                 }
1002                 if (m->debug) { m->mothurOut("\n"); }
1003                 
1004                 if(allFiles && !ignore){
1005                     ofstream output;
1006                     m->openOutputFileAppend(fastaFileNames[barcodeIndex][primerIndex], output);
1007                     output << ">" << fSeq.getName() << endl << contig << endl;
1008                     output.close();
1009                 }
1010                 
1011                 //output
1012                 outFasta << ">" << fSeq.getName() << endl << contig << endl;
1013                 int numNs = 0;
1014                 for (int i = 0; i < contig.length(); i++) { if (contig[i] == 'N') { numNs++; }  }
1015                 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << (oend-oStart) << '\t' << oStart << '\t' << oend << '\t' << numMismatches << '\t' << numNs << endl;
1016             }else {
1017                 //output
1018                 outScrapFasta << ">" << fSeq.getName() << " | " << trashCode << endl << contig << endl;
1019             }
1020             num++;
1021             
1022                         //report progress
1023                         if((num) % 1000 == 0){  m->mothurOut(toString(num)); m->mothurOutEndLine();             }
1024                 }
1025         
1026                 //report progress
1027                 if((num) % 1000 != 0){  m->mothurOut(toString(num)); m->mothurOutEndLine();             }
1028         
1029         inFFasta.close();
1030         inRFasta.close();
1031         outFasta.close();
1032         outScrapFasta.close();
1033         outMisMatch.close();
1034         if (thisfqualfile != "") {
1035             inFQual.close();
1036             inRQual.close();
1037         }
1038         delete alignment;
1039         
1040         if (m->control_pressed) {  m->mothurRemove(outputFasta); m->mothurRemove(outputScrapFasta);m->mothurRemove(outputMisMatches);  }
1041     
1042         return num;
1043     }
1044         catch(exception& e) {
1045                 m->errorOut(e, "MakeContigsCommand", "driver");
1046                 exit(1);
1047         }
1048 }
1049 //**********************************************************************************************************************
1050 vector< vector<string> > MakeContigsCommand::readFastqFiles(unsigned long int& count, string ffastq, string rfastq){
1051     try {
1052         vector< vector<string> > files;
1053         //maps processors number to file pointer
1054         map<int, vector<ofstream*> > tempfiles;  //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
1055         map<int, vector<ofstream*> >::iterator it;
1056         
1057         //create files to write to
1058         for (int i = 0; i < processors; i++) {
1059             vector<ofstream*> temp;
1060             ofstream* outFF = new ofstream;     temp.push_back(outFF);
1061             ofstream* outFQ = new ofstream;     temp.push_back(outFQ);
1062             ofstream* outRF = new ofstream;     temp.push_back(outRF);
1063             ofstream* outRQ = new ofstream;     temp.push_back(outRQ);
1064             tempfiles[i] = temp;
1065             
1066             vector<string> names;
1067             string thisOutputDir = outputDir;
1068             if (outputDir == "") { thisOutputDir = m->hasPath(ffastq); }
1069             string ffastafilename = thisOutputDir + m->getRootName(m->getSimpleName(ffastq)) + toString(i) + "ffastatemp";
1070             string rfastafilename = thisOutputDir + m->getRootName(m->getSimpleName(rfastq)) + toString(i) + "rfastatemp";
1071             string fqualfilename = thisOutputDir + m->getRootName(m->getSimpleName(ffastq)) + toString(i) + "fqualtemp";
1072             string rqualfilename = thisOutputDir + m->getRootName(m->getSimpleName(rfastq)) + toString(i) + "rqualtemp";
1073             names.push_back(ffastafilename); names.push_back(fqualfilename);
1074             names.push_back(rfastafilename); names.push_back(rqualfilename);
1075             files.push_back(names);
1076             
1077             m->openOutputFile(ffastafilename, *outFF);
1078             m->openOutputFile(rfastafilename, *outRF);
1079             m->openOutputFile(fqualfilename, *outFQ);
1080             m->openOutputFile(rqualfilename, *outRQ);
1081         }
1082         
1083         if (m->control_pressed) {
1084             //close files, delete ofstreams
1085             for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } }
1086             //remove files
1087             for (int i = 0; i < files.size(); i++) {  
1088                 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
1089             }
1090         }
1091         
1092         ifstream inForward;
1093         m->openInputFile(ffastq, inForward);
1094         
1095         ifstream inReverse;
1096         m->openInputFile(rfastq, inReverse);
1097         
1098         count = 0;
1099         map<string, fastqRead> uniques;
1100         map<string, fastqRead>::iterator itUniques;
1101         while ((!inForward.eof()) || (!inReverse.eof())) {
1102             
1103             if (m->control_pressed) { for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } } for (int i = 0; i < files.size(); i++) {  for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } inForward.close(); inReverse.close(); return files; }
1104             
1105             //get a read from forward and reverse fastq files
1106             bool ignoref, ignorer;
1107             fastqRead thisFread, thisRread;
1108             if (!inForward.eof()) {  thisFread = readFastq(inForward, ignoref); }
1109             else { ignoref = true; }
1110             if (!inReverse.eof()) { thisRread = readFastq(inReverse, ignorer);  }
1111             else { ignorer = true; }
1112             
1113             vector<pairFastqRead> reads = getReads(ignoref, ignorer, thisFread, thisRread, uniques);
1114            
1115             for (int i = 0; i < reads.size(); i++) {
1116                 fastqRead fread = reads[i].forward;
1117                 fastqRead rread = reads[i].reverse;
1118                 
1119                 if (m->debug) { m->mothurOut(toString(count) + '\t' + fread.name + '\t' + rread.name + '\n'); }
1120                
1121                 //if (checkReads(fread, rread, ffastq, rfastq)) {
1122                     if (m->control_pressed) { for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } } for (int i = 0; i < files.size(); i++) {  for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } inForward.close(); inReverse.close(); return files; }
1123                     
1124                     //if the reads are okay write to output files
1125                     int process = count % processors;
1126                     
1127                     *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
1128                     *(tempfiles[process][1]) << ">" << fread.name << endl;
1129                     for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
1130                     *(tempfiles[process][1]) << endl;
1131                     *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
1132                     *(tempfiles[process][3]) << ">" << rread.name << endl;
1133                     for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
1134                     *(tempfiles[process][3]) << endl;
1135                     
1136                     count++;
1137                     
1138                     //report progress
1139                     if((count) % 10000 == 0){   m->mothurOut(toString(count)); m->mothurOutEndLine();           }
1140                 //}
1141             }
1142                 }
1143                 //report progress
1144                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
1145         
1146         if (uniques.size() != 0) {
1147             for (itUniques = uniques.begin(); itUniques != uniques.end(); itUniques++) {
1148                 m->mothurOut("[WARNING]: did not find paired read for " + itUniques->first + ", ignoring.\n");
1149             }
1150             m->mothurOutEndLine();
1151         }
1152         
1153         //close files, delete ofstreams
1154         for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } }
1155         inForward.close();
1156         inReverse.close();
1157         
1158         return files;
1159     }
1160     catch(exception& e) {
1161         m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
1162         exit(1);
1163     }
1164 }
1165 //**********************************************************************************************************************
1166 vector< vector<string> > MakeContigsCommand::readFastaFiles(unsigned long int& count, string ffasta, string rfasta){
1167     try {
1168         vector< vector<string> > files;
1169         //maps processors number to file pointer
1170         map<int, vector<ofstream*> > tempfiles;  //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
1171         map<int, vector<ofstream*> >::iterator it;
1172         
1173         //create files to write to
1174         for (int i = 0; i < processors; i++) {
1175             vector<ofstream*> temp;
1176             ofstream* outFF = new ofstream;     temp.push_back(outFF);
1177             ofstream* outFQ = new ofstream;     temp.push_back(outFQ);
1178             ofstream* outRF = new ofstream;     temp.push_back(outRF);
1179             ofstream* outRQ = new ofstream;     temp.push_back(outRQ);
1180             tempfiles[i] = temp;
1181             
1182             vector<string> names;
1183             string thisOutputDir = outputDir;
1184             if (outputDir == "") { thisOutputDir = m->hasPath(ffasta); }
1185             string ffastafilename = thisOutputDir + m->getRootName(m->getSimpleName(ffasta)) + toString(i) + "ffastatemp";
1186             string rfastafilename = thisOutputDir + m->getRootName(m->getSimpleName(rfasta)) + toString(i) + "rfastatemp";
1187             string fqualfilename = "";
1188             if (fqualfile != "") { fqualfilename = thisOutputDir + m->getRootName(m->getSimpleName(fqualfile)) + toString(i) + "fqual.temp";  m->openOutputFile(fqualfilename, *outFQ); }
1189             string rqualfilename = "";
1190             if (rqualfile != "") { rqualfilename = thisOutputDir + m->getRootName(m->getSimpleName(rqualfile)) + toString(i) + "rqual.temp"; m->openOutputFile(rqualfilename, *outRQ); }
1191             names.push_back(ffastafilename); names.push_back(fqualfilename);
1192             names.push_back(rfastafilename); names.push_back(rqualfilename);
1193             files.push_back(names);
1194             
1195             m->openOutputFile(ffastafilename, *outFF);
1196             m->openOutputFile(rfastafilename, *outRF);
1197         }
1198         
1199         if (m->control_pressed) {
1200             //close files, delete ofstreams
1201             for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } }
1202             //remove files
1203             for (int i = 0; i < files.size(); i++) {  
1204                 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
1205             }
1206         }
1207         
1208         ifstream inForwardFasta;
1209         m->openInputFile(ffasta, inForwardFasta);
1210         
1211         ifstream inReverseFasta;
1212         m->openInputFile(rfasta, inReverseFasta);
1213         
1214         ifstream inForwardQual, inReverseQual;
1215         if (fqualfile != "") { m->openInputFile(fqualfile, inForwardQual); m->openInputFile(rqualfile, inReverseQual); }
1216         
1217         count = 0;
1218         map<string, fastqRead> uniques;
1219         map<string, fastqRead>::iterator itUniques;
1220         while ((!inForwardFasta.eof()) || (!inReverseFasta.eof())) {
1221             
1222             if (m->control_pressed) { for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } } for (int i = 0; i < files.size(); i++) {  for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } inReverseFasta.close(); inForwardFasta.close(); if (fqualfile != "") { inReverseQual.close(); inReverseQual.close(); } return files; }
1223             
1224             //get a reads from forward and reverse fasta files
1225             bool ignoref, ignorer;
1226             fastqRead thisFread, thisRread;
1227             if (!inForwardFasta.eof()) {  
1228                 ignoref = false; 
1229                 Sequence temp(inForwardFasta); m->gobble(inForwardFasta);
1230                 thisFread.name = temp.getName();
1231                 thisFread.sequence = temp.getUnaligned();
1232             }else { ignoref = true; }
1233             if (!inReverseFasta.eof()) {  
1234                 ignorer = false; 
1235                 Sequence temp(inReverseFasta); m->gobble(inReverseFasta);
1236                 thisRread.name = temp.getName();
1237                 thisRread.sequence = temp.getUnaligned();  
1238             }else { ignorer = true; }
1239             
1240             //get qual reads if given
1241             if (fqualfile != "") {
1242                 if (!inForwardQual.eof() && !ignoref) {  
1243                     QualityScores temp(inForwardQual); m->gobble(inForwardQual);
1244                     //if forward files dont match ignore read
1245                     if (thisFread.name != temp.getName()) { ignoref = true; } 
1246                     else { thisFread.scores = temp.getQualityScores(); }
1247                 }else { ignoref = true; }
1248                 if (!inReverseQual.eof() && !ignorer) {  
1249                     QualityScores temp(inReverseQual); m->gobble(inReverseQual);
1250                     //if reverse files dont match ignore read
1251                     if (thisRread.name != temp.getName()) { ignorer = true; } 
1252                     else { thisRread.scores = temp.getQualityScores(); }
1253                 }else { ignorer = true; }
1254             }
1255             
1256             vector<pairFastqRead> reads = getReads(ignoref, ignorer, thisFread, thisRread, uniques);
1257             
1258             for (int i = 0; i < reads.size(); i++) {
1259                 fastqRead fread = reads[i].forward;
1260                 fastqRead rread = reads[i].reverse;
1261                 
1262                 if (m->debug) { m->mothurOut(toString(count) + '\t' + fread.name + '\t' + rread.name + '\n'); }
1263                 
1264                // if (checkReads(fread, rread, ffasta, rfasta)) {
1265                     if (m->control_pressed) { for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } } for (int i = 0; i < files.size(); i++) {  for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } inReverseFasta.close(); inForwardFasta.close(); if (fqualfile != "") { inReverseQual.close(); inReverseQual.close(); } return files; }
1266                     
1267                     //if the reads are okay write to output files
1268                     int process = count % processors;
1269                     
1270                     *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
1271                     *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
1272                     if (fqualfile != "") { //if you have quality info, print it
1273                         *(tempfiles[process][1]) << ">" << fread.name << endl;
1274                         for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
1275                         *(tempfiles[process][1]) << endl;
1276                         *(tempfiles[process][3]) << ">" << rread.name << endl;
1277                         for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
1278                         *(tempfiles[process][3]) << endl;
1279                     }
1280                     count++;
1281                     
1282                     //report progress
1283                     if((count) % 10000 == 0){   m->mothurOut(toString(count)); m->mothurOutEndLine();           }
1284                 //}
1285             }
1286                 }
1287                 //report progress
1288                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
1289         
1290         if (uniques.size() != 0) {
1291             for (itUniques = uniques.begin(); itUniques != uniques.end(); itUniques++) {
1292                 m->mothurOut("[WARNING]: did not find paired read for " + itUniques->first + ", ignoring.\n");
1293             }
1294             m->mothurOutEndLine();
1295         }
1296         
1297         //close files, delete ofstreams
1298         for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close();  delete (it->second)[i]; } }
1299         inReverseFasta.close(); 
1300         inForwardFasta.close(); 
1301         if (fqualfile != "") { inReverseQual.close(); inReverseQual.close(); }
1302         
1303         return files;
1304     }
1305     catch(exception& e) {
1306         m->errorOut(e, "MakeContigsCommand", "readFastaFiles");
1307         exit(1);
1308     }
1309 }
1310 //**********************************************************************************************************************
1311 vector<pairFastqRead> MakeContigsCommand::getReads(bool ignoref, bool ignorer, fastqRead forward, fastqRead reverse, map<string, fastqRead>& uniques){
1312     try {
1313         vector<pairFastqRead> reads;
1314         map<string, fastqRead>::iterator itUniques;
1315             
1316         if (!ignoref && !ignorer) {
1317             if (forward.name == reverse.name) { 
1318                 pairFastqRead temp(forward, reverse);
1319                 reads.push_back(temp);
1320             }else {
1321                 bool match = false;
1322                 //if no match are the names only different by 1 and 2?
1323                 string tempFRead = forward.name.substr(0, forward.name.length()-1);
1324                 string tempRRead = reverse.name.substr(0, reverse.name.length()-1);
1325                 if (tempFRead == tempRRead) {
1326                     if ((forward.name[forward.name.length()-1] == '1') && (reverse.name[reverse.name.length()-1] == '2')) {
1327                         forward.name = tempFRead;
1328                         reverse.name = tempRRead;
1329                         pairFastqRead temp(forward, reverse);
1330                         reads.push_back(temp);
1331                         match = true;
1332                     }
1333                 }
1334                 
1335                 if (!match) {
1336                     //look for forward pair
1337                     itUniques = uniques.find(forward.name);
1338                     if (itUniques != uniques.end()) {  //we have the pair for this read
1339                         pairFastqRead temp(forward, itUniques->second);
1340                         reads.push_back(temp);
1341                         uniques.erase(itUniques);
1342                     }else { //save this read for later
1343                         uniques[forward.name] = forward;
1344                     }
1345                     
1346                     //look for reverse pair
1347                     itUniques = uniques.find(reverse.name);
1348                     if (itUniques != uniques.end()) {  //we have the pair for this read
1349                         pairFastqRead temp(itUniques->second, reverse);
1350                         reads.push_back(temp);
1351                         uniques.erase(itUniques);
1352                     }else { //save this read for later
1353                         uniques[reverse.name] = reverse;
1354                     }
1355                 }
1356                                 
1357             }
1358         }else if (!ignoref && ignorer) { //ignore reverse keep forward
1359             //look for forward pair
1360             itUniques = uniques.find(forward.name);
1361             if (itUniques != uniques.end()) {  //we have the pair for this read
1362                 pairFastqRead temp(forward, itUniques->second);
1363                 reads.push_back(temp);
1364                 uniques.erase(itUniques);
1365             }else { //save this read for later
1366                 uniques[forward.name] = forward;
1367             }
1368
1369         }else if (ignoref && !ignorer) { //ignore forward keep reverse
1370             //look for reverse pair
1371             itUniques = uniques.find(reverse.name);
1372             if (itUniques != uniques.end()) {  //we have the pair for this read
1373                 pairFastqRead temp(itUniques->second, reverse);
1374                 reads.push_back(temp);
1375                 uniques.erase(itUniques);
1376             }else { //save this read for later
1377                 uniques[reverse.name] = reverse;
1378             }
1379         }//else ignore both and do nothing
1380         
1381         return reads;
1382     }
1383     catch(exception& e) {
1384         m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
1385         exit(1);
1386     }
1387 }
1388 //**********************************************************************************************************************
1389 fastqRead MakeContigsCommand::readFastq(ifstream& in, bool& ignore){
1390     try {
1391         fastqRead read;
1392         
1393         ignore = false;
1394         
1395         //read sequence name
1396         string line = m->getline(in); m->gobble(in);
1397         vector<string> pieces = m->splitWhiteSpace(line);
1398         string name = "";  if (pieces.size() != 0) { name = pieces[0]; }
1399         if (name == "") {  m->mothurOut("[WARNING]: Blank fasta name, ignoring read."); m->mothurOutEndLine(); ignore=true;  }
1400         else if (name[0] != '@') { m->mothurOut("[WARNING]: reading " + name + " expected a name with @ as a leading character, ignoring read."); m->mothurOutEndLine(); ignore=true; }
1401         else { name = name.substr(1); }
1402         
1403         //read sequence
1404         string sequence = m->getline(in); m->gobble(in);
1405         if (sequence == "") {  m->mothurOut("[WARNING]: missing sequence for " + name + ", ignoring."); ignore=true; }
1406         
1407         //read sequence name
1408         line = m->getline(in); m->gobble(in);
1409         pieces = m->splitWhiteSpace(line);
1410         string name2 = "";  if (pieces.size() != 0) { name2 = pieces[0]; }
1411         if (name2 == "") {  m->mothurOut("[WARNING]: expected a name with + as a leading character, ignoring."); ignore=true; }
1412         else if (name2[0] != '+') { m->mothurOut("[WARNING]: reading " + name2 + " expected a name with + as a leading character, ignoring."); ignore=true; }
1413         else { name2 = name2.substr(1); if (name2 == "") { name2 = name; } }
1414         
1415         //read quality scores
1416         string quality = m->getline(in); m->gobble(in);
1417         if (quality == "") {  m->mothurOut("[WARNING]: missing quality for " + name2 + ", ignoring."); ignore=true; }
1418          
1419         //sanity check sequence length and number of quality scores match
1420         if (name2 != "") { if (name != name2) { m->mothurOut("[WARNING]: names do not match. read " + name + " for fasta and " + name2 + " for quality, ignoring."); ignore=true; } }
1421         if (quality.length() != sequence.length()) { m->mothurOut("[WARNING]: Lengths do not match for sequence " + name + ". Read " + toString(sequence.length()) + " characters for fasta and " + toString(quality.length()) + " characters for quality scores, ignoring read."); ignore=true; }
1422         
1423         vector<int> qualScores = convertQual(quality);
1424         
1425         read.name = name;
1426         read.sequence = sequence;
1427         read.scores = qualScores;
1428
1429         return read;
1430     }
1431     catch(exception& e) {
1432         m->errorOut(e, "MakeContigsCommand", "readFastq");
1433         exit(1);
1434     }
1435 }
1436 /**********************************************************************************************************************
1437 bool MakeContigsCommand::checkReads(fastqRead& forward, fastqRead& reverse, string ffile, string rfile){
1438     try {
1439         bool good = true;
1440         
1441         //do sequence lengths match
1442         if (forward.sequence.length() != reverse.sequence.length()) {
1443             m->mothurOut("[WARNING]: For sequence " + forward.name + " I read a sequence of length " + toString(forward.sequence.length()) + " from " + ffile + ", but read a sequence of length " + toString(reverse.sequence.length()) + " from " + rfile + ", ignoring.\n");
1444             good = false; 
1445         }
1446         
1447         //do number of qual scores match 
1448         if (forward.scores.size() != reverse.scores.size()) {
1449             m->mothurOut("[WARNING]: For sequence " + forward.name + " I read " + toString(forward.scores.size()) + " quality scores from " + ffile + ", but read  " + toString(reverse.scores.size()) + " quality scores from " + rfile + ", ignoring.\n");
1450             good = false; 
1451         }
1452
1453         return good;
1454     }
1455     catch(exception& e) {
1456         m->errorOut(e, "MakeContigsCommand", "checkReads");
1457         exit(1);
1458     }
1459 }*/
1460 //***************************************************************************************************************
1461 vector< vector<string> > MakeContigsCommand::readFileNames(string filename){
1462         try {
1463         vector< vector<string> > files;
1464         string forward, reverse;
1465         
1466         ifstream in;
1467         m->openInputFile(filename, in);
1468         
1469         while(!in.eof()) {
1470             
1471             if (m->control_pressed) { return files; }
1472             
1473             in >> forward; m->gobble(in);
1474             in >> reverse; m->gobble(in);
1475             
1476             //check to make sure both are able to be opened
1477             ifstream in2;
1478             int openForward = m->openInputFile(forward, in2, "noerror");
1479             
1480             //if you can't open it, try default location
1481             if (openForward == 1) {
1482                 if (m->getDefaultPath() != "") { //default path is set
1483                     string tryPath = m->getDefaultPath() + m->getSimpleName(forward);
1484                     m->mothurOut("Unable to open " + forward + ". Trying default " + tryPath); m->mothurOutEndLine();
1485                     ifstream in3;
1486                     openForward = m->openInputFile(tryPath, in3, "noerror");
1487                     in3.close();
1488                     forward = tryPath;
1489                 }
1490             }
1491             
1492             //if you can't open it, try output location
1493             if (openForward == 1) {
1494                 if (m->getOutputDir() != "") { //default path is set
1495                     string tryPath = m->getOutputDir() + m->getSimpleName(forward);
1496                     m->mothurOut("Unable to open " + forward + ". Trying output directory " + tryPath); m->mothurOutEndLine();
1497                     ifstream in4;
1498                     openForward = m->openInputFile(tryPath, in4, "noerror");
1499                     forward = tryPath;
1500                     in4.close();
1501                 }
1502             }
1503             
1504             if (openForward == 1) { //can't find it
1505                 m->mothurOut("[WARNING]: can't find " + forward + ", ignoring pair.\n"); 
1506             }else{  in2.close();  }
1507             
1508             ifstream in3;
1509             int openReverse = m->openInputFile(reverse, in3, "noerror");
1510             
1511             //if you can't open it, try default location
1512             if (openReverse == 1) {
1513                 if (m->getDefaultPath() != "") { //default path is set
1514                     string tryPath = m->getDefaultPath() + m->getSimpleName(reverse);
1515                     m->mothurOut("Unable to open " + reverse + ". Trying default " + tryPath); m->mothurOutEndLine();
1516                     ifstream in3;
1517                     openReverse = m->openInputFile(tryPath, in3, "noerror");
1518                     in3.close();
1519                     reverse = tryPath;
1520                 }
1521             }
1522             
1523             //if you can't open it, try output location
1524             if (openReverse == 1) {
1525                 if (m->getOutputDir() != "") { //default path is set
1526                     string tryPath = m->getOutputDir() + m->getSimpleName(reverse);
1527                     m->mothurOut("Unable to open " + reverse + ". Trying output directory " + tryPath); m->mothurOutEndLine();
1528                     ifstream in4;
1529                     openReverse = m->openInputFile(tryPath, in4, "noerror");
1530                     reverse = tryPath;
1531                     in4.close();
1532                 }
1533             }
1534             
1535             if (openReverse == 1) { //can't find it
1536                 m->mothurOut("[WARNING]: can't find " + reverse + ", ignoring pair.\n"); 
1537             }else{  in3.close();  }
1538             
1539             if ((openForward != 1) && (openReverse != 1)) { //good pair
1540                 vector<string> pair;
1541                 pair.push_back(forward);
1542                 pair.push_back(reverse);
1543                 files.push_back(pair);
1544             }
1545             
1546         }
1547         in.close();
1548         
1549         return files;
1550     }
1551     catch(exception& e) {
1552         m->errorOut(e, "MakeContigsCommand", "checkReads");
1553         exit(1);
1554     }
1555 }
1556 //***************************************************************************************************************
1557 //illumina data requires paired forward and reverse data
1558 //BARCODE   atgcatgc   atgcatgc    groupName 
1559 //PRIMER   atgcatgc   atgcatgc    groupName  
1560 //PRIMER   atgcatgc   atgcatgc  
1561 bool MakeContigsCommand::getOligos(vector<vector<string> >& fastaFileNames, string rootname){
1562         try {
1563                 ifstream in;
1564                 m->openInputFile(oligosfile, in);
1565                 
1566                 ofstream test;
1567                 
1568                 string type, foligo, roligo, group;
1569         
1570                 int indexPrimer = 0;
1571                 int indexBarcode = 0;
1572         set<string> uniquePrimers;
1573         set<string> uniqueBarcodes;
1574                 
1575                 while(!in.eof()){
1576             
1577                         in >> type; 
1578     
1579                         if (m->debug) { m->mothurOut("[DEBUG]: reading type - " + type + ".\n"); }      
1580             
1581                         if(type[0] == '#'){
1582                                 while (!in.eof())       {       char c = in.get();  if (c == 10 || c == 13){    break;  }       } // get rest of line if there's any crap there
1583                                 m->gobble(in);
1584                         }
1585                         else{
1586                                 m->gobble(in);
1587                                 //make type case insensitive
1588                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }
1589                                 
1590                                 in >> foligo;
1591                 
1592                 if (m->debug) { m->mothurOut("[DEBUG]: reading - " + foligo + ".\n"); }
1593                                 
1594                                 for(int i=0;i<foligo.length();i++){
1595                                         foligo[i] = toupper(foligo[i]);
1596                                         if(foligo[i] == 'U')    {       foligo[i] = 'T';        }
1597                                 }
1598                                 
1599                                 if(type == "FORWARD"){
1600                                         m->gobble(in);
1601                                         
1602                     in >> roligo;
1603                     
1604                     for(int i=0;i<roligo.length();i++){
1605                         roligo[i] = toupper(roligo[i]);
1606                         if(roligo[i] == 'U')    {       roligo[i] = 'T';        }
1607                     }
1608                     //roligo = reverseOligo(roligo);
1609                     
1610                     group = "";
1611                     
1612                                         // get rest of line in case there is a primer name
1613                                         while (!in.eof())       {       
1614                                                 char c = in.get(); 
1615                                                 if (c == 10 || c == 13){        break;  }
1616                                                 else if (c == 32 || c == 9){;} //space or tab
1617                                                 else {  group += c;  }
1618                                         } 
1619                     
1620                     oligosPair newPrimer(foligo, roligo);
1621                                         
1622                                         //check for repeat barcodes
1623                     string tempPair = foligo+roligo;
1624                     if (uniquePrimers.count(tempPair) != 0) { m->mothurOut("primer pair " + newPrimer.forward + " " + newPrimer.reverse + " is in your oligos file already."); m->mothurOutEndLine();  }
1625                     else { uniquePrimers.insert(tempPair); }
1626                                         
1627                     if (m->debug) {  if (group != "") { m->mothurOut("[DEBUG]: reading group " + group + ".\n"); }else{ m->mothurOut("[DEBUG]: no group for primer pair " + newPrimer.forward + " " + newPrimer.reverse + ".\n"); }  }
1628                     
1629                                         primers[indexPrimer]=newPrimer; indexPrimer++;          
1630                                         primerNameVector.push_back(group);
1631                                 }else if(type == "BARCODE"){
1632                                         m->gobble(in);
1633                                         
1634                     in >> roligo;
1635                     
1636                     for(int i=0;i<roligo.length();i++){
1637                         roligo[i] = toupper(roligo[i]);
1638                         if(roligo[i] == 'U')    {       roligo[i] = 'T';        }
1639                     }
1640                     //roligo = reverseOligo(roligo);
1641                     
1642                     oligosPair newPair(foligo, roligo);
1643                     
1644                     group = "";
1645                     while (!in.eof())   {       
1646                                                 char c = in.get(); 
1647                                                 if (c == 10 || c == 13){        break;  }
1648                                                 else if (c == 32 || c == 9){;} //space or tab
1649                                                 else {  group += c;  }
1650                                         } 
1651                                         
1652                     if (m->debug) { m->mothurOut("[DEBUG]: barcode pair " + newPair.forward + " " + newPair.reverse + ", and group = " + group + ".\n"); }
1653                         
1654                     //check for repeat barcodes
1655                     string tempPair = foligo+roligo;
1656                     if (uniqueBarcodes.count(tempPair) != 0) { m->mothurOut("barcode pair " + newPair.forward + " " + newPair.reverse +  " is in your oligos file already, disregarding."); m->mothurOutEndLine();  }
1657                     else { uniqueBarcodes.insert(tempPair); }
1658                         
1659                     barcodes[indexBarcode]=newPair; indexBarcode++;
1660                                         barcodeNameVector.push_back(group);
1661                                 }else if(type == "LINKER"){
1662                                         linker.push_back(foligo);
1663                     m->mothurOut("[WARNING]: make.contigs is not setup to remove linkers, ignoring.\n");
1664                                 }else if(type == "SPACER"){
1665                                         spacer.push_back(foligo);
1666                     m->mothurOut("[WARNING]: make.contigs is not setup to remove spacers, ignoring.\n");
1667                                 }
1668                                 else{   m->mothurOut("[WARNING]: " + type + " is not recognized as a valid type. Choices are primer, barcode, linker and spacer. Ignoring " + foligo + "."); m->mothurOutEndLine(); }
1669                         }
1670                         m->gobble(in);
1671                 }       
1672                 in.close();
1673                 
1674                 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0;   }
1675                 
1676                 //add in potential combos
1677                 if(barcodeNameVector.size() == 0){
1678             oligosPair temp("", "");
1679                         barcodes[0] = temp;
1680                         barcodeNameVector.push_back("");                        
1681                 }
1682                 
1683                 if(primerNameVector.size() == 0){
1684             oligosPair temp("", "");
1685                         primers[0] = temp;
1686                         primerNameVector.push_back("");                 
1687                 }
1688                 
1689                 fastaFileNames.resize(barcodeNameVector.size());
1690                 for(int i=0;i<fastaFileNames.size();i++){
1691                         fastaFileNames[i].assign(primerNameVector.size(), "");
1692                 }
1693                 
1694                 if(allFiles){
1695                         set<string> uniqueNames; //used to cleanup outputFileNames
1696                         for(map<int, oligosPair>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
1697                                 for(map<int, oligosPair>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
1698                                         
1699                                         string primerName = primerNameVector[itPrimer->first];
1700                                         string barcodeName = barcodeNameVector[itBar->first];
1701                     
1702                     if ((primerName == "ignore") || (barcodeName == "ignore")) { } //do nothing 
1703                                         else {
1704                         string comboGroupName = "";
1705                         string fastaFileName = "";
1706                         string qualFileName = "";
1707                         string nameFileName = "";
1708                         string countFileName = "";
1709                         
1710                         if(primerName == ""){
1711                             comboGroupName = barcodeNameVector[itBar->first];
1712                         }
1713                         else{
1714                             if(barcodeName == ""){
1715                                 comboGroupName = primerNameVector[itPrimer->first];
1716                             }
1717                             else{
1718                                 comboGroupName = barcodeNameVector[itBar->first] + "." + primerNameVector[itPrimer->first];
1719                             }
1720                         }
1721                         
1722                         
1723                         ofstream temp;
1724                         fastaFileName = rootname + comboGroupName + ".fasta";
1725                         if (uniqueNames.count(fastaFileName) == 0) {
1726                             outputNames.push_back(fastaFileName);
1727                             outputTypes["fasta"].push_back(fastaFileName);
1728                             uniqueNames.insert(fastaFileName);
1729                         }
1730                         
1731                         fastaFileNames[itBar->first][itPrimer->first] = fastaFileName;
1732                         m->openOutputFile(fastaFileName, temp);         temp.close();
1733                     }
1734                                 }
1735                         }
1736                 }
1737                 
1738                 bool allBlank = true;
1739                 for (int i = 0; i < barcodeNameVector.size(); i++) {
1740                         if (barcodeNameVector[i] != "") {
1741                                 allBlank = false;
1742                                 break;
1743                         }
1744                 }
1745                 for (int i = 0; i < primerNameVector.size(); i++) {
1746                         if (primerNameVector[i] != "") {
1747                                 allBlank = false;
1748                                 break;
1749                         }
1750                 }
1751         
1752                 if (allBlank) {
1753                         m->mothurOut("[WARNING]: your oligos file does not contain any group names.  mothur will not create a groupfile."); m->mothurOutEndLine();
1754                         allFiles = false;
1755                         return false;
1756                 }
1757                 
1758                 return true;
1759                 
1760         }
1761         catch(exception& e) {
1762                 m->errorOut(e, "MakeContigsCommand", "getOligos");
1763                 exit(1);
1764         }
1765 }
1766 //********************************************************************/
1767 string MakeContigsCommand::reverseOligo(string oligo){
1768         try {
1769         string reverse = "";
1770         
1771         for(int i=oligo.length()-1;i>=0;i--){
1772             
1773             if(oligo[i] == 'A')         {       reverse += 'T'; }
1774             else if(oligo[i] == 'T'){   reverse += 'A'; }
1775             else if(oligo[i] == 'U'){   reverse += 'A'; }
1776             
1777             else if(oligo[i] == 'G'){   reverse += 'C'; }
1778             else if(oligo[i] == 'C'){   reverse += 'G'; }
1779             
1780             else if(oligo[i] == 'R'){   reverse += 'Y'; }
1781             else if(oligo[i] == 'Y'){   reverse += 'R'; }
1782             
1783             else if(oligo[i] == 'M'){   reverse += 'K'; }
1784             else if(oligo[i] == 'K'){   reverse += 'M'; }
1785             
1786             else if(oligo[i] == 'W'){   reverse += 'W'; }
1787             else if(oligo[i] == 'S'){   reverse += 'S'; }
1788             
1789             else if(oligo[i] == 'B'){   reverse += 'V'; }
1790             else if(oligo[i] == 'V'){   reverse += 'B'; }
1791             
1792             else if(oligo[i] == 'D'){   reverse += 'H'; }
1793             else if(oligo[i] == 'H'){   reverse += 'D'; }
1794             
1795             else                                                {       reverse += 'N'; }
1796         }
1797         
1798         
1799         return reverse;
1800     }
1801         catch(exception& e) {
1802                 m->errorOut(e, "MakeContigsCommand", "reverseOligo");
1803                 exit(1);
1804         }
1805 }
1806 //**********************************************************************************************************************
1807 vector<int> MakeContigsCommand::convertQual(string qual) {
1808         try {
1809                 vector<int> qualScores;
1810         bool negativeScores = false;
1811                 
1812                 for (int i = 0; i < qual.length(); i++) { 
1813             
1814             int temp = 0;
1815             temp = int(qual[i]);
1816             if (format == "illumina") {
1817                 temp -= 64; //char '@'
1818             }else if (format == "illumina1.8+") {
1819                     temp -= int('!'); //char '!'
1820             }else if (format == "solexa") {
1821                 temp = int(convertTable[temp]); //convert to sanger
1822                 temp -= int('!'); //char '!'
1823             }else {
1824                 temp -= int('!'); //char '!'
1825             }
1826             
1827             if (temp < -5) { negativeScores = true; }
1828                         qualScores.push_back(temp);
1829                 }
1830                 
1831         if (negativeScores) { m->mothurOut("[ERROR]: finding negative quality scores, do you have the right format selected? http://en.wikipedia.org/wiki/FASTQ_format#Encoding \n");  m->control_pressed = true;  }
1832         
1833                 return qualScores;
1834         }
1835         catch(exception& e) {
1836                 m->errorOut(e, "MakeContigsCommand", "convertQual");
1837                 exit(1);
1838         }
1839 }
1840
1841 //**********************************************************************************************************************
1842
1843
1844
1845