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