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