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