]> git.donarmstrong.com Git - mothur.git/blob - trimseqscommand.cpp
4e7a12994f4854c487d036dd422aa1f3130e288c
[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                 
788                 if (firstSeqNames.size() != 0) { 
789                         for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
790                                 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
791                         }
792                         qFileName = "";
793                         return processors;
794                 }
795
796                 //get last file position of qfile
797                 FILE * pFile;
798                 unsigned long int size;
799                 
800                 //get num bytes in file
801                 pFile = fopen (qfilename.c_str(),"rb");
802                 if (pFile==NULL) perror ("Error opening file");
803                 else{
804                         fseek (pFile, 0, SEEK_END);
805                         size=ftell (pFile);
806                         fclose (pFile);
807                 }
808                 
809                 qfileFilePos.push_back(size);
810                 
811                 return processors;
812         }
813         catch(exception& e) {
814                 m->errorOut(e, "TrimSeqsCommand", "setLines");
815                 exit(1);
816         }
817 }
818 //***************************************************************************************************************
819
820 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
821         try {
822                 ifstream inOligos;
823                 m->openInputFile(oligoFile, inOligos);
824                 
825                 ofstream test;
826                 
827                 string type, oligo, group;
828                 int index=0;
829                 //int indexPrimer = 0;
830                 
831                 while(!inOligos.eof()){
832                         inOligos >> type;
833                                         
834                         if(type[0] == '#'){
835                                 while (!inOligos.eof()) {       char c = inOligos.get(); if (c == 10 || c == 13){       break;  }       } // get rest of line if there's any crap there
836                         }
837                         else{
838                                 //make type case insensitive
839                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }
840                                 
841                                 inOligos >> oligo;
842                                 
843                                 for(int i=0;i<oligo.length();i++){
844                                         oligo[i] = toupper(oligo[i]);
845                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
846                                 }
847                                 
848                                 if(type == "FORWARD"){
849                                         group = "";
850                                         
851                                         // get rest of line in case there is a primer name
852                                         while (!inOligos.eof()) {       
853                                                 char c = inOligos.get(); 
854                                                 if (c == 10 || c == 13){        break;  }
855                                                 else if (c == 32 || c == 9){;} //space or tab
856                                                 else {  group += c;  }
857                                         } 
858                                         
859                                         //check for repeat barcodes
860                                         map<string, int>::iterator itPrime = primers.find(oligo);
861                                         if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
862                                         
863                                         primers[oligo]=index; index++;
864                                         groupVector.push_back(group);
865                                         
866                                         if(allFiles){
867                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
868                                                 if(qFileName != ""){
869                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
870                                                 }
871                                                 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
872                                                         filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
873                                                         if(qFileName != ""){
874                                                                 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
875                                                         }
876                                                 }else {
877                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
878                                                         outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
879                                                         if(qFileName != ""){
880                                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
881                                                                 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
882                                                         }                                                       
883                                                 }
884                                         }
885
886                                 }
887                                 else if(type == "REVERSE"){
888                                         Sequence oligoRC("reverse", oligo);
889                                         oligoRC.reverseComplement();
890                                         revPrimer.push_back(oligoRC.getUnaligned());
891                                 }
892                                 else if(type == "BARCODE"){
893                                         inOligos >> group;
894                                         
895                                         //check for repeat barcodes
896                                         map<string, int>::iterator itBar = barcodes.find(oligo);
897                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
898                                         
899                                         barcodes[oligo]=index; index++;
900                                         groupVector.push_back(group);
901                                         
902                                         if(allFiles){
903                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
904                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
905                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
906                                                 if(qFileName != ""){
907                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
908                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
909                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
910                                                 }                                                       
911                                         }
912                                 }else{  m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  }
913                         }
914                         m->gobble(inOligos);
915                 }
916                 
917                 inOligos.close();
918                 
919                 //add in potential combos
920                 if(allFiles){
921                         comboStarts = outFASTAVec.size()-1;
922                         for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
923                                 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
924                                         if (groupVector[itPrime->second] != "") { //there is a group for this primer
925                                                 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
926                                                 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
927                                                 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
928                                                 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
929                                                 
930                                                 if(qFileName != ""){
931                                                         outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
932                                                         outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
933                                                         outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
934                                                 }
935                                         }
936                                 }
937                         }
938                 }
939                 
940                 numFPrimers = primers.size();
941                 numRPrimers = revPrimer.size();
942                 
943         }
944         catch(exception& e) {
945                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
946                 exit(1);
947         }
948 }
949 //***************************************************************************************************************
950
951 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
952         try {
953                 
954                 string rawSequence = seq.getUnaligned();
955                 int success = bdiffs + 1;       //guilty until proven innocent
956                 
957                 //can you find the barcode
958                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
959                         string oligo = it->first;
960                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
961                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
962                                 break;  
963                         }
964                         
965                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
966                                 group = it->second;
967                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
968                                 
969                                 if(qual.getName() != ""){
970                                         qual.trimQScores(oligo.length(), -1);
971                                 }
972                                 
973                                 success = 0;
974                                 break;
975                         }
976                 }
977                 
978                 //if you found the barcode or if you don't want to allow for diffs
979 //              cout << success;
980                 if ((bdiffs == 0) || (success == 0)) { return success;  }
981                 
982                 else { //try aligning and see if you can find it
983 //                      cout << endl;
984
985                         int maxLength = 0;
986
987                         Alignment* alignment;
988                         if (barcodes.size() > 0) {
989                                 map<string,int>::iterator it=barcodes.begin();
990
991                                 for(it;it!=barcodes.end();it++){
992                                         if(it->first.length() > maxLength){
993                                                 maxLength = it->first.length();
994                                         }
995                                 }
996                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
997
998                         }else{ alignment = NULL; } 
999                         
1000                         //can you find the barcode
1001                         int minDiff = 1e6;
1002                         int minCount = 1;
1003                         int minGroup = -1;
1004                         int minPos = 0;
1005                         
1006                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
1007                                 string oligo = it->first;
1008 //                              int length = oligo.length();
1009                                 
1010                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
1011                                         success = bdiffs + 10;
1012                                         break;
1013                                 }
1014                                 
1015                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1016                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
1017                                 oligo = alignment->getSeqAAln();
1018                                 string temp = alignment->getSeqBAln();
1019                 
1020                                 int alnLength = oligo.length();
1021                                 
1022                                 for(int i=oligo.length()-1;i>=0;i--){
1023                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1024                                 }
1025                                 oligo = oligo.substr(0,alnLength);
1026                                 temp = temp.substr(0,alnLength);
1027                                 
1028                                 int newStart=0;
1029                                 int numDiff = countDiffs(oligo, temp);
1030                                 
1031 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1032                                 
1033                                 if(numDiff < minDiff){
1034                                         minDiff = numDiff;
1035                                         minCount = 1;
1036                                         minGroup = it->second;
1037                                         minPos = 0;
1038                                         for(int i=0;i<alnLength;i++){
1039                                                 if(temp[i] != '-'){
1040                                                         minPos++;
1041                                                 }
1042                                         }
1043                                 }
1044                                 else if(numDiff == minDiff){
1045                                         minCount++;
1046                                 }
1047
1048                         }
1049
1050                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
1051                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
1052                         else{                                                                                                   //use the best match
1053                                 group = minGroup;
1054                                 seq.setUnaligned(rawSequence.substr(minPos));
1055                                 
1056                                 if(qual.getName() != ""){
1057                                         qual.trimQScores(minPos, -1);
1058                                 }
1059                                 success = minDiff;
1060                         }
1061                         
1062                         if (alignment != NULL) {  delete alignment;  }
1063                         
1064                 }
1065 //              cout << success << endl;
1066                 
1067                 return success;
1068                 
1069         }
1070         catch(exception& e) {
1071                 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
1072                 exit(1);
1073         }
1074
1075 }
1076
1077 //***************************************************************************************************************
1078
1079 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
1080         try {
1081                 string rawSequence = seq.getUnaligned();
1082                 int success = pdiffs + 1;       //guilty until proven innocent
1083                 
1084                 //can you find the primer
1085                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1086                         string oligo = it->first;
1087                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
1088                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
1089                                 break;  
1090                         }
1091                         
1092                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1093                                 group = it->second;
1094                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
1095                                 if(qual.getName() != ""){
1096                                         qual.trimQScores(oligo.length(), -1);
1097                                         
1098                                 }
1099                                 success = 0;
1100                                 break;
1101                         }
1102                 }
1103
1104                 //if you found the barcode or if you don't want to allow for diffs
1105 //              cout << success;
1106                 if ((pdiffs == 0) || (success == 0)) { return success;  }
1107                 
1108                 else { //try aligning and see if you can find it
1109 //                      cout << endl;
1110
1111                         int maxLength = 0;
1112
1113                         Alignment* alignment;
1114                         if (primers.size() > 0) {
1115                                 map<string,int>::iterator it=primers.begin();
1116
1117                                 for(it;it!=primers.end();it++){
1118                                         if(it->first.length() > maxLength){
1119                                                 maxLength = it->first.length();
1120                                         }
1121                                 }
1122                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
1123
1124                         }else{ alignment = NULL; } 
1125                         
1126                         //can you find the barcode
1127                         int minDiff = 1e6;
1128                         int minCount = 1;
1129                         int minGroup = -1;
1130                         int minPos = 0;
1131                         
1132                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1133                                 string oligo = it->first;
1134 //                              int length = oligo.length();
1135                                 
1136                                 if(rawSequence.length() < maxLength){   
1137                                         success = pdiffs + 100;
1138                                         break;
1139                                 }
1140                                 
1141                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1142                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1143                                 oligo = alignment->getSeqAAln();
1144                                 string temp = alignment->getSeqBAln();
1145                 
1146                                 int alnLength = oligo.length();
1147                                 
1148                                 for(int i=oligo.length()-1;i>=0;i--){
1149                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1150                                 }
1151                                 oligo = oligo.substr(0,alnLength);
1152                                 temp = temp.substr(0,alnLength);
1153                                 
1154                                 int newStart=0;
1155                                 int numDiff = countDiffs(oligo, temp);
1156                                 
1157 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1158                                 
1159                                 if(numDiff < minDiff){
1160                                         minDiff = numDiff;
1161                                         minCount = 1;
1162                                         minGroup = it->second;
1163                                         minPos = 0;
1164                                         for(int i=0;i<alnLength;i++){
1165                                                 if(temp[i] != '-'){
1166                                                         minPos++;
1167                                                 }
1168                                         }
1169                                 }
1170                                 else if(numDiff == minDiff){
1171                                         minCount++;
1172                                 }
1173
1174                         }
1175
1176                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
1177                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
1178                         else{                                                                                                   //use the best match
1179                                 group = minGroup;
1180                                 seq.setUnaligned(rawSequence.substr(minPos));
1181                                 if(qual.getName() != ""){
1182                                         qual.trimQScores(minPos, -1);
1183                                 }
1184                                 success = minDiff;
1185                         }
1186                         
1187                         if (alignment != NULL) {  delete alignment;  }
1188                         
1189                 }
1190                 
1191                 return success;
1192
1193         }
1194         catch(exception& e) {
1195                 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1196                 exit(1);
1197         }
1198 }
1199
1200 //***************************************************************************************************************
1201
1202 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1203         try {
1204                 string rawSequence = seq.getUnaligned();
1205                 bool success = 0;       //guilty until proven innocent
1206                 
1207                 for(int i=0;i<numRPrimers;i++){
1208                         string oligo = revPrimer[i];
1209                         
1210                         if(rawSequence.length() < oligo.length()){
1211                                 success = 0;
1212                                 break;
1213                         }
1214                         
1215                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1216                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1217                                 if(qual.getName() != ""){
1218                                         qual.trimQScores(-1, rawSequence.length()-oligo.length());
1219                                 }
1220                                 success = 1;
1221                                 break;
1222                         }
1223                 }       
1224                 return success;
1225                 
1226         }
1227         catch(exception& e) {
1228                 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1229                 exit(1);
1230         }
1231 }
1232
1233 //***************************************************************************************************************
1234
1235 bool TrimSeqsCommand::cullLength(Sequence& seq){
1236         try {
1237         
1238                 int length = seq.getNumBases();
1239                 bool success = 0;       //guilty until proven innocent
1240                 
1241                 if(length >= minLength && maxLength == 0)                       {       success = 1;    }
1242                 else if(length >= minLength && length <= maxLength)     {       success = 1;    }
1243                 else                                                                                            {       success = 0;    }
1244                 
1245                 return success;
1246         
1247         }
1248         catch(exception& e) {
1249                 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1250                 exit(1);
1251         }
1252         
1253 }
1254
1255 //***************************************************************************************************************
1256
1257 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1258         try {
1259                 int longHomoP = seq.getLongHomoPolymer();
1260                 bool success = 0;       //guilty until proven innocent
1261                 
1262                 if(longHomoP <= maxHomoP){      success = 1;    }
1263                 else                                    {       success = 0;    }
1264                 
1265                 return success;
1266         }
1267         catch(exception& e) {
1268                 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1269                 exit(1);
1270         }
1271         
1272 }
1273
1274 //***************************************************************************************************************
1275
1276 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1277         try {
1278                 int numNs = seq.getAmbigBases();
1279                 bool success = 0;       //guilty until proven innocent
1280                 
1281                 if(numNs <= maxAmbig)   {       success = 1;    }
1282                 else                                    {       success = 0;    }
1283                 
1284                 return success;
1285         }
1286         catch(exception& e) {
1287                 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1288                 exit(1);
1289         }
1290         
1291 }
1292
1293 //***************************************************************************************************************
1294
1295 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1296         try {
1297                 bool success = 1;
1298                 int length = oligo.length();
1299                 
1300                 for(int i=0;i<length;i++){
1301                         
1302                         if(oligo[i] != seq[i]){
1303                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
1304                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
1305                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
1306                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
1307                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
1308                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
1309                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
1310                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
1311                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1312                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1313                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
1314                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
1315                                 
1316                                 if(success == 0)        {       break;   }
1317                         }
1318                         else{
1319                                 success = 1;
1320                         }
1321                 }
1322                 
1323                 return success;
1324         }
1325         catch(exception& e) {
1326                 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1327                 exit(1);
1328         }
1329
1330 }
1331 //***************************************************************************************************************
1332
1333 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1334         try {
1335
1336                 int length = oligo.length();
1337                 int countDiffs = 0;
1338                 
1339                 for(int i=0;i<length;i++){
1340                                                                 
1341                         if(oligo[i] != seq[i]){
1342                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
1343                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
1344                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
1345                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
1346                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
1347                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
1348                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
1349                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
1350                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1351                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1352                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
1353                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }       
1354                         }
1355                         
1356                 }
1357                 
1358                 return countDiffs;
1359         }
1360         catch(exception& e) {
1361                 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1362                 exit(1);
1363         }
1364
1365 }
1366 //***************************************************************************************************************
1367
1368 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1369 //      try {
1370 //              
1371 //              string rawSequence = seq.getUnaligned();
1372 //              int seqLength = seq.getNumBases();
1373 //              bool success = 0;       //guilty until proven innocent
1374 //              string name;
1375 //              
1376 //              qFile >> name;
1377 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1378 //              
1379 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1380 //              
1381 //              int score;
1382 //              int end = seqLength;
1383 //              
1384 //              for(int i=0;i<seqLength;i++){
1385 //                      qFile >> score;
1386 //                      
1387 //                      if(score < qThreshold){
1388 //                              end = i;
1389 //                              break;
1390 //                      }
1391 //              }
1392 //              for(int i=end+1;i<seqLength;i++){
1393 //                      qFile >> score;
1394 //              }
1395 //              
1396 //              seq.setUnaligned(rawSequence.substr(0,end));
1397 //              
1398 //              return 1;
1399 //      }
1400 //      catch(exception& e) {
1401 //              m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1402 //              exit(1);
1403 //      }
1404 //}
1405
1406 //***************************************************************************************************************
1407
1408 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1409 //      try {
1410 //              string rawSequence = seq.getUnaligned();
1411 //              int seqLength = seq.getNumBases();
1412 //              bool success = 0;       //guilty until proven innocent
1413 //              string name;
1414 //              
1415 //              qFile >> name;
1416 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1417 //              
1418 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1419 //              
1420 //              float score;    
1421 //              float average = 0;
1422 //              
1423 //              for(int i=0;i<seqLength;i++){
1424 //                      qFile >> score;
1425 //                      average += score;
1426 //              }
1427 //              average /= seqLength;
1428 //
1429 //              if(average >= qAverage) {       success = 1;    }
1430 //              else                                    {       success = 0;    }
1431 //              
1432 //              return success;
1433 //      }
1434 //      catch(exception& e) {
1435 //              m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1436 //              exit(1);
1437 //      }
1438 //}
1439
1440 //***************************************************************************************************************