]> git.donarmstrong.com Git - mothur.git/blob - trimseqscommand.cpp
pat's changes to 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                 if(qFileName != "")     {       setLines(qFileName, qLines);    }
240
241                 
242                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
243                                 if(processors == 1){
244                                         ifstream inFASTA;
245                                         int numSeqs;
246                                         openInputFile(fastaFile, inFASTA);
247                                         getNumSeqs(inFASTA, numSeqs);
248                                         inFASTA.close();
249                                         
250                                         lines.push_back(new linePair(0, numSeqs));
251                                         
252                                         driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], lines[0]);
253                                         
254                                         for (int j = 0; j < fastaFileNames.size(); j++) {
255                                                 rename((fastaFileNames[j] + toString(getpid()) + ".temp").c_str(), fastaFileNames[j].c_str());
256                                         }
257                                         if(qFileName != ""){
258                                                 for (int j = 0; j < qualFileNames.size(); j++) {
259                                                         rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
260                                                 }
261                                         }                                               
262
263                                 }else{
264                                         setLines(fastaFile, lines);     
265                                         if(qFileName == "")     {       qLines = lines; }       
266                                                                 
267                                         createProcessesCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames); 
268                                         
269                                         rename((trimSeqFile + toString(processIDS[0]) + ".temp").c_str(), trimSeqFile.c_str());
270                                         rename((scrapSeqFile + toString(processIDS[0]) + ".temp").c_str(), scrapSeqFile.c_str());
271                                         rename((groupFile + toString(processIDS[0]) + ".temp").c_str(), groupFile.c_str());
272                                         
273                                         if(qFileName != ""){
274                                                 rename((trimQualFile + toString(processIDS[0]) + ".temp").c_str(), trimQualFile.c_str());
275                                                 rename((scrapQualFile + toString(processIDS[0]) + ".temp").c_str(), scrapQualFile.c_str());
276                                         }
277                                         
278                                         
279                                         for (int j = 0; j < fastaFileNames.size(); j++) {
280                                                 rename((fastaFileNames[j] + toString(processIDS[0]) + ".temp").c_str(), fastaFileNames[j].c_str());
281                                         }
282                                         if(qFileName != ""){
283                                                 for (int j = 0; j < qualFileNames.size(); j++) {
284                                                         rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
285                                                 }
286                                         }                                               
287                                         
288                                         //append files
289                                         for(int i=1;i<processors;i++){
290                                                 appendFiles((trimSeqFile + toString(processIDS[i]) + ".temp"), trimSeqFile);
291                                                 remove((trimSeqFile + toString(processIDS[i]) + ".temp").c_str());
292                                                 appendFiles((scrapSeqFile + toString(processIDS[i]) + ".temp"), scrapSeqFile);
293                                                 remove((scrapSeqFile + toString(processIDS[i]) + ".temp").c_str());
294
295                                                 appendFiles((trimQualFile + toString(processIDS[i]) + ".temp"), trimQualFile);
296                                                 remove((trimQualFile + toString(processIDS[i]) + ".temp").c_str());
297                                                 appendFiles((scrapQualFile + toString(processIDS[i]) + ".temp"), scrapQualFile);
298                                                 remove((scrapQualFile + toString(processIDS[i]) + ".temp").c_str());
299                                                 
300                                                 appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
301                                                 remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
302                                                 for (int j = 0; j < fastaFileNames.size(); j++) {
303                                                         appendFiles((fastaFileNames[j] + toString(processIDS[i]) + ".temp"), fastaFileNames[j]);
304                                                         remove((fastaFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
305                                                 }
306                                                 
307                                                 if(qFileName != ""){
308                                                         for (int j = 0; j < qualFileNames.size(); j++) {
309                                                                 appendFiles((qualFileNames[j] + toString(processIDS[i]) + ".temp"), qualFileNames[j]);
310                                                                 remove((qualFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
311                                                         }
312                                                 }                                               
313                                                 
314                                                 
315                                         }
316                                 }
317                                 
318                                 if (m->control_pressed) {  return 0; }
319                 #else
320                                 ifstream inFASTA;
321                                 int numSeqs;
322                                 openInputFile(fastaFile, inFASTA);
323                                 getNumSeqs(inFASTA, numSeqs);
324                                 inFASTA.close();
325                                 qFile.close();
326                                 lines.push_back(new linePair(0, numSeqs));
327                                 
328                                 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], lines[0]);
329                                 
330                                 if (m->control_pressed) {  return 0; }
331                 #endif
332                                                 
333                                                                                 
334                 for(int i=0;i<fastaFileNames.size();i++){
335                         if (isBlank(fastaFileNames[i])) { remove(fastaFileNames[i].c_str());    }
336                         else if (filesToRemove.count(fastaFileNames[i]) > 0) { remove(fastaFileNames[i].c_str()); }
337                         else {
338                                 ifstream inFASTA;
339                                 string seqName;
340                                 openInputFile(fastaFileNames[i], inFASTA);
341                                 ofstream outGroups;
342                                 string outGroupFilename = outputDir + getRootName(getSimpleName(fastaFileNames[i])) + "groups";
343                                 openOutputFile(outGroupFilename, outGroups);
344                                 outputNames.push_back(outGroupFilename);
345                                 
346                                 string thisGroup = "";
347                                 if (i > comboStarts) {
348                                         map<string, int>::iterator itCombo;
349                                         for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
350                                                 if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
351                                         }
352                                 }else{ thisGroup = groupVector[i]; }
353                                 
354                                 while(!inFASTA.eof()){
355                                         if(inFASTA.get() == '>'){
356                                                 inFASTA >> seqName;
357                                                 outGroups << seqName << '\t' << thisGroup << endl;
358                                         }
359                                         while (!inFASTA.eof())  {       char c = inFASTA.get(); if (c == 10 || c == 13){        break;  }       }
360                                 }
361                                 outGroups.close();
362                                 inFASTA.close();
363                         }
364                 }
365                 
366                 if(qFileName != ""){
367                         for(int i=0;i<qualFileNames.size();i++){
368                                 if (isBlank(qualFileNames[i])) { remove(qualFileNames[i].c_str());      }
369                                 else if (filesToRemove.count(qualFileNames[i]) > 0) { remove(qualFileNames[i].c_str()); }
370                                 else {
371                                         ifstream inQual;
372                                         string seqName;
373                                         openInputFile(qualFileNames[i], inQual);
374 //                                      ofstream outGroups;
375 //                                      
376 //                                      string thisGroup = "";
377 //                                      if (i > comboStarts) {
378 //                                              map<string, int>::iterator itCombo;
379 //                                              for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
380 //                                                      if(itCombo->second == i){       thisGroup = itCombo->first;     combos.erase(itCombo);  break;  }
381 //                                              }
382 //                                      }
383 //                                      else{ thisGroup = groupVector[i]; }
384                                         
385                                         inQual.close();
386                                 }
387                         }
388                 }
389                 
390                 
391                 if (m->control_pressed) { 
392                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
393                         return 0;
394                 }
395
396                 m->mothurOutEndLine();
397                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
398                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
399                 m->mothurOutEndLine();
400                 
401                 return 0;       
402                         
403         }
404         catch(exception& e) {
405                 m->errorOut(e, "TrimSeqsCommand", "execute");
406                 exit(1);
407         }
408 }
409                 
410 /**************************************************************************************/
411
412 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) {      
413                 
414         try {
415                 
416                 ofstream outFASTA;
417                 int able = openOutputFile(trimFile, outFASTA);
418                 
419                 ofstream scrapFASTA;
420                 openOutputFile(scrapFile, scrapFASTA);
421                 
422                 ofstream outQual;
423                 ofstream scrapQual;
424                 if(qFileName != ""){
425                         openOutputFile(trimQFile, outQual);
426                         openOutputFile(scrapQFile, scrapQual);
427                 }
428                 
429                 ofstream outGroups;
430                 vector<ofstream*> fastaFileNames;
431                 vector<ofstream*> qualFileNames;
432                 
433                 
434                 if (oligoFile != "") {          
435                         openOutputFile(groupFile, outGroups);   
436                         for (int i = 0; i < fastaNames.size(); i++) {
437                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
438                                 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate)); 
439                                 if(qFileName != ""){
440                                         qualFileNames.push_back(new ofstream((qualNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate)); 
441                                 }
442                         #else
443                                 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(i) + ".temp").c_str(), ios::ate));                      
444                                 if(qFileName != ""){
445                                         qualFileNames.push_back(new ofstream((qualNames[i] + toString(i) + ".temp").c_str(), ios::ate));                        
446                                 }
447                         #endif
448                         }
449                 }
450                 
451                 ifstream inFASTA;
452                 openInputFile(filename, inFASTA);
453                 
454                 ifstream qFile;
455                 if(qFileName != "")     {       openInputFile(qFileName, qFile);        }
456                 
457                 qFile.seekg(qline->start);
458                 inFASTA.seekg(line->start);
459                 
460                 for(int i=0;i<line->num;i++){
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);
480                         QualityScores currQual;
481                         if(qFileName != ""){
482                                 currQual = QualityScores(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                         }
571                         gobble(inFASTA);
572                         gobble(qFile);
573                 }
574                 
575                 inFASTA.close();
576                 outFASTA.close();
577                 scrapFASTA.close();
578                 if (oligoFile != "") {   outGroups.close();   }
579                 if(qFileName != "")     {       qFile.close();  scrapQual.close(); outQual.close();     }
580                 
581                 for(int i=0;i<fastaFileNames.size();i++){
582                         fastaFileNames[i]->close();
583                         delete fastaFileNames[i];
584                 }               
585                 
586                 if(qFileName != ""){
587                         for(int i=0;i<qualFileNames.size();i++){
588                                 qualFileNames[i]->close();
589                                 delete qualFileNames[i];
590                         }               
591                 }                       
592                 
593                 return 0;
594         }
595         catch(exception& e) {
596                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
597                 exit(1);
598         }
599 }
600
601 /**************************************************************************************************/
602
603 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
604         try {
605 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
606                 int process = 0;
607                 int exitCommand = 1;
608                 processIDS.clear();
609                 
610                 //loop through and create all the processes you want
611                 while (process != processors) {
612                         int pid = fork();
613                         
614                         if (pid > 0) {
615                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
616                                 process++;
617                         }else if (pid == 0){
618                                 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]);
619                                 exit(0);
620                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
621                 }
622                 
623                 //force parent to wait until all the processes are done
624                 for (int i=0;i<processors;i++) { 
625                         int temp = processIDS[i];
626                         wait(&temp);
627                 }
628                 
629                 return exitCommand;
630 #endif          
631         }
632         catch(exception& e) {
633                 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
634                 exit(1);
635         }
636 }
637
638 /**************************************************************************************************/
639
640 int TrimSeqsCommand::setLines(string filename, vector<linePair*>& lines) {
641         try {
642                 
643                 lines.clear();
644                 
645                 vector<unsigned long int> positions;
646                 
647                 ifstream inFASTA;
648                 openInputFile(filename, inFASTA);
649                         
650                 string input;
651                 while(!inFASTA.eof()){  
652                         input = getline(inFASTA);
653
654                         if (input.length() != 0) {
655                                 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);    }
656                         }
657                 }
658                 inFASTA.close();
659                 
660                 int numFastaSeqs = positions.size();
661         
662                 FILE * pFile;
663                 unsigned long int size;
664                 
665                 //get num bytes in file
666                 pFile = fopen (filename.c_str(),"rb");
667                 if (pFile==NULL) perror ("Error opening file");
668                 else{
669                         fseek (pFile, 0, SEEK_END);
670                         size=ftell (pFile);
671                         fclose (pFile);
672                 }
673                 
674                 int numSeqsPerProcessor = numFastaSeqs / processors;
675                 
676                 for (int i = 0; i < processors; i++) {
677
678                         unsigned long int startPos = positions[ i * numSeqsPerProcessor ];
679                         if(i == processors - 1){
680                                 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
681                         }else{  
682                                 unsigned long int myEnd = positions[ (i+1) * numSeqsPerProcessor ];
683                         }
684                         lines.push_back(new linePair(startPos, numSeqsPerProcessor));
685                 }
686                 
687                 return numFastaSeqs;
688         }
689         catch(exception& e) {
690                 m->errorOut(e, "TrimSeqsCommand", "setLines");
691                 exit(1);
692         }
693 }
694 //***************************************************************************************************************
695
696 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
697         try {
698                 ifstream inOligos;
699                 openInputFile(oligoFile, inOligos);
700                 
701                 ofstream test;
702                 
703                 string type, oligo, group;
704                 int index=0;
705                 //int indexPrimer = 0;
706                 
707                 while(!inOligos.eof()){
708                         inOligos >> type;
709                                         
710                         if(type[0] == '#'){
711                                 while (!inOligos.eof()) {       char c = inOligos.get(); if (c == 10 || c == 13){       break;  }       } // get rest of line if there's any crap there
712                         }
713                         else{
714                                 //make type case insensitive
715                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }
716                                 
717                                 inOligos >> oligo;
718                                 
719                                 for(int i=0;i<oligo.length();i++){
720                                         oligo[i] = toupper(oligo[i]);
721                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
722                                 }
723                                 
724                                 if(type == "FORWARD"){
725                                         group = "";
726                                         
727                                         // get rest of line in case there is a primer name
728                                         while (!inOligos.eof()) {       
729                                                 char c = inOligos.get(); 
730                                                 if (c == 10 || c == 13){        break;  }
731                                                 else if (c == 32 || c == 9){;} //space or tab
732                                                 else {  group += c;  }
733                                         } 
734                                         
735                                         //check for repeat barcodes
736                                         map<string, int>::iterator itPrime = primers.find(oligo);
737                                         if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
738                                         
739                                         primers[oligo]=index; index++;
740                                         groupVector.push_back(group);
741                                         
742                                         if(allFiles){
743                                                 outFASTAVec.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
744                                                 if(qFileName != ""){
745                                                         outQualVec.push_back((outputDir + getRootName(getSimpleName(qFileName)) + group + ".qual"));
746                                                 }
747                                                 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
748                                                         filesToRemove.insert((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
749                                                         if(qFileName != ""){
750                                                                 filesToRemove.insert((outputDir + getRootName(getSimpleName(qFileName)) + group + ".qual"));
751                                                         }
752                                                 }else {
753                                                         outputNames.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
754                                                         if(qFileName != ""){
755                                                                 outputNames.push_back((outputDir + getRootName(getSimpleName(qFileName)) + group + ".qual"));
756                                                         }                                                       
757                                                 }
758                                         }
759
760                                 }
761                                 else if(type == "REVERSE"){
762                                         Sequence oligoRC("reverse", oligo);
763                                         oligoRC.reverseComplement();
764                                         revPrimer.push_back(oligoRC.getUnaligned());
765                                 }
766                                 else if(type == "BARCODE"){
767                                         inOligos >> group;
768                                         
769                                         //check for repeat barcodes
770                                         map<string, int>::iterator itBar = barcodes.find(oligo);
771                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
772                                         
773                                         barcodes[oligo]=index; index++;
774                                         groupVector.push_back(group);
775                                         
776                                         if(allFiles){
777                                                 outputNames.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
778                                                 outFASTAVec.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
779                                                 if(qFileName != ""){
780                                                         outQualVec.push_back((outputDir + getRootName(getSimpleName(qFileName)) + group + ".qual"));
781                                                         outputNames.push_back((outputDir + getRootName(getSimpleName(qFileName)) + group + ".qual"));
782                                                 }                                                       
783                                         }
784                                 }else{  m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  }
785                         }
786                         gobble(inOligos);
787                 }
788                 
789                 inOligos.close();
790                 
791                 //add in potential combos
792                 if(allFiles){
793                         comboStarts = outFASTAVec.size()-1;
794                         for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
795                                 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
796                                         if (groupVector[itPrime->second] != "") { //there is a group for this primer
797                                                 outputNames.push_back((outputDir + getRootName(getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
798                                                 outFASTAVec.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
799                                                 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
800                                                 
801                                                 if(qFileName != ""){
802                                                         outQualVec.push_back((outputDir + getRootName(getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
803                                                         outputNames.push_back((outputDir + getRootName(getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
804                                                 }
805                                         }
806                                 }
807                         }
808                 }
809                 
810                 numFPrimers = primers.size();
811                 numRPrimers = revPrimer.size();
812                 
813         }
814         catch(exception& e) {
815                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
816                 exit(1);
817         }
818 }
819 //***************************************************************************************************************
820
821 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
822         try {
823                 
824                 string rawSequence = seq.getUnaligned();
825                 int success = bdiffs + 1;       //guilty until proven innocent
826                 
827                 //can you find the barcode
828                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
829                         string oligo = it->first;
830                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
831                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
832                                 break;  
833                         }
834                         
835                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
836                                 group = it->second;
837                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
838                                 
839                                 if(qual.getName() != ""){
840                                         qual.trimQScores(oligo.length(), -1);
841                                 }
842                                 
843                                 success = 0;
844                                 break;
845                         }
846                 }
847                 
848                 //if you found the barcode or if you don't want to allow for diffs
849 //              cout << success;
850                 if ((bdiffs == 0) || (success == 0)) { return success;  }
851                 
852                 else { //try aligning and see if you can find it
853 //                      cout << endl;
854
855                         int maxLength = 0;
856
857                         Alignment* alignment;
858                         if (barcodes.size() > 0) {
859                                 map<string,int>::iterator it=barcodes.begin();
860
861                                 for(it;it!=barcodes.end();it++){
862                                         if(it->first.length() > maxLength){
863                                                 maxLength = it->first.length();
864                                         }
865                                 }
866                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
867
868                         }else{ alignment = NULL; } 
869                         
870                         //can you find the barcode
871                         int minDiff = 1e6;
872                         int minCount = 1;
873                         int minGroup = -1;
874                         int minPos = 0;
875                         
876                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
877                                 string oligo = it->first;
878 //                              int length = oligo.length();
879                                 
880                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
881                                         success = bdiffs + 10;
882                                         break;
883                                 }
884                                 
885                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
886                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
887                                 oligo = alignment->getSeqAAln();
888                                 string temp = alignment->getSeqBAln();
889                 
890                                 int alnLength = oligo.length();
891                                 
892                                 for(int i=oligo.length()-1;i>=0;i--){
893                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
894                                 }
895                                 oligo = oligo.substr(0,alnLength);
896                                 temp = temp.substr(0,alnLength);
897                                 
898                                 int newStart=0;
899                                 int numDiff = countDiffs(oligo, temp);
900                                 
901 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
902                                 
903                                 if(numDiff < minDiff){
904                                         minDiff = numDiff;
905                                         minCount = 1;
906                                         minGroup = it->second;
907                                         minPos = 0;
908                                         for(int i=0;i<alnLength;i++){
909                                                 if(temp[i] != '-'){
910                                                         minPos++;
911                                                 }
912                                         }
913                                 }
914                                 else if(numDiff == minDiff){
915                                         minCount++;
916                                 }
917
918                         }
919
920                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
921                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
922                         else{                                                                                                   //use the best match
923                                 group = minGroup;
924                                 seq.setUnaligned(rawSequence.substr(minPos));
925                                 
926                                 if(qual.getName() != ""){
927                                         qual.trimQScores(minPos, -1);
928                                 }
929                                 success = minDiff;
930                         }
931                         
932                         if (alignment != NULL) {  delete alignment;  }
933                         
934                 }
935 //              cout << success << endl;
936                 
937                 return success;
938                 
939         }
940         catch(exception& e) {
941                 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
942                 exit(1);
943         }
944
945 }
946
947 //***************************************************************************************************************
948
949 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
950         try {
951                 string rawSequence = seq.getUnaligned();
952                 int success = pdiffs + 1;       //guilty until proven innocent
953                 
954                 //can you find the primer
955                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
956                         string oligo = it->first;
957                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
958                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
959                                 break;  
960                         }
961                         
962                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
963                                 group = it->second;
964                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
965                                 if(qual.getName() != ""){
966                                         qual.trimQScores(oligo.length(), -1);
967                                         
968                                 }
969                                 success = 0;
970                                 break;
971                         }
972                 }
973
974                 //if you found the barcode or if you don't want to allow for diffs
975 //              cout << success;
976                 if ((pdiffs == 0) || (success == 0)) { return success;  }
977                 
978                 else { //try aligning and see if you can find it
979 //                      cout << endl;
980
981                         int maxLength = 0;
982
983                         Alignment* alignment;
984                         if (primers.size() > 0) {
985                                 map<string,int>::iterator it=primers.begin();
986
987                                 for(it;it!=primers.end();it++){
988                                         if(it->first.length() > maxLength){
989                                                 maxLength = it->first.length();
990                                         }
991                                 }
992                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
993
994                         }else{ alignment = NULL; } 
995                         
996                         //can you find the barcode
997                         int minDiff = 1e6;
998                         int minCount = 1;
999                         int minGroup = -1;
1000                         int minPos = 0;
1001                         
1002                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1003                                 string oligo = it->first;
1004 //                              int length = oligo.length();
1005                                 
1006                                 if(rawSequence.length() < maxLength){   
1007                                         success = pdiffs + 100;
1008                                         break;
1009                                 }
1010                                 
1011                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1012                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1013                                 oligo = alignment->getSeqAAln();
1014                                 string temp = alignment->getSeqBAln();
1015                 
1016                                 int alnLength = oligo.length();
1017                                 
1018                                 for(int i=oligo.length()-1;i>=0;i--){
1019                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
1020                                 }
1021                                 oligo = oligo.substr(0,alnLength);
1022                                 temp = temp.substr(0,alnLength);
1023                                 
1024                                 int newStart=0;
1025                                 int numDiff = countDiffs(oligo, temp);
1026                                 
1027 //                              cout << oligo << '\t' << temp << '\t' << numDiff << endl;                               
1028                                 
1029                                 if(numDiff < minDiff){
1030                                         minDiff = numDiff;
1031                                         minCount = 1;
1032                                         minGroup = it->second;
1033                                         minPos = 0;
1034                                         for(int i=0;i<alnLength;i++){
1035                                                 if(temp[i] != '-'){
1036                                                         minPos++;
1037                                                 }
1038                                         }
1039                                 }
1040                                 else if(numDiff == minDiff){
1041                                         minCount++;
1042                                 }
1043
1044                         }
1045
1046                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
1047                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
1048                         else{                                                                                                   //use the best match
1049                                 group = minGroup;
1050                                 seq.setUnaligned(rawSequence.substr(minPos));
1051                                 if(qual.getName() != ""){
1052                                         qual.trimQScores(minPos, -1);
1053                                 }
1054                                 success = minDiff;
1055                         }
1056                         
1057                         if (alignment != NULL) {  delete alignment;  }
1058                         
1059                 }
1060                 
1061                 return success;
1062
1063         }
1064         catch(exception& e) {
1065                 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1066                 exit(1);
1067         }
1068 }
1069
1070 //***************************************************************************************************************
1071
1072 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1073         try {
1074                 string rawSequence = seq.getUnaligned();
1075                 bool success = 0;       //guilty until proven innocent
1076                 
1077                 for(int i=0;i<numRPrimers;i++){
1078                         string oligo = revPrimer[i];
1079                         
1080                         if(rawSequence.length() < oligo.length()){
1081                                 success = 0;
1082                                 break;
1083                         }
1084                         
1085                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1086                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1087                                 if(qual.getName() != ""){
1088                                         qual.trimQScores(-1, rawSequence.length()-oligo.length());
1089                                 }
1090                                 success = 1;
1091                                 break;
1092                         }
1093                 }       
1094                 return success;
1095                 
1096         }
1097         catch(exception& e) {
1098                 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1099                 exit(1);
1100         }
1101 }
1102
1103 //***************************************************************************************************************
1104
1105 bool TrimSeqsCommand::cullLength(Sequence& seq){
1106         try {
1107         
1108                 int length = seq.getNumBases();
1109                 bool success = 0;       //guilty until proven innocent
1110                 
1111                 if(length >= minLength && maxLength == 0)                       {       success = 1;    }
1112                 else if(length >= minLength && length <= maxLength)     {       success = 1;    }
1113                 else                                                                                            {       success = 0;    }
1114                 
1115                 return success;
1116         
1117         }
1118         catch(exception& e) {
1119                 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1120                 exit(1);
1121         }
1122         
1123 }
1124
1125 //***************************************************************************************************************
1126
1127 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1128         try {
1129                 int longHomoP = seq.getLongHomoPolymer();
1130                 bool success = 0;       //guilty until proven innocent
1131                 
1132                 if(longHomoP <= maxHomoP){      success = 1;    }
1133                 else                                    {       success = 0;    }
1134                 
1135                 return success;
1136         }
1137         catch(exception& e) {
1138                 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1139                 exit(1);
1140         }
1141         
1142 }
1143
1144 //***************************************************************************************************************
1145
1146 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1147         try {
1148                 int numNs = seq.getAmbigBases();
1149                 bool success = 0;       //guilty until proven innocent
1150                 
1151                 if(numNs <= maxAmbig)   {       success = 1;    }
1152                 else                                    {       success = 0;    }
1153                 
1154                 return success;
1155         }
1156         catch(exception& e) {
1157                 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1158                 exit(1);
1159         }
1160         
1161 }
1162
1163 //***************************************************************************************************************
1164
1165 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1166         try {
1167                 bool success = 1;
1168                 int length = oligo.length();
1169                 
1170                 for(int i=0;i<length;i++){
1171                         
1172                         if(oligo[i] != seq[i]){
1173                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
1174                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
1175                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
1176                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
1177                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
1178                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
1179                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
1180                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
1181                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1182                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
1183                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
1184                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
1185                                 
1186                                 if(success == 0)        {       break;   }
1187                         }
1188                         else{
1189                                 success = 1;
1190                         }
1191                 }
1192                 
1193                 return success;
1194         }
1195         catch(exception& e) {
1196                 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1197                 exit(1);
1198         }
1199
1200 }
1201 //***************************************************************************************************************
1202
1203 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1204         try {
1205
1206                 int length = oligo.length();
1207                 int countDiffs = 0;
1208                 
1209                 for(int i=0;i<length;i++){
1210                                                                 
1211                         if(oligo[i] != seq[i]){
1212                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
1213                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
1214                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
1215                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
1216                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
1217                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
1218                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
1219                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
1220                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1221                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
1222                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
1223                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }                       
1224                                 
1225                         }
1226                 }
1227                 
1228                 return countDiffs;
1229         }
1230         catch(exception& e) {
1231                 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1232                 exit(1);
1233         }
1234
1235 }
1236 //***************************************************************************************************************
1237
1238 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1239 //      try {
1240 //              
1241 //              string rawSequence = seq.getUnaligned();
1242 //              int seqLength = seq.getNumBases();
1243 //              bool success = 0;       //guilty until proven innocent
1244 //              string name;
1245 //              
1246 //              qFile >> name;
1247 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1248 //              
1249 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1250 //              
1251 //              int score;
1252 //              int end = seqLength;
1253 //              
1254 //              for(int i=0;i<seqLength;i++){
1255 //                      qFile >> score;
1256 //                      
1257 //                      if(score < qThreshold){
1258 //                              end = i;
1259 //                              break;
1260 //                      }
1261 //              }
1262 //              for(int i=end+1;i<seqLength;i++){
1263 //                      qFile >> score;
1264 //              }
1265 //              
1266 //              seq.setUnaligned(rawSequence.substr(0,end));
1267 //              
1268 //              return 1;
1269 //      }
1270 //      catch(exception& e) {
1271 //              m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1272 //              exit(1);
1273 //      }
1274 //}
1275
1276 //***************************************************************************************************************
1277
1278 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1279 //      try {
1280 //              string rawSequence = seq.getUnaligned();
1281 //              int seqLength = seq.getNumBases();
1282 //              bool success = 0;       //guilty until proven innocent
1283 //              string name;
1284 //              
1285 //              qFile >> name;
1286 //              if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); }  }
1287 //              
1288 //              while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
1289 //              
1290 //              float score;    
1291 //              float average = 0;
1292 //              
1293 //              for(int i=0;i<seqLength;i++){
1294 //                      qFile >> score;
1295 //                      average += score;
1296 //              }
1297 //              average /= seqLength;
1298 //
1299 //              if(average >= qAverage) {       success = 1;    }
1300 //              else                                    {       success = 0;    }
1301 //              
1302 //              return success;
1303 //      }
1304 //      catch(exception& e) {
1305 //              m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1306 //              exit(1);
1307 //      }
1308 //}
1309
1310 //***************************************************************************************************************