]> git.donarmstrong.com Git - mothur.git/blob - trimseqscommand.cpp
get.oturep change and trim.seqs fix
[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                 
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                                                                                 
364                 for(int i=0;i<fastaFileNames.size();i++){
365                         
366                         if (m->isBlank(fastaFileNames[i])) {  remove(fastaFileNames[i].c_str());        }
367                         else if (filesToRemove.count(fastaFileNames[i]) > 0) {  remove(fastaFileNames[i].c_str()); }
368                         else {
369                                 ifstream inFASTA;
370                                 string seqName;
371                                 m->openInputFile(fastaFileNames[i], inFASTA);
372                                 ofstream outGroups;
373                                 string outGroupFilename = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "groups";
374                                 m->openOutputFile(outGroupFilename, outGroups);
375                                 outputNames.push_back(outGroupFilename); outputTypes["group"].push_back(outGroupFilename);  
376                                 
377                                 string thisGroup = "";
378                                 if (i > comboStarts) {
379                                         map<string, int>::iterator itCombo;
380                                         for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
381                                                 if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
382                                         }
383                                 }else{ thisGroup = groupVector[i]; }
384                                         
385                                 while(!inFASTA.eof()){
386                                         if(inFASTA.get() == '>'){
387                                                 inFASTA >> seqName;
388                                                 outGroups << seqName << '\t' << thisGroup << endl;
389                                         }
390                                         while (!inFASTA.eof())  {       char c = inFASTA.get(); if (c == 10 || c == 13){        break;  }       }
391                                 }
392                                 outGroups.close();
393                                 inFASTA.close();
394                         }
395                 }
396                 
397                 if(qFileName != ""){
398                         for(int i=0;i<qualFileNames.size();i++){
399                                 if (m->isBlank(qualFileNames[i])) {  remove(qualFileNames[i].c_str());  }
400                                 else if (filesToRemove.count(qualFileNames[i]) > 0) {  remove(qualFileNames[i].c_str()); }
401                                 else {
402                                         ifstream inQual;
403                                         string seqName;
404                                         m->openInputFile(qualFileNames[i], inQual);
405 //                                      ofstream outGroups;
406 //                                      
407 //                                      string thisGroup = "";
408 //                                      if (i > comboStarts) {
409 //                                              map<string, int>::iterator itCombo;
410 //                                              for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
411 //                                                      if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
412 //                                              }
413 //                                      }
414 //                                      else{ thisGroup = groupVector[i]; }
415                                         
416                                         inQual.close();
417                                 }
418                         }
419                 }
420                 
421                 
422                 if (m->control_pressed) { 
423                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
424                         return 0;
425                 }
426
427                 m->mothurOutEndLine();
428                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
429                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
430                 m->mothurOutEndLine();
431                 
432                 return 0;       
433                         
434         }
435         catch(exception& e) {
436                 m->errorOut(e, "TrimSeqsCommand", "execute");
437                 exit(1);
438         }
439 }
440                 
441 /**************************************************************************************/
442
443 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) {      
444                 
445         try {
446                 
447                 ofstream outFASTA;
448                 int able = m->openOutputFile(trimFile, outFASTA);
449                 
450                 ofstream scrapFASTA;
451                 m->openOutputFile(scrapFile, scrapFASTA);
452                 
453                 ofstream outQual;
454                 ofstream scrapQual;
455                 if(qFileName != ""){
456                         m->openOutputFile(trimQFile, outQual);
457                         m->openOutputFile(scrapQFile, scrapQual);
458                 }
459                 
460                 ofstream outGroups;
461                 
462                 if (oligoFile != "") {          
463                         m->openOutputFile(groupFile, outGroups);   
464                 }
465                 
466                 ifstream inFASTA;
467                 m->openInputFile(filename, inFASTA);
468                 inFASTA.seekg(line->start);
469                 
470                 ifstream qFile;
471                 if(qFileName != "")     {       m->openInputFile(qFileName, qFile);     qFile.seekg(qline->start);  }
472                 
473                 
474                 for (int i = 0; i < fastaNames.size(); i++) { //clears old file
475                         ofstream temp;
476                         m->openOutputFile(fastaNames[i], temp);
477                         temp.close();
478                 }
479                 for (int i = 0; i < qualNames.size(); i++) { //clears old file
480                         ofstream temp;
481                         m->openOutputFile(qualNames[i], temp);
482                         temp.close();
483                 }
484                 
485                         
486                 bool done = false;
487                 int count = 0;
488         
489                 while (!done) {
490                                 
491                         if (m->control_pressed) { 
492                                 inFASTA.close(); outFASTA.close(); scrapFASTA.close();
493                                 if (oligoFile != "") {   outGroups.close();   }
494
495                                 if(qFileName != ""){
496                                         qFile.close();
497                                 }
498                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
499
500                                 return 0;
501                         }
502                         
503                         int success = 1;
504                         
505
506                         Sequence currSeq(inFASTA); m->gobble(inFASTA);
507
508                         QualityScores currQual;
509                         if(qFileName != ""){
510                                 currQual = QualityScores(qFile, currSeq.getNumBases());  m->gobble(qFile);
511                         }
512                         
513                         string origSeq = currSeq.getUnaligned();
514                         if (origSeq != "") {
515                                 int groupBar, groupPrime;
516                                 string trashCode = "";
517                                 int currentSeqsDiffs = 0;
518
519                                 if(qFileName != ""){
520                                         if(qThreshold != 0)                     {       success = currQual.stripQualThreshold(currSeq, qThreshold);                     }
521                                         else if(qAverage != 0)          {       success = currQual.cullQualAverage(currSeq, qAverage);                          }
522                                         else if(qRollAverage != 0)      {       success = currQual.stripQualRollingAverage(currSeq, qRollAverage);      }
523                                         else if(qWindowAverage != 0){   success = currQual.stripQualWindowAverage(currSeq, qWindowStep, qWindowSize, qWindowAverage);   }
524
525                                         if (qtrim == 1 && (origSeq.length() != currSeq.getUnaligned().length())) { 
526                                                 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
527                                         }
528
529                                         if(!success)                            {       trashCode += 'q';       }
530                                 }
531                         
532                                 if(barcodes.size() != 0){
533                                         success = stripBarcode(currSeq, currQual, groupBar);
534                                         if(success > bdiffs)            {       trashCode += 'b';       }
535                                         else{ currentSeqsDiffs += success;  }
536                                 }
537
538                                 if(numFPrimers != 0){
539                                         success = stripForward(currSeq, currQual, groupPrime);
540                                         if(success > pdiffs)            {       trashCode += 'f';       }
541                                         else{ currentSeqsDiffs += success;  }
542                                 }
543                                 
544                                 if (currentSeqsDiffs > tdiffs)  {       trashCode += 't';   }
545
546                                 if(numRPrimers != 0){
547                                         success = stripReverse(currSeq, currQual);
548                                         if(!success)                            {       trashCode += 'r';       }
549                                 }
550                 
551                                 if(minLength > 0 || maxLength > 0){
552                                         success = cullLength(currSeq);
553                                         if(!success)                            {       trashCode += 'l';       }
554                                 }
555                                 if(maxHomoP > 0){
556                                         success = cullHomoP(currSeq);
557                                         if(!success)                            {       trashCode += 'h';       }
558                                 }
559                                 if(maxAmbig != -1){
560                                         success = cullAmbigs(currSeq);
561                                         if(!success)                            {       trashCode += 'n';       }
562                                 }
563                                 
564                                 if(flip){       currSeq.reverseComplement();            currQual.flipQScores(); }               // should go last                       
565                                 
566                                 if(trashCode.length() == 0){
567                                         currSeq.setAligned(currSeq.getUnaligned());
568                                         currSeq.printSequence(outFASTA);
569                                         currQual.printQScores(outQual);
570                                         
571                                         if(barcodes.size() != 0){
572                                                 string thisGroup = groupVector[groupBar];
573                                                 int indexToFastaFile = groupBar;
574                                                 if (primers.size() != 0){
575                                                         //does this primer have a group
576                                                         if (groupVector[groupPrime] != "") {  
577                                                                 thisGroup += "." + groupVector[groupPrime]; 
578                                                                 indexToFastaFile = combos[thisGroup];
579                                                         }
580                                                 }
581                                                 outGroups << currSeq.getName() << '\t' << thisGroup << endl;
582                                                 if(allFiles){
583                                                         ofstream outTemp;
584                                                         m->openOutputFileAppend(fastaNames[indexToFastaFile], outTemp);
585                                                         //currSeq.printSequence(*fastaFileNames[indexToFastaFile]);
586                                                         currSeq.printSequence(outTemp);
587                                                         outTemp.close();
588                                                         
589                                                         if(qFileName != ""){
590                                                                 //currQual.printQScores(*qualFileNames[indexToFastaFile]);
591                                                                 ofstream outTemp2;
592                                                                 m->openOutputFileAppend(qualNames[indexToFastaFile], outTemp2);
593                                                                 currQual.printQScores(outTemp2);
594                                                                 outTemp2.close();                                                       
595                                                         }
596                                                 }
597                                         }
598                                         
599                                         if (groupfile != "") {
600                                                 string thisGroup = groupMap->getGroup(currSeq.getName());
601                                                 
602                                                 if (thisGroup != "not found") {
603                                                         outGroups << currSeq.getName() << '\t' << thisGroup << endl;
604                                                         if (allFiles) {
605                                                                 ofstream outTemp;
606                                                                 m->openOutputFileAppend(fastaNames[groupToIndex[thisGroup]], outTemp);
607                                                                 currSeq.printSequence(outTemp);
608                                                                 outTemp.close();
609                                                                 if(qFileName != ""){
610                                                                         ofstream outTemp2;
611                                                                         m->openOutputFileAppend(qualNames[groupToIndex[thisGroup]], outTemp2);
612                                                                         currQual.printQScores(outTemp2);
613                                                                         outTemp2.close();                                                       
614                                                                 }
615                                                         }
616                                                 }else{
617                                                         m->mothurOut(currSeq.getName() + " is not in your groupfile, adding to group XXX."); m->mothurOutEndLine();
618                                                         outGroups << currSeq.getName() << '\t' << "XXX" << endl;
619                                                         if (allFiles) {  
620                                                                 m->mothurOut("[ERROR]: " + currSeq.getName() + " will not be added to any .group.fasta or .group.qual file."); m->mothurOutEndLine();
621                                                         }
622                                                 }
623                                         }
624                                 }
625                                 else{
626                                         currSeq.setName(currSeq.getName() + '|' + trashCode);
627                                         currSeq.setUnaligned(origSeq);
628                                         currSeq.setAligned(origSeq);
629                                         currSeq.printSequence(scrapFASTA);
630                                         currQual.printQScores(scrapQual);
631                                 }
632                                 count++;
633                         }
634                         
635                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
636                                 unsigned long int pos = inFASTA.tellg();
637                                 if ((pos == -1) || (pos >= line->end)) { break; }
638                         #else
639                                 if (inFASTA.eof()) { break; }
640                         #endif
641                                 
642                         //report progress
643                         if((count) % 1000 == 0){        m->mothurOut(toString(count)); m->mothurOutEndLine();           }
644                         
645                 }
646                 //report progress
647                 if((count) % 1000 != 0){        m->mothurOut(toString(count)); m->mothurOutEndLine();           }
648
649                 
650                 inFASTA.close();
651                 outFASTA.close();
652                 scrapFASTA.close();
653                 if (oligoFile != "") {   outGroups.close();   }
654                 if(qFileName != "")     {       qFile.close();  scrapQual.close(); outQual.close();     }
655                 
656                 return count;
657         }
658         catch(exception& e) {
659                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
660                 exit(1);
661         }
662 }
663
664 /**************************************************************************************************/
665
666 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
667         try {
668 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
669                 int process = 1;
670                 int exitCommand = 1;
671                 processIDS.clear();
672                 
673                 //loop through and create all the processes you want
674                 while (process != processors) {
675                         int pid = fork();
676                         
677                         if (pid > 0) {
678                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
679                                 process++;
680                         }else if (pid == 0){
681                                 for (int i = 0; i < fastaNames.size(); i++) {
682                                         fastaNames[i] = (fastaNames[i] + toString(getpid()) + ".temp");
683                                         //clear old file if it exists
684                                         ofstream temp;
685                                         m->openOutputFile(fastaNames[i], temp);
686                                         temp.close();
687                                         if(qFileName != ""){
688                                                 qualNames[i] = (qualNames[i] + toString(getpid()) + ".temp");
689                                                 //clear old file if it exists
690                                                 ofstream temp2;
691                                                 m->openOutputFile(qualNames[i], temp2);
692                                                 temp2.close();
693                                         }
694                                 }
695                                 
696                                 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]);
697                                 exit(0);
698                         }else { 
699                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
700                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
701                                 exit(0);
702                         }
703                 }
704                 
705                 //parent do my part
706                 for (int i = 0; i < fastaNames.size(); i++) {
707                         //clear old file if it exists
708                         ofstream temp;
709                         m->openOutputFile(fastaNames[i], temp);
710                         temp.close();
711                         if(qFileName != ""){
712                                 //clear old file if it exists
713                                 ofstream temp2;
714                                 m->openOutputFile(qualNames[i], temp2);
715                                 temp2.close();
716                         }
717                 }
718                 
719                 driverCreateTrim(filename, qFileName, trimFile, scrapFile, trimQFile, scrapQFile, groupFile, fastaNames, qualNames, lines[0], qLines[0]);
720                 
721                 
722                 //force parent to wait until all the processes are done
723                 for (int i=0;i<processIDS.size();i++) { 
724                         int temp = processIDS[i];
725                         wait(&temp);
726                 }
727                 
728                 //append files
729                 for(int i=0;i<processIDS.size();i++){
730                         m->mothurOut("Appending files from process " + processIDS[i]); m->mothurOutEndLine();
731                         
732                         m->appendFiles((trimFile + toString(processIDS[i]) + ".temp"), trimFile);
733                         remove((trimFile + toString(processIDS[i]) + ".temp").c_str());
734                         m->appendFiles((scrapFile + toString(processIDS[i]) + ".temp"), scrapFile);
735                         remove((scrapFile + toString(processIDS[i]) + ".temp").c_str());
736                         
737                         m->mothurOut("Done with fasta files"); m->mothurOutEndLine();
738                         
739                         if(qFileName != ""){
740                                 m->appendFiles((trimQFile + toString(processIDS[i]) + ".temp"), trimQFile);
741                                 remove((trimQFile + toString(processIDS[i]) + ".temp").c_str());
742                                 m->appendFiles((scrapQFile + toString(processIDS[i]) + ".temp"), scrapQFile);
743                                 remove((scrapQFile + toString(processIDS[i]) + ".temp").c_str());
744                         
745                                 m->mothurOut("Done with quality files"); m->mothurOutEndLine();
746                         }
747                         
748                         m->appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
749                         remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
750                         
751                         m->mothurOut("Done with group file"); m->mothurOutEndLine();
752                         
753                         for (int j = 0; j < fastaNames.size(); j++) {
754                                 m->appendFiles((fastaNames[j] + toString(processIDS[i]) + ".temp"), fastaNames[j]);
755                                 remove((fastaNames[j] + toString(processIDS[i]) + ".temp").c_str());
756                         }
757                         
758                         if(qFileName != ""){
759                                 for (int j = 0; j < qualNames.size(); j++) {
760                                         m->appendFiles((qualNames[j] + toString(processIDS[i]) + ".temp"), qualNames[j]);
761                                         remove((qualNames[j] + toString(processIDS[i]) + ".temp").c_str());
762                                 }
763                         }
764                         
765                         if (allFiles) { m->mothurOut("Done with allfiles"); m->mothurOutEndLine(); }
766                 }
767         
768                 return exitCommand;
769 #endif          
770         }
771         catch(exception& e) {
772                 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
773                 exit(1);
774         }
775 }
776
777 /**************************************************************************************************/
778
779 int TrimSeqsCommand::setLines(string filename, string qfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos) {
780         try {
781                 
782                 //set file positions for fasta file
783                 fastaFilePos = m->divideFile(filename, processors);
784                 
785                 if (qfilename == "") { return processors; }
786                 
787                 //get name of first sequence in each chunk
788                 map<string, int> firstSeqNames;
789                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
790                         ifstream in;
791                         m->openInputFile(filename, in);
792                         in.seekg(fastaFilePos[i]);
793                 
794                         Sequence temp(in); 
795                         firstSeqNames[temp.getName()] = i;
796                 
797                         in.close();
798                 }
799                                 
800                 //seach for filePos of each first name in the qfile and save in qfileFilePos
801                 ifstream inQual;
802                 m->openInputFile(qfilename, inQual);
803                 
804                 string input;
805                 while(!inQual.eof()){   
806                         input = m->getline(inQual);
807
808                         if (input.length() != 0) {
809                                 if(input[0] == '>'){ //this is a sequence name line
810                                         istringstream nameStream(input);
811                                         
812                                         string sname = "";  nameStream >> sname;
813                                         sname = sname.substr(1);
814                                         
815                                         map<string, int>::iterator it = firstSeqNames.find(sname);
816                                         
817                                         if(it != firstSeqNames.end()) { //this is the start of a new chunk
818                                                 unsigned long int pos = inQual.tellg(); 
819                                                 qfileFilePos.push_back(pos - input.length() - 1);       
820                                                 firstSeqNames.erase(it);
821                                         }
822                                 }
823                         }
824                         
825                         if (firstSeqNames.size() == 0) { break; }
826                 }
827                 inQual.close();
828                 
829                 
830                 if (firstSeqNames.size() != 0) { 
831                         for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
832                                 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
833                         }
834                         qFileName = "";
835                         return processors;
836                 }
837
838                 //get last file position of qfile
839                 FILE * pFile;
840                 unsigned long int size;
841                 
842                 //get num bytes in file
843                 pFile = fopen (qfilename.c_str(),"rb");
844                 if (pFile==NULL) perror ("Error opening file");
845                 else{
846                         fseek (pFile, 0, SEEK_END);
847                         size=ftell (pFile);
848                         fclose (pFile);
849                 }
850                 
851                 qfileFilePos.push_back(size);
852                 
853                 return processors;
854         }
855         catch(exception& e) {
856                 m->errorOut(e, "TrimSeqsCommand", "setLines");
857                 exit(1);
858         }
859 }
860 //***************************************************************************************************************
861
862 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
863         try {
864                 ifstream inOligos;
865                 m->openInputFile(oligoFile, inOligos);
866                 
867                 ofstream test;
868                 
869                 string type, oligo, group;
870                 int index=0;
871                 //int indexPrimer = 0;
872                 
873                 while(!inOligos.eof()){
874                         inOligos >> type; m->gobble(inOligos);
875                                         
876                         if(type[0] == '#'){
877                                 while (!inOligos.eof()) {       char c = inOligos.get(); if (c == 10 || c == 13){       break;  }       } // get rest of line if there's any crap there
878                         }
879                         else{
880                                 //make type case insensitive
881                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }
882                                 
883                                 inOligos >> oligo;
884                                 
885                                 for(int i=0;i<oligo.length();i++){
886                                         oligo[i] = toupper(oligo[i]);
887                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
888                                 }
889                                 
890                                 if(type == "FORWARD"){
891                                         group = "";
892                                         
893                                         // get rest of line in case there is a primer name
894                                         while (!inOligos.eof()) {       
895                                                 char c = inOligos.get(); 
896                                                 if (c == 10 || c == 13){        break;  }
897                                                 else if (c == 32 || c == 9){;} //space or tab
898                                                 else {  group += c;  }
899                                         } 
900                                         
901                                         //check for repeat barcodes
902                                         map<string, int>::iterator itPrime = primers.find(oligo);
903                                         if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
904                                         
905                                                 primers[oligo]=index; index++;
906                                                 groupVector.push_back(group);
907                                         
908                                                 if(allFiles){
909                                                         outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
910                                                         if(qFileName != ""){
911                                                                 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
912                                                         }
913                                                         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
914                                                                 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
915                                                                 if(qFileName != ""){
916                                                                         filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
917                                                                 }
918                                                         }else {
919                                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
920                                                                 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
921                                                                 if(qFileName != ""){
922                                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
923                                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
924                                                                 }                                                       
925                                                         }
926                                                 }
927                                         
928                                 }
929                                 else if(type == "REVERSE"){
930                                         Sequence oligoRC("reverse", oligo);
931                                         oligoRC.reverseComplement();
932                                         revPrimer.push_back(oligoRC.getUnaligned());
933                                 }
934                                 else if(type == "BARCODE"){
935                                         inOligos >> group;
936                                         
937                                         //check for repeat barcodes
938                                         map<string, int>::iterator itBar = barcodes.find(oligo);
939                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
940                                         
941                                                 barcodes[oligo]=index; index++;
942                                                 groupVector.push_back(group);
943                                                 
944                                                 if(allFiles){
945                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
946                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
947                                                         outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
948                                                         if(qFileName != ""){
949                                                                 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
950                                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
951                                                                 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
952                                                         }                                                       
953                                                 }
954                                         
955                                 }else{  m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  }
956                         }
957                         m->gobble(inOligos);
958                 }
959                 
960                 inOligos.close();
961                 
962                 //add in potential combos
963                 if(allFiles){
964                         comboStarts = outFASTAVec.size()-1;
965                         for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
966                                 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
967                                         if (groupVector[itPrime->second] != "") { //there is a group for this primer
968                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
969                                                 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
970                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
971                                                 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
972                                                 
973                                                 if(qFileName != ""){
974                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
975                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
976                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
977                                                 }
978                                         }
979                                 }
980                         }
981                 }
982                 
983                 numFPrimers = primers.size();
984                 numRPrimers = revPrimer.size();
985                 
986         }
987         catch(exception& e) {
988                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
989                 exit(1);
990         }
991 }
992 //***************************************************************************************************************
993
994 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
995         try {
996                 
997                 string rawSequence = seq.getUnaligned();
998                 int success = bdiffs + 1;       //guilty until proven innocent
999                 
1000                 //can you find the barcode
1001                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
1002                         string oligo = it->first;
1003                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
1004                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
1005                                 break;  
1006                         }
1007                         
1008                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1009                                 group = it->second;
1010                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
1011                                 
1012                                 if(qual.getName() != ""){
1013                                         qual.trimQScores(oligo.length(), -1);
1014                                 }
1015                                 
1016                                 success = 0;
1017                                 break;
1018                         }
1019                 }
1020                 
1021                 //if you found the barcode or if you don't want to allow for diffs
1022 //              cout << success;
1023                 if ((bdiffs == 0) || (success == 0)) { return success;  }
1024                 
1025                 else { //try aligning and see if you can find it
1026 //                      cout << endl;
1027
1028                         int maxLength = 0;
1029
1030                         Alignment* alignment;
1031                         if (barcodes.size() > 0) {
1032                                 map<string,int>::iterator it=barcodes.begin();
1033
1034                                 for(it;it!=barcodes.end();it++){
1035                                         if(it->first.length() > maxLength){
1036                                                 maxLength = it->first.length();
1037                                         }
1038                                 }
1039                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
1040
1041                         }else{ alignment = NULL; } 
1042                         
1043                         //can you find the barcode
1044                         int minDiff = 1e6;
1045                         int minCount = 1;
1046                         int minGroup = -1;
1047                         int minPos = 0;
1048                         
1049                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
1050                                 string oligo = it->first;
1051 //                              int length = oligo.length();
1052                                 
1053                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
1054                                         success = bdiffs + 10;
1055                                         break;
1056                                 }
1057                                 
1058                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1059                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
1060                                 oligo = alignment->getSeqAAln();
1061                                 string temp = alignment->getSeqBAln();
1062                 
1063                                 int alnLength = oligo.length();
1064                                 
1065                                 for(int i=oligo.length()-1;i>=0;i--){
1066                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1067                                 }
1068                                 oligo = oligo.substr(0,alnLength);
1069                                 temp = temp.substr(0,alnLength);
1070                                 
1071                                 int newStart=0;
1072                                 int numDiff = countDiffs(oligo, temp);
1073                                 
1074 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1075                                 
1076                                 if(numDiff < minDiff){
1077                                         minDiff = numDiff;
1078                                         minCount = 1;
1079                                         minGroup = it->second;
1080                                         minPos = 0;
1081                                         for(int i=0;i<alnLength;i++){
1082                                                 if(temp[i] != '-'){
1083                                                         minPos++;
1084                                                 }
1085                                         }
1086                                 }
1087                                 else if(numDiff == minDiff){
1088                                         minCount++;
1089                                 }
1090
1091                         }
1092
1093                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
1094                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
1095                         else{                                                                                                   //use the best match
1096                                 group = minGroup;
1097                                 seq.setUnaligned(rawSequence.substr(minPos));
1098                                 
1099                                 if(qual.getName() != ""){
1100                                         qual.trimQScores(minPos, -1);
1101                                 }
1102                                 success = minDiff;
1103                         }
1104                         
1105                         if (alignment != NULL) {  delete alignment;  }
1106                         
1107                 }
1108 //              cout << success << endl;
1109                 
1110                 return success;
1111                 
1112         }
1113         catch(exception& e) {
1114                 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
1115                 exit(1);
1116         }
1117
1118 }
1119
1120 //***************************************************************************************************************
1121
1122 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
1123         try {
1124                 string rawSequence = seq.getUnaligned();
1125                 int success = pdiffs + 1;       //guilty until proven innocent
1126                 
1127                 //can you find the primer
1128                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1129                         string oligo = it->first;
1130                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
1131                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
1132                                 break;  
1133                         }
1134                         
1135                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1136                                 group = it->second;
1137                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
1138                                 if(qual.getName() != ""){
1139                                         qual.trimQScores(oligo.length(), -1);
1140                                         
1141                                 }
1142                                 success = 0;
1143                                 break;
1144                         }
1145                 }
1146
1147                 //if you found the barcode or if you don't want to allow for diffs
1148 //              cout << success;
1149                 if ((pdiffs == 0) || (success == 0)) { return success;  }
1150                 
1151                 else { //try aligning and see if you can find it
1152 //                      cout << endl;
1153
1154                         int maxLength = 0;
1155
1156                         Alignment* alignment;
1157                         if (primers.size() > 0) {
1158                                 map<string,int>::iterator it=primers.begin();
1159
1160                                 for(it;it!=primers.end();it++){
1161                                         if(it->first.length() > maxLength){
1162                                                 maxLength = it->first.length();
1163                                         }
1164                                 }
1165                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
1166
1167                         }else{ alignment = NULL; } 
1168                         
1169                         //can you find the barcode
1170                         int minDiff = 1e6;
1171                         int minCount = 1;
1172                         int minGroup = -1;
1173                         int minPos = 0;
1174                         
1175                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1176                                 string oligo = it->first;
1177 //                              int length = oligo.length();
1178                                 
1179                                 if(rawSequence.length() < maxLength){   
1180                                         success = pdiffs + 100;
1181                                         break;
1182                                 }
1183                                 
1184                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1185                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1186                                 oligo = alignment->getSeqAAln();
1187                                 string temp = alignment->getSeqBAln();
1188                 
1189                                 int alnLength = oligo.length();
1190                                 
1191                                 for(int i=oligo.length()-1;i>=0;i--){
1192                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1193                                 }
1194                                 oligo = oligo.substr(0,alnLength);
1195                                 temp = temp.substr(0,alnLength);
1196                                 
1197                                 int newStart=0;
1198                                 int numDiff = countDiffs(oligo, temp);
1199                                 
1200 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1201                                 
1202                                 if(numDiff < minDiff){
1203                                         minDiff = numDiff;
1204                                         minCount = 1;
1205                                         minGroup = it->second;
1206                                         minPos = 0;
1207                                         for(int i=0;i<alnLength;i++){
1208                                                 if(temp[i] != '-'){
1209                                                         minPos++;
1210                                                 }
1211                                         }
1212                                 }
1213                                 else if(numDiff == minDiff){
1214                                         minCount++;
1215                                 }
1216
1217                         }
1218
1219                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
1220                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
1221                         else{                                                                                                   //use the best match
1222                                 group = minGroup;
1223                                 seq.setUnaligned(rawSequence.substr(minPos));
1224                                 if(qual.getName() != ""){
1225                                         qual.trimQScores(minPos, -1);
1226                                 }
1227                                 success = minDiff;
1228                         }
1229                         
1230                         if (alignment != NULL) {  delete alignment;  }
1231                         
1232                 }
1233                 
1234                 return success;
1235
1236         }
1237         catch(exception& e) {
1238                 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1239                 exit(1);
1240         }
1241 }
1242
1243 //***************************************************************************************************************
1244
1245 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1246         try {
1247                 string rawSequence = seq.getUnaligned();
1248                 bool success = 0;       //guilty until proven innocent
1249                 
1250                 for(int i=0;i<numRPrimers;i++){
1251                         string oligo = revPrimer[i];
1252                         
1253                         if(rawSequence.length() < oligo.length()){
1254                                 success = 0;
1255                                 break;
1256                         }
1257                         
1258                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1259                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1260                                 if(qual.getName() != ""){
1261                                         qual.trimQScores(-1, rawSequence.length()-oligo.length());
1262                                 }
1263                                 success = 1;
1264                                 break;
1265                         }
1266                 }       
1267                 return success;
1268                 
1269         }
1270         catch(exception& e) {
1271                 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1272                 exit(1);
1273         }
1274 }
1275
1276 //***************************************************************************************************************
1277
1278 bool TrimSeqsCommand::cullLength(Sequence& seq){
1279         try {
1280         
1281                 int length = seq.getNumBases();
1282                 bool success = 0;       //guilty until proven innocent
1283                 
1284                 if(length >= minLength && maxLength == 0)                       {       success = 1;    }
1285                 else if(length >= minLength && length <= maxLength)     {       success = 1;    }
1286                 else                                                                                            {       success = 0;    }
1287                 
1288                 return success;
1289         
1290         }
1291         catch(exception& e) {
1292                 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1293                 exit(1);
1294         }
1295         
1296 }
1297
1298 //***************************************************************************************************************
1299
1300 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1301         try {
1302                 int longHomoP = seq.getLongHomoPolymer();
1303                 bool success = 0;       //guilty until proven innocent
1304                 
1305                 if(longHomoP <= maxHomoP){      success = 1;    }
1306                 else                                    {       success = 0;    }
1307                 
1308                 return success;
1309         }
1310         catch(exception& e) {
1311                 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1312                 exit(1);
1313         }
1314         
1315 }
1316
1317 //***************************************************************************************************************
1318
1319 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1320         try {
1321                 int numNs = seq.getAmbigBases();
1322                 bool success = 0;       //guilty until proven innocent
1323                 
1324                 if(numNs <= maxAmbig)   {       success = 1;    }
1325                 else                                    {       success = 0;    }
1326                 
1327                 return success;
1328         }
1329         catch(exception& e) {
1330                 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1331                 exit(1);
1332         }
1333         
1334 }
1335
1336 //***************************************************************************************************************
1337
1338 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1339         try {
1340                 bool success = 1;
1341                 int length = oligo.length();
1342                 
1343                 for(int i=0;i<length;i++){
1344                         
1345                         if(oligo[i] != seq[i]){
1346                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
1347                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
1348                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
1349                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
1350                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
1351                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
1352                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
1353                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
1354                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1355                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1356                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
1357                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
1358                                 
1359                                 if(success == 0)        {       break;   }
1360                         }
1361                         else{
1362                                 success = 1;
1363                         }
1364                 }
1365                 
1366                 return success;
1367         }
1368         catch(exception& e) {
1369                 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1370                 exit(1);
1371         }
1372
1373 }
1374 //***************************************************************************************************************
1375
1376 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1377         try {
1378
1379                 int length = oligo.length();
1380                 int countDiffs = 0;
1381                 
1382                 for(int i=0;i<length;i++){
1383                                                                 
1384                         if(oligo[i] != seq[i]){
1385                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
1386                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
1387                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
1388                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
1389                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
1390                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
1391                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
1392                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
1393                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1394                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1395                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
1396                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }       
1397                         }
1398                         
1399                 }
1400                 
1401                 return countDiffs;
1402         }
1403         catch(exception& e) {
1404                 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1405                 exit(1);
1406         }
1407
1408 }
1409 //***************************************************************************************************************
1410
1411 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1412 //      try {
1413 //              
1414 //              string rawSequence = seq.getUnaligned();
1415 //              int seqLength = seq.getNumBases();
1416 //              bool success = 0;       //guilty until proven innocent
1417 //              string name;
1418 //              
1419 //              qFile >> name;
1420 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1421 //              
1422 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1423 //              
1424 //              int score;
1425 //              int end = seqLength;
1426 //              
1427 //              for(int i=0;i<seqLength;i++){
1428 //                      qFile >> score;
1429 //                      
1430 //                      if(score < qThreshold){
1431 //                              end = i;
1432 //                              break;
1433 //                      }
1434 //              }
1435 //              for(int i=end+1;i<seqLength;i++){
1436 //                      qFile >> score;
1437 //              }
1438 //              
1439 //              seq.setUnaligned(rawSequence.substr(0,end));
1440 //              
1441 //              return 1;
1442 //      }
1443 //      catch(exception& e) {
1444 //              m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1445 //              exit(1);
1446 //      }
1447 //}
1448
1449 //***************************************************************************************************************
1450
1451 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1452 //      try {
1453 //              string rawSequence = seq.getUnaligned();
1454 //              int seqLength = seq.getNumBases();
1455 //              bool success = 0;       //guilty until proven innocent
1456 //              string name;
1457 //              
1458 //              qFile >> name;
1459 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1460 //              
1461 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1462 //              
1463 //              float score;    
1464 //              float average = 0;
1465 //              
1466 //              for(int i=0;i<seqLength;i++){
1467 //                      qFile >> score;
1468 //                      average += score;
1469 //              }
1470 //              average /= seqLength;
1471 //
1472 //              if(average >= qAverage) {       success = 1;    }
1473 //              else                                    {       success = 0;    }
1474 //              
1475 //              return success;
1476 //      }
1477 //      catch(exception& e) {
1478 //              m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1479 //              exit(1);
1480 //      }
1481 //}
1482
1483 //***************************************************************************************************************