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