]> git.donarmstrong.com Git - mothur.git/blob - trimseqscommand.cpp
modified trim.seqs to speed up the append with multiple processors
[mothur.git] / trimseqscommand.cpp
1 /*
2  *  trimseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 6/6/09.
6  *  Copyright 2009 Patrick D. Schloss. All rights reserved.
7  *
8  */
9
10 #include "trimseqscommand.h"
11 #include "needlemanoverlap.hpp"
12
13 //**********************************************************************************************************************
14 vector<string> TrimSeqsCommand::getValidParameters(){   
15         try {
16                 string Array[] =  {"fasta", "flip", "oligos", "maxambig", "maxhomop", "group","minlength", "maxlength", "qfile", 
17                                                                         "qthreshold", "qwindowaverage", "qstepsize", "qwindowsize", "qaverage", "rollaverage", "allfiles", "qtrim","tdiffs", "pdiffs", "bdiffs", "processors", "outputdir","inputdir"};
18                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
19                 return myArray;
20         }
21         catch(exception& e) {
22                 m->errorOut(e, "TrimSeqsCommand", "getValidParameters");
23                 exit(1);
24         }
25 }
26 //**********************************************************************************************************************
27 TrimSeqsCommand::TrimSeqsCommand(){     
28         try {
29                 abort = true;
30                 //initialize outputTypes
31                 vector<string> tempOutNames;
32                 outputTypes["fasta"] = tempOutNames;
33                 outputTypes["qual"] = tempOutNames;
34                 outputTypes["group"] = tempOutNames;
35         }
36         catch(exception& e) {
37                 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
38                 exit(1);
39         }
40 }
41 //**********************************************************************************************************************
42 vector<string> TrimSeqsCommand::getRequiredParameters(){        
43         try {
44                 string Array[] =  {"fasta"};
45                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
46                 return myArray;
47         }
48         catch(exception& e) {
49                 m->errorOut(e, "TrimSeqsCommand", "getRequiredParameters");
50                 exit(1);
51         }
52 }
53 //**********************************************************************************************************************
54 vector<string> TrimSeqsCommand::getRequiredFiles(){     
55         try {
56                 vector<string> myArray;
57                 return myArray;
58         }
59         catch(exception& e) {
60                 m->errorOut(e, "TrimSeqsCommand", "getRequiredFiles");
61                 exit(1);
62         }
63 }
64 //***************************************************************************************************************
65
66 TrimSeqsCommand::TrimSeqsCommand(string option)  {
67         try {
68                 
69                 abort = false;
70                 comboStarts = 0;
71                 
72                 //allow user to run help
73                 if(option == "help") { help(); abort = true; }
74                 
75                 else {
76                         //valid paramters for this command
77                         string AlignArray[] =  {"fasta", "flip", "group","oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile", 
78                                                                         "qthreshold", "qwindowaverage", "qstepsize", "qwindowsize", "qaverage", "rollaverage", "allfiles", "qtrim","tdiffs", "pdiffs", "bdiffs", "processors", "outputdir","inputdir"};
79                         
80                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
81                         
82                         OptionParser parser(option);
83                         map<string,string> parameters = parser.getParameters();
84                         
85                         ValidParameters validParameter;
86                         map<string,string>::iterator it;
87                         
88                         //check to make sure all parameters are valid for command
89                         for (it = parameters.begin(); it != parameters.end(); it++) { 
90                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
91                         }
92                         
93                         //initialize outputTypes
94                         vector<string> tempOutNames;
95                         outputTypes["fasta"] = tempOutNames;
96                         outputTypes["qual"] = tempOutNames;
97                         outputTypes["group"] = tempOutNames;
98                         
99                         //if the user changes the input directory command factory will send this info to us in the output parameter 
100                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
101                         if (inputDir == "not found"){   inputDir = "";          }
102                         else {
103                                 string path;
104                                 it = parameters.find("fasta");
105                                 //user has given a template file
106                                 if(it != parameters.end()){ 
107                                         path = m->hasPath(it->second);
108                                         //if the user has not given a path then, add inputdir. else leave path alone.
109                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
110                                 }
111                                 
112                                 it = parameters.find("oligos");
113                                 //user has given a template file
114                                 if(it != parameters.end()){ 
115                                         path = m->hasPath(it->second);
116                                         //if the user has not given a path then, add inputdir. else leave path alone.
117                                         if (path == "") {       parameters["oligos"] = inputDir + it->second;           }
118                                 }
119                                 
120                                 it = parameters.find("qfile");
121                                 //user has given a template file
122                                 if(it != parameters.end()){ 
123                                         path = m->hasPath(it->second);
124                                         //if the user has not given a path then, add inputdir. else leave path alone.
125                                         if (path == "") {       parameters["qfile"] = inputDir + it->second;            }
126                                 }
127                                 
128                                 it = parameters.find("group");
129                                 //user has given a template file
130                                 if(it != parameters.end()){ 
131                                         path = m->hasPath(it->second);
132                                         //if the user has not given a path then, add inputdir. else leave path alone.
133                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
134                                 }
135                         }
136
137                         
138                         //check for required parameters
139                         fastaFile = validParameter.validFile(parameters, "fasta", true);
140                         if (fastaFile == "not found") { m->mothurOut("fasta is a required parameter for the trim.seqs command."); m->mothurOutEndLine(); abort = true; }
141                         else if (fastaFile == "not open") { abort = true; }     
142                         
143                         //if the user changes the output directory command factory will send this info to us in the output parameter 
144                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
145                                 outputDir = ""; 
146                                 outputDir += m->hasPath(fastaFile); //if user entered a file with a path then preserve it       
147                         }
148                 
149                         
150                         //check for optional parameter and set defaults
151                         // ...at some point should added some additional type checking...
152                         string temp;
153                         temp = validParameter.validFile(parameters, "flip", false);
154                         if (temp == "not found"){       flip = 0;       }
155                         else if(m->isTrue(temp))        {       flip = 1;       }
156                 
157                         temp = validParameter.validFile(parameters, "oligos", true);
158                         if (temp == "not found"){       oligoFile = "";         }
159                         else if(temp == "not open"){    abort = true;   } 
160                         else                                    {       oligoFile = temp;               }
161                         
162                         temp = validParameter.validFile(parameters, "group", true);
163                         if (temp == "not found"){       groupfile = "";         }
164                         else if(temp == "not open"){    abort = true;   } 
165                         else                                    {       groupfile = temp;               }
166                         
167                         temp = validParameter.validFile(parameters, "maxambig", false);         if (temp == "not found") { temp = "-1"; }
168                         convert(temp, maxAmbig);  
169
170                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found") { temp = "0"; }
171                         convert(temp, maxHomoP);  
172
173                         temp = validParameter.validFile(parameters, "minlength", false);        if (temp == "not found") { temp = "0"; }
174                         convert(temp, minLength); 
175                         
176                         temp = validParameter.validFile(parameters, "maxlength", false);        if (temp == "not found") { temp = "0"; }
177                         convert(temp, maxLength);
178                         
179                         temp = validParameter.validFile(parameters, "bdiffs", false);           if (temp == "not found") { temp = "0"; }
180                         convert(temp, bdiffs);
181                         
182                         temp = validParameter.validFile(parameters, "pdiffs", false);           if (temp == "not found") { temp = "0"; }
183                         convert(temp, pdiffs);
184                         
185                         temp = validParameter.validFile(parameters, "tdiffs", false);           if (temp == "not found") { int tempTotal = pdiffs + bdiffs;  temp = toString(tempTotal); }
186                         convert(temp, tdiffs);
187                         
188                         if(tdiffs == 0){        tdiffs = bdiffs + pdiffs;       }
189                         
190                         temp = validParameter.validFile(parameters, "qfile", true);     
191                         if (temp == "not found")        {       qFileName = "";         }
192                         else if(temp == "not open")     {       abort = true;           }
193                         else                                            {       qFileName = temp;       }
194                         
195                         temp = validParameter.validFile(parameters, "qthreshold", false);       if (temp == "not found") { temp = "0"; }
196                         convert(temp, qThreshold);
197                         
198                         temp = validParameter.validFile(parameters, "qtrim", false);            if (temp == "not found") { temp = "F"; }
199                         qtrim = m->isTrue(temp);
200
201                         temp = validParameter.validFile(parameters, "rollaverage", false);      if (temp == "not found") { temp = "0"; }
202                         convert(temp, qRollAverage);
203
204                         temp = validParameter.validFile(parameters, "qwindowaverage", false);if (temp == "not found") { temp = "0"; }
205                         convert(temp, qWindowAverage);
206
207                         temp = validParameter.validFile(parameters, "qwindowsize", false);      if (temp == "not found") { temp = "100"; }
208                         convert(temp, qWindowSize);
209
210                         temp = validParameter.validFile(parameters, "qstepsize", false);                if (temp == "not found") { temp = "10"; }
211                         convert(temp, qWindowStep);
212
213                         temp = validParameter.validFile(parameters, "qaverage", false);         if (temp == "not found") { temp = "0"; }
214                         convert(temp, qAverage);
215                         
216                         temp = validParameter.validFile(parameters, "allfiles", false);         if (temp == "not found") { temp = "F"; }
217                         allFiles = m->isTrue(temp);
218                         
219                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found") { temp = "1"; }
220                         convert(temp, processors); 
221                         
222                         if ((oligoFile != "") && (groupfile != "")) {
223                                 m->mothurOut("You given both a oligos file and a groupfile, only one is allowed."); m->mothurOutEndLine(); abort = true;
224                         }
225                                                                                                 
226                         
227                         if(allFiles && (oligoFile == "") && (groupfile == "")){
228                                 m->mothurOut("You selected allfiles, but didn't enter an oligos or group file.  Ignoring the allfiles request."); m->mothurOutEndLine();
229                         }
230                         if((qAverage != 0 && qThreshold != 0) && qFileName == ""){
231                                 m->mothurOut("You didn't provide a quality file name, quality criteria will be ignored."); m->mothurOutEndLine();
232                                 qAverage=0;
233                                 qThreshold=0;
234                         }
235                         if(!flip && oligoFile=="" && !maxLength && !minLength && (maxAmbig==-1) && !maxHomoP && qFileName == ""){               
236                                 m->mothurOut("You didn't set any options... quiting command."); m->mothurOutEndLine();
237                                 abort = true;
238                         }
239                 }
240
241         }
242         catch(exception& e) {
243                 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
244                 exit(1);
245         }
246 }
247 //**********************************************************************************************************************
248
249 void TrimSeqsCommand::help(){
250         try {
251                 m->mothurOut("The trim.seqs command reads a fastaFile and creates .....\n");
252                 m->mothurOut("The trim.seqs command parameters are fasta, flip, oligos, group, maxambig, maxhomop, minlength, maxlength, qfile, qthreshold, qaverage, diffs, qtrim and allfiles.\n");
253                 m->mothurOut("The fasta parameter is required.\n");
254                 m->mothurOut("The group parameter allows you to enter a group file for your fasta file.\n");
255                 m->mothurOut("The flip parameter will output the reverse compliment of your trimmed sequence. The default is false.\n");
256                 m->mothurOut("The oligos parameter .... The default is "".\n");
257                 m->mothurOut("The maxambig parameter .... The default is -1.\n");
258                 m->mothurOut("The maxhomop parameter .... The default is 0.\n");
259                 m->mothurOut("The minlength parameter .... The default is 0.\n");
260                 m->mothurOut("The maxlength parameter .... The default is 0.\n");
261                 m->mothurOut("The tdiffs parameter is used to specify the total number of differences allowed in the sequence. The default is pdiffs + bdiffs.\n");
262                 m->mothurOut("The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n");
263                 m->mothurOut("The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n");
264                 m->mothurOut("The qfile parameter .....\n");
265                 m->mothurOut("The qthreshold parameter .... The default is 0.\n");
266                 m->mothurOut("The qaverage parameter .... The default is 0.\n");
267                 m->mothurOut("The allfiles parameter .... The default is F.\n");
268                 m->mothurOut("The qtrim parameter .... The default is F.\n");
269                 m->mothurOut("The trim.seqs command should be in the following format: \n");
270                 m->mothurOut("trim.seqs(fasta=yourFastaFile, flip=yourFlip, oligos=yourOligos, maxambig=yourMaxambig,  \n");
271                 m->mothurOut("maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength)  \n");    
272                 m->mothurOut("Example trim.seqs(fasta=abrecovery.fasta, flip=..., oligos=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n");
273                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
274                 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.seqs .\n\n");
275
276         }
277         catch(exception& e) {
278                 m->errorOut(e, "TrimSeqsCommand", "help");
279                 exit(1);
280         }
281 }
282
283
284 //***************************************************************************************************************
285
286 TrimSeqsCommand::~TrimSeqsCommand(){    /*      do nothing      */      }
287
288 //***************************************************************************************************************
289
290 int TrimSeqsCommand::execute(){
291         try{
292         
293                 if (abort == true) { return 0; }
294                 
295                 numFPrimers = 0;  //this needs to be initialized
296                 numRPrimers = 0;
297                 vector<string> fastaFileNames;
298                 vector<string> qualFileNames;
299                 
300                 string trimSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.fasta";
301                 outputNames.push_back(trimSeqFile); outputTypes["fasta"].push_back(trimSeqFile);
302                 string scrapSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.fasta";
303                 outputNames.push_back(scrapSeqFile); outputTypes["fasta"].push_back(scrapSeqFile);
304                 string trimQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.qual";
305                 string scrapQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.qual";
306                 if (qFileName != "") {  outputNames.push_back(trimQualFile); outputNames.push_back(scrapQualFile);  outputTypes["qual"].push_back(trimQualFile); outputTypes["qual"].push_back(scrapQualFile); }
307                 string groupFile = "";
308                 if (groupfile == "") { groupFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "groups"; }
309                 else{
310                         groupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "trim.groups";
311                         outputNames.push_back(groupFile); outputTypes["group"].push_back(groupFile);
312                         groupMap = new GroupMap(groupfile);
313                         groupMap->readMap();
314                         
315                         if(allFiles){
316                                 for (int i = 0; i < groupMap->namesOfGroups.size(); i++) {
317                                         groupToIndex[groupMap->namesOfGroups[i]] = i;
318                                         groupVector.push_back(groupMap->namesOfGroups[i]);
319                                         fastaFileNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) +  groupMap->namesOfGroups[i] + ".fasta"));
320                                         
321                                         //we append later, so we want to clear file
322                                         ofstream outRemove;
323                                         m->openOutputFile(fastaFileNames[i], outRemove);
324                                         outRemove.close();
325                                         if(qFileName != ""){
326                                                 qualFileNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) +  groupMap->namesOfGroups[i] + ".qual"));
327                                                 ofstream outRemove2;
328                                                 m->openOutputFile(qualFileNames[i], outRemove2);
329                                                 outRemove2.close();
330                                         }
331                                 }
332                         }
333                         comboStarts = fastaFileNames.size()-1;
334                 }
335                 
336                 if(oligoFile != ""){
337                         outputNames.push_back(groupFile); outputTypes["group"].push_back(groupFile);
338                         getOligos(fastaFileNames, qualFileNames);
339                 }
340                 cout << fastaFileNames.size() << '\t' << qualFileNames.size() << endl;
341                 vector<unsigned long int> fastaFilePos;
342                 vector<unsigned long int> qFilePos;
343                 
344                 setLines(fastaFile, qFileName, fastaFilePos, qFilePos);
345                 
346                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
347                         lines.push_back(new linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
348                         if (qFileName != "") {  qLines.push_back(new linePair(qFilePos[i], qFilePos[(i+1)]));  }
349                 }       
350                 if(qFileName == "")     {       qLines = lines; } //files with duds
351                 
352                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
353                                 if(processors == 1){
354                                         driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
355                                 }else{
356                                         createProcessesCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames); 
357                                 }       
358                 #else
359                                 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
360                 #endif
361                 
362                 if (m->control_pressed) {  return 0; }                  
363                 cout << "done with driver " << endl;                                                                    
364                 for(int i=0;i<fastaFileNames.size();i++){
365                         cout << fastaFileNames[i] << endl;
366                         
367                         if (m->isBlank(fastaFileNames[i])) { cout << fastaFileNames[i] << " was blank" << endl; remove(fastaFileNames[i].c_str());      }
368                         else if (filesToRemove.count(fastaFileNames[i]) > 0) { cout << fastaFileNames[i] << " was on the remove list" << endl; remove(fastaFileNames[i].c_str()); }
369                         else {
370                                 ifstream inFASTA;
371                                 string seqName;
372                                 m->openInputFile(fastaFileNames[i], inFASTA);
373                                 ofstream outGroups;
374                                 string outGroupFilename = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "groups";
375                                 m->openOutputFile(outGroupFilename, outGroups);
376                                 outputNames.push_back(outGroupFilename); outputTypes["group"].push_back(outGroupFilename);  
377                                 
378                                 string thisGroup = "";
379                                 if (i > comboStarts) {
380                                         map<string, int>::iterator itCombo;
381                                         for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
382                                                 if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
383                                         }
384                                 }else{ thisGroup = groupVector[i]; }
385                                 cout << thisGroup << '\t' << i  << '\t' << comboStarts << endl; 
386                                 while(!inFASTA.eof()){
387                                         if(inFASTA.get() == '>'){
388                                                 inFASTA >> seqName;
389                                                 outGroups << seqName << '\t' << thisGroup << endl;
390                                         }
391                                         while (!inFASTA.eof())  {       char c = inFASTA.get(); if (c == 10 || c == 13){        break;  }       }
392                                 }
393                                 outGroups.close();
394                                 inFASTA.close();
395                         }
396                 }
397         cout << "done with fastaFileNames " << endl;            
398                 if(qFileName != ""){
399                         for(int i=0;i<qualFileNames.size();i++){
400                                 cout << qualFileNames[i] << endl;
401                                 if (m->isBlank(qualFileNames[i])) { cout << qualFileNames[i] << " was blank" << endl; remove(qualFileNames[i].c_str()); }
402                                 else if (filesToRemove.count(qualFileNames[i]) > 0) { cout << qualFileNames[i] << " was on the remove list" << endl; remove(qualFileNames[i].c_str()); }
403                                 else {
404                                         ifstream inQual;
405                                         string seqName;
406                                         m->openInputFile(qualFileNames[i], inQual);
407 //                                      ofstream outGroups;
408 //                                      
409 //                                      string thisGroup = "";
410 //                                      if (i > comboStarts) {
411 //                                              map<string, int>::iterator itCombo;
412 //                                              for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
413 //                                                      if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
414 //                                              }
415 //                                      }
416 //                                      else{ thisGroup = groupVector[i]; }
417                                         
418                                         inQual.close();
419                                 }
420                         }
421                 }
422                 cout << "done with qualFileNames " << endl;
423                 
424                 if (m->control_pressed) { 
425                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
426                         return 0;
427                 }
428
429                 m->mothurOutEndLine();
430                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
431                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
432                 m->mothurOutEndLine();
433                 
434                 return 0;       
435                         
436         }
437         catch(exception& e) {
438                 m->errorOut(e, "TrimSeqsCommand", "execute");
439                 exit(1);
440         }
441 }
442                 
443 /**************************************************************************************/
444
445 int TrimSeqsCommand::driverCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames, linePair* line, linePair* qline) {      
446                 
447         try {
448                 
449                 ofstream outFASTA;
450                 int able = m->openOutputFile(trimFile, outFASTA);
451                 
452                 ofstream scrapFASTA;
453                 m->openOutputFile(scrapFile, scrapFASTA);
454                 
455                 ofstream outQual;
456                 ofstream scrapQual;
457                 if(qFileName != ""){
458                         m->openOutputFile(trimQFile, outQual);
459                         m->openOutputFile(scrapQFile, scrapQual);
460                 }
461                 
462                 ofstream outGroups;
463                 //vector<ofstream*> fastaFileNames;
464                 //vector<ofstream*> qualFileNames;
465                 
466                 if (oligoFile != "") {          
467                         m->openOutputFile(groupFile, outGroups);   
468                 }
469                 
470                 ifstream inFASTA;
471                 m->openInputFile(filename, inFASTA);
472                 inFASTA.seekg(line->start);
473                 
474                 ifstream qFile;
475                 if(qFileName != "")     {       m->openInputFile(qFileName, qFile);     qFile.seekg(qline->start);  }
476                 
477                 bool done = false;
478                 int count = 0;
479         
480                 while (!done) {
481                                 
482                         if (m->control_pressed) { 
483                                 inFASTA.close(); outFASTA.close(); scrapFASTA.close();
484                                 if (oligoFile != "") {   outGroups.close();   }
485
486                                 if(qFileName != ""){
487                                         qFile.close();
488                                 }
489                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
490
491                                 return 0;
492                         }
493                         
494                         int success = 1;
495                         
496
497                         Sequence currSeq(inFASTA); m->gobble(inFASTA);
498
499                         QualityScores currQual;
500                         if(qFileName != ""){
501                                 currQual = QualityScores(qFile, currSeq.getNumBases());  m->gobble(qFile);
502                         }
503                         
504                         string origSeq = currSeq.getUnaligned();
505                         if (origSeq != "") {
506                                 int groupBar, groupPrime;
507                                 string trashCode = "";
508                                 int currentSeqsDiffs = 0;
509
510                                 if(qFileName != ""){
511                                         if(qThreshold != 0)                     {       success = currQual.stripQualThreshold(currSeq, qThreshold);                     }
512                                         else if(qAverage != 0)          {       success = currQual.cullQualAverage(currSeq, qAverage);                          }
513                                         else if(qRollAverage != 0)      {       success = currQual.stripQualRollingAverage(currSeq, qRollAverage);      }
514                                         else if(qWindowAverage != 0){   success = currQual.stripQualWindowAverage(currSeq, qWindowStep, qWindowSize, qWindowAverage);   }
515
516                                         if (qtrim == 1 && (origSeq.length() != currSeq.getUnaligned().length())) { 
517                                                 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
518                                         }
519
520                                         if(!success)                            {       trashCode += 'q';       }
521                                 }
522                         
523                                 if(barcodes.size() != 0){
524                                         success = stripBarcode(currSeq, currQual, groupBar);
525                                         if(success > bdiffs)            {       trashCode += 'b';       }
526                                         else{ currentSeqsDiffs += success;  }
527                                 }
528
529                                 if(numFPrimers != 0){
530                                         success = stripForward(currSeq, currQual, groupPrime);
531                                         if(success > pdiffs)            {       trashCode += 'f';       }
532                                         else{ currentSeqsDiffs += success;  }
533                                 }
534                                 
535                                 if (currentSeqsDiffs > tdiffs)  {       trashCode += 't';   }
536
537                                 if(numRPrimers != 0){
538                                         success = stripReverse(currSeq, currQual);
539                                         if(!success)                            {       trashCode += 'r';       }
540                                 }
541                 
542                                 if(minLength > 0 || maxLength > 0){
543                                         success = cullLength(currSeq);
544                                         if(!success)                            {       trashCode += 'l';       }
545                                 }
546                                 if(maxHomoP > 0){
547                                         success = cullHomoP(currSeq);
548                                         if(!success)                            {       trashCode += 'h';       }
549                                 }
550                                 if(maxAmbig != -1){
551                                         success = cullAmbigs(currSeq);
552                                         if(!success)                            {       trashCode += 'n';       }
553                                 }
554                                 
555                                 if(flip){       currSeq.reverseComplement();            currQual.flipQScores(); }               // should go last                       
556                                 
557                                 if(trashCode.length() == 0){
558                                         currSeq.setAligned(currSeq.getUnaligned());
559                                         currSeq.printSequence(outFASTA);
560                                         currQual.printQScores(outQual);
561                                         
562                                         if(barcodes.size() != 0){
563                                                 string thisGroup = groupVector[groupBar];
564                                                 int indexToFastaFile = groupBar;
565                                                 if (primers.size() != 0){
566                                                         //does this primer have a group
567                                                         if (groupVector[groupPrime] != "") {  
568                                                                 thisGroup += "." + groupVector[groupPrime]; 
569                                                                 indexToFastaFile = combos[thisGroup];
570                                                         }
571                                                 }
572                                                 outGroups << currSeq.getName() << '\t' << thisGroup << endl;
573                                                 if(allFiles){
574                                                         ofstream outTemp;
575                                                         m->openOutputFileAppend(fastaNames[indexToFastaFile], outTemp);
576                                                         //currSeq.printSequence(*fastaFileNames[indexToFastaFile]);
577                                                         currSeq.printSequence(outTemp);
578                                                         outTemp.close();
579                                                         
580                                                         if(qFileName != ""){
581                                                                 //currQual.printQScores(*qualFileNames[indexToFastaFile]);
582                                                                 ofstream outTemp2;
583                                                                 m->openOutputFileAppend(qualNames[indexToFastaFile], outTemp2);
584                                                                 currQual.printQScores(outTemp2);
585                                                                 outTemp2.close();                                                       
586                                                         }
587                                                 }
588                                         }
589                                         
590                                         if (groupfile != "") {
591                                                 string thisGroup = groupMap->getGroup(currSeq.getName());
592                                                 
593                                                 if (thisGroup != "not found") {
594                                                         outGroups << currSeq.getName() << '\t' << thisGroup << endl;
595                                                         if (allFiles) {
596                                                                 ofstream outTemp;
597                                                                 m->openOutputFileAppend(fastaNames[groupToIndex[thisGroup]], outTemp);
598                                                                 currSeq.printSequence(outTemp);
599                                                                 outTemp.close();
600                                                                 if(qFileName != ""){
601                                                                         ofstream outTemp2;
602                                                                         m->openOutputFileAppend(qualNames[groupToIndex[thisGroup]], outTemp2);
603                                                                         currQual.printQScores(outTemp2);
604                                                                         outTemp2.close();                                                       
605                                                                 }
606                                                         }
607                                                 }else{
608                                                         m->mothurOut(currSeq.getName() + " is not in your groupfile, adding to group XXX."); m->mothurOutEndLine();
609                                                         outGroups << currSeq.getName() << '\t' << "XXX" << endl;
610                                                         if (allFiles) {  
611                                                                 m->mothurOut("[ERROR]: " + currSeq.getName() + " will not be added to any .group.fasta or .group.qual file."); m->mothurOutEndLine();
612                                                         }
613                                                 }
614                                         }
615                                 }
616                                 else{
617                                         currSeq.setName(currSeq.getName() + '|' + trashCode);
618                                         currSeq.setUnaligned(origSeq);
619                                         currSeq.setAligned(origSeq);
620                                         currSeq.printSequence(scrapFASTA);
621                                         currQual.printQScores(scrapQual);
622                                 }
623                                 count++;
624                         }
625                         
626                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
627                                 unsigned long int pos = inFASTA.tellg();
628                                 if ((pos == -1) || (pos >= line->end)) { break; }
629                         #else
630                                 if (inFASTA.eof()) { break; }
631                         #endif
632                                 
633                         //report progress
634                         if((count) % 1000 == 0){        m->mothurOut(toString(count)); m->mothurOutEndLine();           }
635                         
636                 }
637                 //report progress
638                 if((count) % 1000 != 0){        m->mothurOut(toString(count)); m->mothurOutEndLine();           }
639
640                 
641                 inFASTA.close();
642                 outFASTA.close();
643                 scrapFASTA.close();
644                 if (oligoFile != "") {   outGroups.close();   }
645                 if(qFileName != "")     {       qFile.close();  scrapQual.close(); outQual.close();     }
646                 
647                 return count;
648         }
649         catch(exception& e) {
650                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
651                 exit(1);
652         }
653 }
654
655 /**************************************************************************************************/
656
657 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
658         try {
659 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
660                 int process = 1;
661                 int exitCommand = 1;
662                 processIDS.clear();
663                 
664                 //loop through and create all the processes you want
665                 while (process != processors) {
666                         int pid = fork();
667                         
668                         if (pid > 0) {
669                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
670                                 process++;
671                         }else if (pid == 0){
672                                 for (int i = 0; i < fastaNames.size(); i++) {
673                                         fastaNames[i] = (fastaNames[i] + toString(getpid()) + ".temp");
674                                         //clear old file if it exists
675                                         ofstream temp;
676                                         m->openOutputFile(fastaNames[i], temp);
677                                         temp.close();
678                                         if(qFileName != ""){
679                                                 qualNames[i] = (qualNames[i] + toString(getpid()) + ".temp");
680                                                 //clear old file if it exists
681                                                 ofstream temp2;
682                                                 m->openOutputFile(qualNames[i], temp2);
683                                                 temp2.close();
684                                         }
685                                 }
686                                 
687                                 driverCreateTrim(filename, qFileName, (trimFile + toString(getpid()) + ".temp"), (scrapFile + toString(getpid()) + ".temp"), (trimQFile + toString(getpid()) + ".temp"), (scrapQFile + toString(getpid()) + ".temp"), (groupFile + toString(getpid()) + ".temp"), fastaNames, qualNames, lines[process], qLines[process]);
688                                 exit(0);
689                         }else { 
690                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
691                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
692                                 exit(0);
693                         }
694                 }
695                 
696                 //parent do my part
697                 for (int i = 0; i < fastaNames.size(); i++) {
698                         //clear old file if it exists
699                         ofstream temp;
700                         m->openOutputFile(fastaNames[i], temp);
701                         temp.close();
702                         if(qFileName != ""){
703                                 //clear old file if it exists
704                                 ofstream temp2;
705                                 m->openOutputFile(qualNames[i], temp2);
706                                 temp2.close();
707                         }
708                 }
709                 
710                 driverCreateTrim(filename, qFileName, trimFile, scrapFile, trimQFile, scrapQFile, groupFile, fastaNames, qualNames, lines[0], qLines[0]);
711                 
712                 
713                 //force parent to wait until all the processes are done
714                 for (int i=0;i<processIDS.size();i++) { 
715                         int temp = processIDS[i];
716                         wait(&temp);
717                 }
718                 
719                 //append files
720                 for(int i=0;i<processIDS.size();i++){
721                         m->mothurOut("Appending files from process " + processIDS[i]); m->mothurOutEndLine();
722                         
723                         m->appendFiles((trimFile + toString(processIDS[i]) + ".temp"), trimFile);
724                         remove((trimFile + toString(processIDS[i]) + ".temp").c_str());
725                         m->appendFiles((scrapFile + toString(processIDS[i]) + ".temp"), scrapFile);
726                         remove((scrapFile + toString(processIDS[i]) + ".temp").c_str());
727                         
728                         m->mothurOut("Done with fasta files"); m->mothurOutEndLine();
729                         
730                         if(qFileName != ""){
731                                 m->appendFiles((trimQFile + toString(processIDS[i]) + ".temp"), trimQFile);
732                                 remove((trimQFile + toString(processIDS[i]) + ".temp").c_str());
733                                 m->appendFiles((scrapQFile + toString(processIDS[i]) + ".temp"), scrapQFile);
734                                 remove((scrapQFile + toString(processIDS[i]) + ".temp").c_str());
735                         
736                                 m->mothurOut("Done with quality files"); m->mothurOutEndLine();
737                         }
738                         
739                         m->appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
740                         remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
741                         
742                         m->mothurOut("Done with group file"); m->mothurOutEndLine();
743                         
744                         for (int j = 0; j < fastaNames.size(); j++) {
745                                 m->appendFiles((fastaNames[j] + toString(processIDS[i]) + ".temp"), fastaNames[j]);
746                                 remove((fastaNames[j] + toString(processIDS[i]) + ".temp").c_str());
747                         }
748                         
749                         if(qFileName != ""){
750                                 for (int j = 0; j < qualNames.size(); j++) {
751                                         m->appendFiles((qualNames[j] + toString(processIDS[i]) + ".temp"), qualNames[j]);
752                                         remove((qualNames[j] + toString(processIDS[i]) + ".temp").c_str());
753                                 }
754                         }
755                         
756                         if (allFiles) { m->mothurOut("Done with allfile"); m->mothurOutEndLine(); }
757                 }
758         
759                 return exitCommand;
760 #endif          
761         }
762         catch(exception& e) {
763                 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
764                 exit(1);
765         }
766 }
767
768 /**************************************************************************************************/
769
770 int TrimSeqsCommand::setLines(string filename, string qfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos) {
771         try {
772                 
773                 //set file positions for fasta file
774                 fastaFilePos = m->divideFile(filename, processors);
775                 
776                 if (qfilename == "") { return processors; }
777                 
778                 //get name of first sequence in each chunk
779                 map<string, int> firstSeqNames;
780                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
781                         ifstream in;
782                         m->openInputFile(filename, in);
783                         in.seekg(fastaFilePos[i]);
784                 
785                         Sequence temp(in); 
786                         firstSeqNames[temp.getName()] = i;
787                 
788                         in.close();
789                 }
790                                 
791                 //seach for filePos of each first name in the qfile and save in qfileFilePos
792                 ifstream inQual;
793                 m->openInputFile(qfilename, inQual);
794                 
795                 string input;
796                 while(!inQual.eof()){   
797                         input = m->getline(inQual);
798
799                         if (input.length() != 0) {
800                                 if(input[0] == '>'){ //this is a sequence name line
801                                         istringstream nameStream(input);
802                                         
803                                         string sname = "";  nameStream >> sname;
804                                         sname = sname.substr(1);
805                                         
806                                         map<string, int>::iterator it = firstSeqNames.find(sname);
807                                         
808                                         if(it != firstSeqNames.end()) { //this is the start of a new chunk
809                                                 unsigned long int pos = inQual.tellg(); 
810                                                 qfileFilePos.push_back(pos - input.length() - 1);       
811                                                 firstSeqNames.erase(it);
812                                         }
813                                 }
814                         }
815                         
816                         if (firstSeqNames.size() == 0) { break; }
817                 }
818                 inQual.close();
819                 
820                 
821                 if (firstSeqNames.size() != 0) { 
822                         for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
823                                 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
824                         }
825                         qFileName = "";
826                         return processors;
827                 }
828
829                 //get last file position of qfile
830                 FILE * pFile;
831                 unsigned long int size;
832                 
833                 //get num bytes in file
834                 pFile = fopen (qfilename.c_str(),"rb");
835                 if (pFile==NULL) perror ("Error opening file");
836                 else{
837                         fseek (pFile, 0, SEEK_END);
838                         size=ftell (pFile);
839                         fclose (pFile);
840                 }
841                 
842                 qfileFilePos.push_back(size);
843                 
844                 return processors;
845         }
846         catch(exception& e) {
847                 m->errorOut(e, "TrimSeqsCommand", "setLines");
848                 exit(1);
849         }
850 }
851 //***************************************************************************************************************
852
853 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
854         try {
855                 ifstream inOligos;
856                 m->openInputFile(oligoFile, inOligos);
857                 
858                 ofstream test;
859                 
860                 string type, oligo, group;
861                 int index=0;
862                 //int indexPrimer = 0;
863                 
864                 while(!inOligos.eof()){
865                         inOligos >> type;
866                                         
867                         if(type[0] == '#'){
868                                 while (!inOligos.eof()) {       char c = inOligos.get(); if (c == 10 || c == 13){       break;  }       } // get rest of line if there's any crap there
869                         }
870                         else{
871                                 //make type case insensitive
872                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }
873                                 
874                                 inOligos >> oligo;
875                                 
876                                 for(int i=0;i<oligo.length();i++){
877                                         oligo[i] = toupper(oligo[i]);
878                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
879                                 }
880                                 
881                                 if(type == "FORWARD"){
882                                         group = "";
883                                         
884                                         // get rest of line in case there is a primer name
885                                         while (!inOligos.eof()) {       
886                                                 char c = inOligos.get(); 
887                                                 if (c == 10 || c == 13){        break;  }
888                                                 else if (c == 32 || c == 9){;} //space or tab
889                                                 else {  group += c;  }
890                                         } 
891                                         
892                                         //check for repeat barcodes
893                                         map<string, int>::iterator itPrime = primers.find(oligo);
894                                         if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
895                                         
896                                         primers[oligo]=index; index++;
897                                         groupVector.push_back(group);
898                                         
899                                         if(allFiles){
900                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
901                                                 if(qFileName != ""){
902                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
903                                                 }
904                                                 if (group == "") { //if there is not a group for this primer, then this file will not get written to, but we add it to keep the indexes correct
905                                                         filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
906                                                         if(qFileName != ""){
907                                                                 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
908                                                         }
909                                                 }else {
910                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
911                                                         outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
912                                                         if(qFileName != ""){
913                                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
914                                                                 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
915                                                         }                                                       
916                                                 }
917                                         }
918
919                                 }
920                                 else if(type == "REVERSE"){
921                                         Sequence oligoRC("reverse", oligo);
922                                         oligoRC.reverseComplement();
923                                         revPrimer.push_back(oligoRC.getUnaligned());
924                                 }
925                                 else if(type == "BARCODE"){
926                                         inOligos >> group;
927                                         
928                                         //check for repeat barcodes
929                                         map<string, int>::iterator itBar = barcodes.find(oligo);
930                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
931                                         
932                                         barcodes[oligo]=index; index++;
933                                         groupVector.push_back(group);
934                                         
935                                         if(allFiles){
936                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
937                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
938                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
939                                                 if(qFileName != ""){
940                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
941                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
942                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
943                                                 }                                                       
944                                         }
945                                 }else{  m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  }
946                         }
947                         m->gobble(inOligos);
948                 }
949                 
950                 inOligos.close();
951                 
952                 //add in potential combos
953                 if(allFiles){
954                         comboStarts = outFASTAVec.size()-1;
955                         for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
956                                 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
957                                         if (groupVector[itPrime->second] != "") { //there is a group for this primer
958                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
959                                                 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
960                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
961                                                 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
962                                                 
963                                                 if(qFileName != ""){
964                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
965                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
966                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
967                                                 }
968                                         }
969                                 }
970                         }
971                 }
972                 
973                 numFPrimers = primers.size();
974                 numRPrimers = revPrimer.size();
975                 
976         }
977         catch(exception& e) {
978                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
979                 exit(1);
980         }
981 }
982 //***************************************************************************************************************
983
984 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
985         try {
986                 
987                 string rawSequence = seq.getUnaligned();
988                 int success = bdiffs + 1;       //guilty until proven innocent
989                 
990                 //can you find the barcode
991                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
992                         string oligo = it->first;
993                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
994                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
995                                 break;  
996                         }
997                         
998                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
999                                 group = it->second;
1000                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
1001                                 
1002                                 if(qual.getName() != ""){
1003                                         qual.trimQScores(oligo.length(), -1);
1004                                 }
1005                                 
1006                                 success = 0;
1007                                 break;
1008                         }
1009                 }
1010                 
1011                 //if you found the barcode or if you don't want to allow for diffs
1012 //              cout << success;
1013                 if ((bdiffs == 0) || (success == 0)) { return success;  }
1014                 
1015                 else { //try aligning and see if you can find it
1016 //                      cout << endl;
1017
1018                         int maxLength = 0;
1019
1020                         Alignment* alignment;
1021                         if (barcodes.size() > 0) {
1022                                 map<string,int>::iterator it=barcodes.begin();
1023
1024                                 for(it;it!=barcodes.end();it++){
1025                                         if(it->first.length() > maxLength){
1026                                                 maxLength = it->first.length();
1027                                         }
1028                                 }
1029                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
1030
1031                         }else{ alignment = NULL; } 
1032                         
1033                         //can you find the barcode
1034                         int minDiff = 1e6;
1035                         int minCount = 1;
1036                         int minGroup = -1;
1037                         int minPos = 0;
1038                         
1039                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
1040                                 string oligo = it->first;
1041 //                              int length = oligo.length();
1042                                 
1043                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
1044                                         success = bdiffs + 10;
1045                                         break;
1046                                 }
1047                                 
1048                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1049                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
1050                                 oligo = alignment->getSeqAAln();
1051                                 string temp = alignment->getSeqBAln();
1052                 
1053                                 int alnLength = oligo.length();
1054                                 
1055                                 for(int i=oligo.length()-1;i>=0;i--){
1056                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1057                                 }
1058                                 oligo = oligo.substr(0,alnLength);
1059                                 temp = temp.substr(0,alnLength);
1060                                 
1061                                 int newStart=0;
1062                                 int numDiff = countDiffs(oligo, temp);
1063                                 
1064 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1065                                 
1066                                 if(numDiff < minDiff){
1067                                         minDiff = numDiff;
1068                                         minCount = 1;
1069                                         minGroup = it->second;
1070                                         minPos = 0;
1071                                         for(int i=0;i<alnLength;i++){
1072                                                 if(temp[i] != '-'){
1073                                                         minPos++;
1074                                                 }
1075                                         }
1076                                 }
1077                                 else if(numDiff == minDiff){
1078                                         minCount++;
1079                                 }
1080
1081                         }
1082
1083                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
1084                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
1085                         else{                                                                                                   //use the best match
1086                                 group = minGroup;
1087                                 seq.setUnaligned(rawSequence.substr(minPos));
1088                                 
1089                                 if(qual.getName() != ""){
1090                                         qual.trimQScores(minPos, -1);
1091                                 }
1092                                 success = minDiff;
1093                         }
1094                         
1095                         if (alignment != NULL) {  delete alignment;  }
1096                         
1097                 }
1098 //              cout << success << endl;
1099                 
1100                 return success;
1101                 
1102         }
1103         catch(exception& e) {
1104                 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
1105                 exit(1);
1106         }
1107
1108 }
1109
1110 //***************************************************************************************************************
1111
1112 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
1113         try {
1114                 string rawSequence = seq.getUnaligned();
1115                 int success = pdiffs + 1;       //guilty until proven innocent
1116                 
1117                 //can you find the primer
1118                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1119                         string oligo = it->first;
1120                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
1121                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
1122                                 break;  
1123                         }
1124                         
1125                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1126                                 group = it->second;
1127                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
1128                                 if(qual.getName() != ""){
1129                                         qual.trimQScores(oligo.length(), -1);
1130                                         
1131                                 }
1132                                 success = 0;
1133                                 break;
1134                         }
1135                 }
1136
1137                 //if you found the barcode or if you don't want to allow for diffs
1138 //              cout << success;
1139                 if ((pdiffs == 0) || (success == 0)) { return success;  }
1140                 
1141                 else { //try aligning and see if you can find it
1142 //                      cout << endl;
1143
1144                         int maxLength = 0;
1145
1146                         Alignment* alignment;
1147                         if (primers.size() > 0) {
1148                                 map<string,int>::iterator it=primers.begin();
1149
1150                                 for(it;it!=primers.end();it++){
1151                                         if(it->first.length() > maxLength){
1152                                                 maxLength = it->first.length();
1153                                         }
1154                                 }
1155                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
1156
1157                         }else{ alignment = NULL; } 
1158                         
1159                         //can you find the barcode
1160                         int minDiff = 1e6;
1161                         int minCount = 1;
1162                         int minGroup = -1;
1163                         int minPos = 0;
1164                         
1165                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1166                                 string oligo = it->first;
1167 //                              int length = oligo.length();
1168                                 
1169                                 if(rawSequence.length() < maxLength){   
1170                                         success = pdiffs + 100;
1171                                         break;
1172                                 }
1173                                 
1174                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1175                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1176                                 oligo = alignment->getSeqAAln();
1177                                 string temp = alignment->getSeqBAln();
1178                 
1179                                 int alnLength = oligo.length();
1180                                 
1181                                 for(int i=oligo.length()-1;i>=0;i--){
1182                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1183                                 }
1184                                 oligo = oligo.substr(0,alnLength);
1185                                 temp = temp.substr(0,alnLength);
1186                                 
1187                                 int newStart=0;
1188                                 int numDiff = countDiffs(oligo, temp);
1189                                 
1190 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1191                                 
1192                                 if(numDiff < minDiff){
1193                                         minDiff = numDiff;
1194                                         minCount = 1;
1195                                         minGroup = it->second;
1196                                         minPos = 0;
1197                                         for(int i=0;i<alnLength;i++){
1198                                                 if(temp[i] != '-'){
1199                                                         minPos++;
1200                                                 }
1201                                         }
1202                                 }
1203                                 else if(numDiff == minDiff){
1204                                         minCount++;
1205                                 }
1206
1207                         }
1208
1209                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
1210                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
1211                         else{                                                                                                   //use the best match
1212                                 group = minGroup;
1213                                 seq.setUnaligned(rawSequence.substr(minPos));
1214                                 if(qual.getName() != ""){
1215                                         qual.trimQScores(minPos, -1);
1216                                 }
1217                                 success = minDiff;
1218                         }
1219                         
1220                         if (alignment != NULL) {  delete alignment;  }
1221                         
1222                 }
1223                 
1224                 return success;
1225
1226         }
1227         catch(exception& e) {
1228                 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1229                 exit(1);
1230         }
1231 }
1232
1233 //***************************************************************************************************************
1234
1235 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1236         try {
1237                 string rawSequence = seq.getUnaligned();
1238                 bool success = 0;       //guilty until proven innocent
1239                 
1240                 for(int i=0;i<numRPrimers;i++){
1241                         string oligo = revPrimer[i];
1242                         
1243                         if(rawSequence.length() < oligo.length()){
1244                                 success = 0;
1245                                 break;
1246                         }
1247                         
1248                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1249                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1250                                 if(qual.getName() != ""){
1251                                         qual.trimQScores(-1, rawSequence.length()-oligo.length());
1252                                 }
1253                                 success = 1;
1254                                 break;
1255                         }
1256                 }       
1257                 return success;
1258                 
1259         }
1260         catch(exception& e) {
1261                 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1262                 exit(1);
1263         }
1264 }
1265
1266 //***************************************************************************************************************
1267
1268 bool TrimSeqsCommand::cullLength(Sequence& seq){
1269         try {
1270         
1271                 int length = seq.getNumBases();
1272                 bool success = 0;       //guilty until proven innocent
1273                 
1274                 if(length >= minLength && maxLength == 0)                       {       success = 1;    }
1275                 else if(length >= minLength && length <= maxLength)     {       success = 1;    }
1276                 else                                                                                            {       success = 0;    }
1277                 
1278                 return success;
1279         
1280         }
1281         catch(exception& e) {
1282                 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1283                 exit(1);
1284         }
1285         
1286 }
1287
1288 //***************************************************************************************************************
1289
1290 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1291         try {
1292                 int longHomoP = seq.getLongHomoPolymer();
1293                 bool success = 0;       //guilty until proven innocent
1294                 
1295                 if(longHomoP <= maxHomoP){      success = 1;    }
1296                 else                                    {       success = 0;    }
1297                 
1298                 return success;
1299         }
1300         catch(exception& e) {
1301                 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1302                 exit(1);
1303         }
1304         
1305 }
1306
1307 //***************************************************************************************************************
1308
1309 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1310         try {
1311                 int numNs = seq.getAmbigBases();
1312                 bool success = 0;       //guilty until proven innocent
1313                 
1314                 if(numNs <= maxAmbig)   {       success = 1;    }
1315                 else                                    {       success = 0;    }
1316                 
1317                 return success;
1318         }
1319         catch(exception& e) {
1320                 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1321                 exit(1);
1322         }
1323         
1324 }
1325
1326 //***************************************************************************************************************
1327
1328 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1329         try {
1330                 bool success = 1;
1331                 int length = oligo.length();
1332                 
1333                 for(int i=0;i<length;i++){
1334                         
1335                         if(oligo[i] != seq[i]){
1336                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
1337                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
1338                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
1339                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
1340                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
1341                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
1342                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
1343                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
1344                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1345                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1346                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
1347                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
1348                                 
1349                                 if(success == 0)        {       break;   }
1350                         }
1351                         else{
1352                                 success = 1;
1353                         }
1354                 }
1355                 
1356                 return success;
1357         }
1358         catch(exception& e) {
1359                 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1360                 exit(1);
1361         }
1362
1363 }
1364 //***************************************************************************************************************
1365
1366 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1367         try {
1368
1369                 int length = oligo.length();
1370                 int countDiffs = 0;
1371                 
1372                 for(int i=0;i<length;i++){
1373                                                                 
1374                         if(oligo[i] != seq[i]){
1375                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
1376                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
1377                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
1378                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
1379                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
1380                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
1381                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
1382                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
1383                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1384                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1385                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
1386                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }       
1387                         }
1388                         
1389                 }
1390                 
1391                 return countDiffs;
1392         }
1393         catch(exception& e) {
1394                 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1395                 exit(1);
1396         }
1397
1398 }
1399 //***************************************************************************************************************
1400
1401 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1402 //      try {
1403 //              
1404 //              string rawSequence = seq.getUnaligned();
1405 //              int seqLength = seq.getNumBases();
1406 //              bool success = 0;       //guilty until proven innocent
1407 //              string name;
1408 //              
1409 //              qFile >> name;
1410 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1411 //              
1412 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1413 //              
1414 //              int score;
1415 //              int end = seqLength;
1416 //              
1417 //              for(int i=0;i<seqLength;i++){
1418 //                      qFile >> score;
1419 //                      
1420 //                      if(score < qThreshold){
1421 //                              end = i;
1422 //                              break;
1423 //                      }
1424 //              }
1425 //              for(int i=end+1;i<seqLength;i++){
1426 //                      qFile >> score;
1427 //              }
1428 //              
1429 //              seq.setUnaligned(rawSequence.substr(0,end));
1430 //              
1431 //              return 1;
1432 //      }
1433 //      catch(exception& e) {
1434 //              m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1435 //              exit(1);
1436 //      }
1437 //}
1438
1439 //***************************************************************************************************************
1440
1441 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1442 //      try {
1443 //              string rawSequence = seq.getUnaligned();
1444 //              int seqLength = seq.getNumBases();
1445 //              bool success = 0;       //guilty until proven innocent
1446 //              string name;
1447 //              
1448 //              qFile >> name;
1449 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1450 //              
1451 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1452 //              
1453 //              float score;    
1454 //              float average = 0;
1455 //              
1456 //              for(int i=0;i<seqLength;i++){
1457 //                      qFile >> score;
1458 //                      average += score;
1459 //              }
1460 //              average /= seqLength;
1461 //
1462 //              if(average >= qAverage) {       success = 1;    }
1463 //              else                                    {       success = 0;    }
1464 //              
1465 //              return success;
1466 //      }
1467 //      catch(exception& e) {
1468 //              m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1469 //              exit(1);
1470 //      }
1471 //}
1472
1473 //***************************************************************************************************************