]> git.donarmstrong.com Git - mothur.git/blob - trimflowscommand.cpp
Merge remote-tracking branch 'mothur/master'
[mothur.git] / trimflowscommand.cpp
1 /*
2  *  trimflowscommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 12/22/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "trimflowscommand.h"
11 #include "needlemanoverlap.hpp"
12
13
14 //**********************************************************************************************************************
15 vector<string> TrimFlowsCommand::setParameters(){       
16         try {
17                 CommandParameter pflow("flow", "InputTypes", "", "", "none", "none", "none","flow",false,true,true); parameters.push_back(pflow);
18                 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none","",false,false,true); parameters.push_back(poligos);
19                 CommandParameter pmaxhomop("maxhomop", "Number", "", "9", "", "", "","",false,false); parameters.push_back(pmaxhomop);
20                 CommandParameter pmaxflows("maxflows", "Number", "", "450", "", "", "","",false,false); parameters.push_back(pmaxflows);
21                 CommandParameter pminflows("minflows", "Number", "", "450", "", "", "","",false,false); parameters.push_back(pminflows);
22                 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(ppdiffs);
23                 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(pbdiffs);
24         CommandParameter pldiffs("ldiffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(pldiffs);
25                 CommandParameter psdiffs("sdiffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(psdiffs);
26         CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(ptdiffs);
27                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
28                 CommandParameter psignal("signal", "Number", "", "0.50", "", "", "","",false,false); parameters.push_back(psignal);
29                 CommandParameter pnoise("noise", "Number", "", "0.70", "", "", "","",false,false); parameters.push_back(pnoise);
30                 CommandParameter pallfiles("allfiles", "Boolean", "", "t", "", "", "","",false,false); parameters.push_back(pallfiles);
31                 CommandParameter porder("order", "String", "", "TACG", "", "", "","",false,false); parameters.push_back(porder);
32                 CommandParameter pfasta("fasta", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pfasta);
33                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
34                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
35                 
36                 vector<string> myArray;
37                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
38                 return myArray;
39         }
40         catch(exception& e) {
41                 m->errorOut(e, "TrimFlowsCommand", "setParameters");
42                 exit(1);
43         }
44 }
45 //**********************************************************************************************************************
46 string TrimFlowsCommand::getHelpString(){       
47         try {
48                 string helpString = "";
49                 helpString += "The trim.flows command reads a flowgram file and creates .....\n";
50                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
51                 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/Trim.flows.\n";
52                 return helpString;
53         }
54         catch(exception& e) {
55                 m->errorOut(e, "TrimFlowsCommand", "getHelpString");
56                 exit(1);
57         }
58 }
59 //**********************************************************************************************************************
60 string TrimFlowsCommand::getOutputPattern(string type) {
61     try {
62         string pattern = "";
63         
64         if (type == "flow") {  pattern = "[filename],[tag],flow"; } 
65         else if (type == "fasta") {  pattern = "[filename],flow.fasta"; } 
66         else if (type == "file") {  pattern = "[filename],[tag],flow.files"; }
67         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
68         
69         return pattern;
70     }
71     catch(exception& e) {
72         m->errorOut(e, "TrimFlowsCommand", "getOutputPattern");
73         exit(1);
74     }
75 }
76 //**********************************************************************************************************************
77
78 TrimFlowsCommand::TrimFlowsCommand(){   
79         try {
80                 abort = true; calledHelp = true; 
81                 setParameters();
82                 vector<string> tempOutNames;
83                 outputTypes["flow"] = tempOutNames;
84                 outputTypes["fasta"] = tempOutNames;
85         outputTypes["file"] = tempOutNames;
86         }
87         catch(exception& e) {
88                 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
89                 exit(1);
90         }
91 }
92 //**********************************************************************************************************************
93
94 TrimFlowsCommand::TrimFlowsCommand(string option)  {
95         try {
96                 
97                 abort = false; calledHelp = false;   
98                 comboStarts = 0;
99                 
100                 //allow user to run help
101                 if(option == "help") { help(); abort = true; calledHelp = true; }
102                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
103                 
104                 else {
105                                                 
106                         vector<string> myArray = setParameters();
107                         
108                         OptionParser parser(option);
109                         map<string,string> parameters = parser.getParameters();
110                         
111                         ValidParameters validParameter;
112                         map<string,string>::iterator it;
113                         
114                         //check to make sure all parameters are valid for command
115                         for (it = parameters.begin(); it != parameters.end(); it++) { 
116                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
117                         }
118                         
119                         //initialize outputTypes
120                         vector<string> tempOutNames;
121                         outputTypes["flow"] = tempOutNames;
122                         outputTypes["fasta"] = tempOutNames;
123             outputTypes["file"] = tempOutNames;
124                         
125                         //if the user changes the input directory command factory will send this info to us in the output parameter 
126                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
127                         if (inputDir == "not found"){   inputDir = "";          }
128                         else {
129                                 string path;
130                                 it = parameters.find("flow");
131                                 //user has given a template file
132                                 if(it != parameters.end()){ 
133                                         path = m->hasPath(it->second);
134                                         //if the user has not given a path then, add inputdir. else leave path alone.
135                                         if (path == "") {       parameters["flow"] = inputDir + it->second;             }
136                                 }
137                                 
138                                 it = parameters.find("oligos");
139                                 //user has given a template file
140                                 if(it != parameters.end()){ 
141                                         path = m->hasPath(it->second);
142                                         //if the user has not given a path then, add inputdir. else leave path alone.
143                                         if (path == "") {       parameters["oligos"] = inputDir + it->second;           }
144                                 }
145                                 
146                         }
147                         
148                         
149                         //check for required parameters
150                         flowFileName = validParameter.validFile(parameters, "flow", true);
151                         if (flowFileName == "not found") { 
152                                 flowFileName = m->getFlowFile(); 
153                                 if (flowFileName != "") {  m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
154                                 else { 
155                                         m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine(); 
156                                         abort = true;
157                                 } 
158                         }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }      
159                         
160                         //if the user changes the output directory command factory will send this info to us in the output parameter 
161                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
162                                 outputDir = ""; 
163                                 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it    
164                         }
165                         
166                         
167                         //check for optional parameter and set defaults
168                         // ...at some point should added some additional type checking...
169                         
170                         string temp;
171                         temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "450"; }
172                         m->mothurConvert(temp, minFlows);  
173
174                         temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "450"; }
175                         m->mothurConvert(temp, maxFlows);  
176                         
177                         
178                         temp = validParameter.validFile(parameters, "oligos", true);
179                         if (temp == "not found")        {       oligoFileName = "";             }
180                         else if(temp == "not open")     {       abort = true;                   } 
181                         else                                            {       oligoFileName = temp;   m->setOligosFile(oligoFileName); }
182                         
183                         temp = validParameter.validFile(parameters, "fasta", false);            if (temp == "not found"){       fasta = 0;              }
184                         else if(m->isTrue(temp))        {       fasta = 1;      }
185                         
186                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found"){       temp = "9";             }
187                         m->mothurConvert(temp, maxHomoP);  
188
189                         temp = validParameter.validFile(parameters, "signal", false);           if (temp == "not found"){       temp = "0.50";  }
190                         m->mothurConvert(temp, signal);  
191
192                         temp = validParameter.validFile(parameters, "noise", false);            if (temp == "not found"){       temp = "0.70";  }
193                         m->mothurConvert(temp, noise);  
194         
195                         temp = validParameter.validFile(parameters, "bdiffs", false);           if (temp == "not found"){       temp = "0";             }
196                         m->mothurConvert(temp, bdiffs);
197                         
198                         temp = validParameter.validFile(parameters, "pdiffs", false);           if (temp == "not found"){       temp = "0";             }
199                         m->mothurConvert(temp, pdiffs);
200                         
201             temp = validParameter.validFile(parameters, "ldiffs", false);               if (temp == "not found") { temp = "0"; }
202                         m->mothurConvert(temp, ldiffs);
203             
204             temp = validParameter.validFile(parameters, "sdiffs", false);               if (temp == "not found") { temp = "0"; }
205                         m->mothurConvert(temp, sdiffs);
206                         
207                         temp = validParameter.validFile(parameters, "tdiffs", false);           if (temp == "not found") { int tempTotal = pdiffs + bdiffs + ldiffs + sdiffs;  temp = toString(tempTotal); }
208                         m->mothurConvert(temp, tdiffs);
209                         
210                         if(tdiffs == 0){        tdiffs = bdiffs + pdiffs + ldiffs + sdiffs;     }
211
212                         
213                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
214                         m->setProcessors(temp);
215                         m->mothurConvert(temp, processors);
216         
217                         flowOrder = validParameter.validFile(parameters, "order", false);
218                         if (flowOrder == "not found"){ flowOrder = "TACG";              }
219                         else if(flowOrder.length() != 4){
220                                 m->mothurOut("The value of the order option must be four bases long\n");
221                         }
222
223                         if(oligoFileName == "") {       allFiles = 0;           }
224                         else                                    {       allFiles = 1;           }
225
226                         numFPrimers = 0;
227                         numRPrimers = 0;
228             numLinkers = 0;
229             numSpacers = 0;
230                 }
231                 
232         }
233         catch(exception& e) {
234                 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
235                 exit(1);
236         }
237 }
238
239 //***************************************************************************************************************
240
241 int TrimFlowsCommand::execute(){
242         try{
243                 
244                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
245
246         map<string, string> variables; 
247                 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(flowFileName));
248         string fastaFileName = getOutputFileName("fasta",variables);
249                 if(fasta){ outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName); }
250         
251         variables["[tag]"] = "trim";
252                 string trimFlowFileName = getOutputFileName("flow",variables);
253                 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
254                 
255         variables["[tag]"] = "scrap";
256                 string scrapFlowFileName = getOutputFileName("flow",variables);
257                 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
258
259                 
260                 
261                 vector<unsigned long long> flowFilePos;
262         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
263                 flowFilePos = getFlowFileBreaks();
264                 for (int i = 0; i < (flowFilePos.size()-1); i++) {
265                         lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
266                 }       
267         #else
268                 ifstream in; m->openInputFile(flowFileName, in); in >> numFlows; in.close();
269         ///////////////////////////////////////// until I fix multiple processors for windows //////////////////        
270                 processors = 1;
271         ///////////////////////////////////////// until I fix multiple processors for windows //////////////////                
272                 if (processors == 1) {
273                         lines.push_back(new linePair(0, 1000));
274                 }else {
275                         int numFlowLines;
276                         flowFilePos = m->setFilePosEachLine(flowFileName, numFlowLines);
277                         flowFilePos.erase(flowFilePos.begin() + 1); numFlowLines--;
278                         
279                         //figure out how many sequences you have to process
280                         int numSeqsPerProcessor = numFlowLines / processors;
281                         cout << numSeqsPerProcessor << '\t' << numFlowLines << endl;
282                         for (int i = 0; i < processors; i++) {
283                                 int startIndex =  i * numSeqsPerProcessor;
284                                 if(i == (processors - 1)){      numSeqsPerProcessor = numFlowLines - i * numSeqsPerProcessor;   }
285                                 lines.push_back(new linePair(flowFilePos[startIndex], numSeqsPerProcessor));
286                                 cout << flowFilePos[startIndex] << '\t' << numSeqsPerProcessor << endl;
287                         }
288                 }
289         #endif
290                 
291                 vector<vector<string> > barcodePrimerComboFileNames;
292                 if(oligoFileName != ""){
293                         getOligos(barcodePrimerComboFileNames); 
294                 }
295                 
296                 if(processors == 1){
297                         driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
298                 }else{
299                         createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames); 
300                 }       
301                 
302                 if (m->control_pressed) {  return 0; }                  
303                 
304                 string flowFilesFileName;
305                 ofstream output;
306                 
307                 if(allFiles){
308                         set<string> namesAlreadyProcessed;
309             variables["[tag]"] = "";
310                         flowFilesFileName = getOutputFileName("file",variables);
311                         m->openOutputFile(flowFilesFileName, output);
312
313                         for(int i=0;i<barcodePrimerComboFileNames.size();i++){
314                                 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
315                                         if (namesAlreadyProcessed.count(barcodePrimerComboFileNames[i][j]) == 0) {
316                         if (barcodePrimerComboFileNames[i][j] != "") {
317                             FILE * pFile;
318                             unsigned long long size;
319                             
320                             //get num bytes in file
321                             pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
322                             if (pFile==NULL) perror ("Error opening file");
323                             else{
324                                 fseek (pFile, 0, SEEK_END);
325                                 size=ftell(pFile);
326                                 fclose (pFile);
327                             }
328                             
329                             if(size < 10){
330                                 m->mothurRemove(barcodePrimerComboFileNames[i][j]);
331                             }
332                             else{
333                                 output << m->getFullPathName(barcodePrimerComboFileNames[i][j]) << endl;
334                                 outputNames.push_back(barcodePrimerComboFileNames[i][j]);
335                                 outputTypes["flow"].push_back(barcodePrimerComboFileNames[i][j]);
336                             }
337                             namesAlreadyProcessed.insert(barcodePrimerComboFileNames[i][j]);
338                         }
339                                         }
340                                 }
341                         }
342                         output.close();
343                 }
344                 else{
345             variables["[tag]"] = "";
346                         flowFilesFileName = getOutputFileName("file",variables);
347                         m->openOutputFile(flowFilesFileName, output);
348                         
349                         output << m->getFullPathName(trimFlowFileName) << endl;
350                         
351                         output.close();
352                 }
353                 outputTypes["file"].push_back(flowFilesFileName);
354                 outputNames.push_back(flowFilesFileName);
355                         
356                 m->mothurOutEndLine();
357                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
358                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
359                 m->mothurOutEndLine();
360                 
361                 return 0;       
362         }
363         catch(exception& e) {
364                 m->errorOut(e, "TrimSeqsCommand", "execute");
365                 exit(1);
366         }
367 }
368
369 //***************************************************************************************************************
370
371 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > thisBarcodePrimerComboFileNames, linePair* line){
372         
373         try {
374                 ofstream trimFlowFile;
375                 m->openOutputFile(trimFlowFileName, trimFlowFile);
376                 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
377
378                 ofstream scrapFlowFile;
379                 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
380                 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
381                 
382                 ofstream fastaFile;
383                 if(fasta){      m->openOutputFile(fastaFileName, fastaFile);    }
384                 
385                 ifstream flowFile;
386                 m->openInputFile(flowFileName, flowFile);
387                 
388                 flowFile.seekg(line->start);
389                 
390                 if(line->start == 0){
391                         flowFile >> numFlows; m->gobble(flowFile);
392                         scrapFlowFile << maxFlows << endl;
393                         trimFlowFile << maxFlows << endl;
394                         if(allFiles){
395                                 for(int i=0;i<thisBarcodePrimerComboFileNames.size();i++){
396                                         for(int j=0;j<thisBarcodePrimerComboFileNames[0].size();j++){
397                         if (thisBarcodePrimerComboFileNames[i][j] != "") {
398                             ofstream temp;
399                             m->openOutputFile(thisBarcodePrimerComboFileNames[i][j], temp);
400                             temp << maxFlows << endl;
401                             temp.close();
402                         }
403                                         }
404                                 }                       
405                         }
406                 }
407                 
408                 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
409                 //cout << " driver flowdata address " <<  &flowData  << &flowFile << endl;      
410                 int count = 0;
411                 bool moreSeqs = 1;
412                 
413                 TrimOligos trimOligos(pdiffs, bdiffs, ldiffs, sdiffs, primers, barcodes, revPrimer, linker, spacer);
414                 
415                 while(moreSeqs) {
416                                 
417                         if (m->control_pressed) { break; }
418                         
419                         int success = 1;
420                         int currentSeqDiffs = 0;
421                         string trashCode = "";
422                         
423                         flowData.getNext(flowFile); 
424                         flowData.capFlows(maxFlows);    
425                         
426                         Sequence currSeq = flowData.getSequence();
427                         if(!flowData.hasMinFlows(minFlows)){    //screen to see if sequence is of a minimum number of flows
428                                 success = 0;
429                                 trashCode += 'l';
430                         }
431                         
432                         int primerIndex = 0;
433                         int barcodeIndex = 0;
434                         
435             if(numLinkers != 0){
436                 success = trimOligos.stripLinker(currSeq);
437                 if(success > ldiffs)            {       trashCode += 'k';       }
438                 else{ currentSeqDiffs += success;  }
439                 
440             }
441             
442             if (m->debug) { m->mothurOut("[DEBUG]: " + currSeq.getName() + " " + currSeq.getUnaligned() + "\n"); }
443             
444                         if(barcodes.size() != 0){
445                                 success = trimOligos.stripBarcode(currSeq, barcodeIndex);
446                                 if(success > bdiffs)            {       trashCode += 'b';       }
447                                 else{ currentSeqDiffs += success;  }
448                         }
449                         
450             if(numSpacers != 0){
451                 success = trimOligos.stripSpacer(currSeq);
452                 if(success > sdiffs)            {       trashCode += 's';       }
453                 else{ currentSeqDiffs += success;  }
454                 
455             }
456             
457                         if(numFPrimers != 0){
458                                 success = trimOligos.stripForward(currSeq, primerIndex);
459                                 if(success > pdiffs)            {       trashCode += 'f';       }
460                                 else{ currentSeqDiffs += success;  }
461                         }
462                         
463                         if (currentSeqDiffs > tdiffs)   {       trashCode += 't';   }
464                         
465                         if(numRPrimers != 0){
466                                 success = trimOligos.stripReverse(currSeq);
467                                 if(!success)                            {       trashCode += 'r';       }
468                         }
469                         
470                         if(trashCode.length() == 0){
471                 string thisGroup = "";
472                 if(barcodes.size() != 0){
473                     thisGroup = barcodeNameVector[barcodeIndex];
474                     if (primers.size() != 0) { 
475                         if (primerNameVector[primerIndex] != "") { 
476                             if(thisGroup != "") {
477                                 thisGroup += "." + primerNameVector[primerIndex]; 
478                             }else {
479                                 thisGroup = primerNameVector[primerIndex]; 
480                             }
481                         } 
482                     }
483                 }
484                 
485                 int pos = thisGroup.find("ignore");
486                 if (pos == string::npos) {              
487                     flowData.printFlows(trimFlowFile);
488                     
489                     if(fasta)   {       currSeq.printSequence(fastaFile);       }
490                     
491                     if(allFiles){
492                         ofstream output;
493                         m->openOutputFileAppend(thisBarcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
494                         output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
495                         
496                         flowData.printFlows(output);
497                         output.close();
498                     }
499                 }
500                         }
501                         else{
502                                 flowData.printFlows(scrapFlowFile, trashCode);
503                         }
504                                 
505                         count++;
506                         //cout << "driver" << '\t' << currSeq.getName() << endl;                        
507                         //report progress
508                         if((count) % 10000 == 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
509
510 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
511                         unsigned long long pos = flowFile.tellg();
512
513                         if ((pos == -1) || (pos >= line->end)) { break; }
514 #else
515                         if (flowFile.eof()) { break; }
516 #endif
517                         
518                 }
519                 //report progress
520                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
521                 
522                 trimFlowFile.close();
523                 scrapFlowFile.close();
524                 flowFile.close();
525                 if(fasta){      fastaFile.close();      }
526                 
527                 return count;
528         }
529         catch(exception& e) {
530                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
531                 exit(1);
532         }
533 }
534
535 //***************************************************************************************************************
536
537 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
538         try {
539                 ifstream oligosFile;
540                 m->openInputFile(oligoFileName, oligosFile);
541                 
542                 string type, oligo, group;
543
544                 int indexPrimer = 0;
545                 int indexBarcode = 0;
546                 
547                 while(!oligosFile.eof()){
548                 
549                         oligosFile >> type; m->gobble(oligosFile);      //get the first column value of the row - is it a comment or a feature we are interested in?
550
551                         if(type[0] == '#'){     //igore the line because there's a comment
552                                 while (!oligosFile.eof())       {       char c = oligosFile.get(); if (c == 10 || c == 13){     break;  }       } // get rest of line if there's any crap there
553                         }
554                         else{                           //there's a feature we're interested in
555
556                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }                                  //make type case insensitive
557
558                                 oligosFile >> oligo;    //get the DNA sequence for the feature
559
560                                 for(int i=0;i<oligo.length();i++){      //make type case insensitive and change any U's to T's
561                                         oligo[i] = toupper(oligo[i]);
562                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
563                                 }
564
565                                 if(type == "FORWARD"){  //if the feature is a forward primer...
566                                         group = "";
567
568                                         while (!oligosFile.eof())       {       // get rest of line in case there is a primer name = will have the name of the primer
569                                                 char c = oligosFile.get(); 
570                                                 if (c == 10 || c == 13){        break;  }
571                                                 else if (c == 32 || c == 9){;} //space or tab
572                                                 else {  group += c;  }
573                                         } 
574
575                                         //have we seen this primer already?
576                                         map<string, int>::iterator itPrimer = primers.find(oligo);
577                                         if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
578
579                                         primers[oligo]=indexPrimer; indexPrimer++;
580                                         primerNameVector.push_back(group);
581
582                                 }
583                                 else if(type == "REVERSE"){
584                                         string oligoRC = reverseOligo(oligo);
585                                         revPrimer.push_back(oligoRC);
586                                 }
587                                 else if(type == "BARCODE"){
588                                         oligosFile >> group;
589
590                                         //check for repeat barcodes
591                                         map<string, int>::iterator itBar = barcodes.find(oligo);
592                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
593
594                                         barcodes[oligo]=indexBarcode; indexBarcode++;
595                                         barcodeNameVector.push_back(group);
596                                 }else if(type == "LINKER"){
597                                         linker.push_back(oligo);
598                                 }else if(type == "SPACER"){
599                                         spacer.push_back(oligo);
600                                 }
601                                 else{
602                                         m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  
603                                 }
604                         }
605
606                         m->gobble(oligosFile);
607                 }
608                 oligosFile.close();
609                 
610                 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0;   }
611                 
612                 //add in potential combos
613                 if(barcodeNameVector.size() == 0){
614                         barcodes[""] = 0;
615                         barcodeNameVector.push_back("");                        
616                 }
617                 
618                 if(primerNameVector.size() == 0){
619                         primers[""] = 0;
620                         primerNameVector.push_back("");                 
621                 }
622                 
623                 
624                 outFlowFileNames.resize(barcodeNameVector.size());
625                 for(int i=0;i<outFlowFileNames.size();i++){
626                         outFlowFileNames[i].assign(primerNameVector.size(), "");
627                 }
628                 
629                 if(allFiles){
630
631                         for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
632                                 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
633
634                                         string primerName = primerNameVector[itPrimer->second];
635                                         string barcodeName = barcodeNameVector[itBar->second];
636                     
637                                         if ((primerName == "ignore") || (barcodeName == "ignore")) { } //do nothing 
638                                         else {                                  
639                         string comboGroupName = "";
640                         string fileName = "";
641                         
642                         map<string, string> variables; 
643                         variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(flowFileName));
644                         
645                         if(primerName == ""){
646                             comboGroupName = barcodeNameVector[itBar->second];
647                             variables["[tag]"] = comboGroupName;
648                             fileName = getOutputFileName("flow", variables);
649                         }
650                         else{
651                             if(barcodeName == ""){
652                                 comboGroupName = primerNameVector[itPrimer->second];
653                             }
654                             else{
655                                 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
656                             }
657                             variables["[tag]"] = comboGroupName;
658                             fileName = getOutputFileName("flow", variables);
659                         }
660                         
661                         outFlowFileNames[itBar->second][itPrimer->second] = fileName;
662                         
663                         ofstream temp;
664                         m->openOutputFile(fileName, temp);
665                         temp.close();
666                     }
667                                 }
668                         }
669                 }
670                 
671                 numFPrimers = primers.size();
672                 numRPrimers = revPrimer.size();
673         numLinkers = linker.size();
674         numSpacers = spacer.size();
675                 
676         }
677         catch(exception& e) {
678                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
679                 exit(1);
680         }
681 }
682 //********************************************************************/
683 string TrimFlowsCommand::reverseOligo(string oligo){
684         try {
685         string reverse = "";
686         
687         for(int i=oligo.length()-1;i>=0;i--){
688             
689             if(oligo[i] == 'A')         {       reverse += 'T'; }
690             else if(oligo[i] == 'T'){   reverse += 'A'; }
691             else if(oligo[i] == 'U'){   reverse += 'A'; }
692             
693             else if(oligo[i] == 'G'){   reverse += 'C'; }
694             else if(oligo[i] == 'C'){   reverse += 'G'; }
695             
696             else if(oligo[i] == 'R'){   reverse += 'Y'; }
697             else if(oligo[i] == 'Y'){   reverse += 'R'; }
698             
699             else if(oligo[i] == 'M'){   reverse += 'K'; }
700             else if(oligo[i] == 'K'){   reverse += 'M'; }
701             
702             else if(oligo[i] == 'W'){   reverse += 'W'; }
703             else if(oligo[i] == 'S'){   reverse += 'S'; }
704             
705             else if(oligo[i] == 'B'){   reverse += 'V'; }
706             else if(oligo[i] == 'V'){   reverse += 'B'; }
707             
708             else if(oligo[i] == 'D'){   reverse += 'H'; }
709             else if(oligo[i] == 'H'){   reverse += 'D'; }
710             
711             else                                                {       reverse += 'N'; }
712         }
713         
714         
715         return reverse;
716     }
717         catch(exception& e) {
718                 m->errorOut(e, "TrimFlowsCommand", "reverseOligo");
719                 exit(1);
720         }
721 }
722
723 /**************************************************************************************************/
724 vector<unsigned long long> TrimFlowsCommand::getFlowFileBreaks() {
725
726         try{
727                         
728                 vector<unsigned long long> filePos;
729                 filePos.push_back(0);
730                                         
731                 FILE * pFile;
732                 unsigned long long size;
733                 
734                 //get num bytes in file
735                 pFile = fopen (flowFileName.c_str(),"rb");
736                 if (pFile==NULL) perror ("Error opening file");
737                 else{
738                         fseek (pFile, 0, SEEK_END);
739                         size=ftell (pFile);
740                         fclose (pFile);
741                 }
742                                 
743                 //estimate file breaks
744                 unsigned long long chunkSize = 0;
745                 chunkSize = size / processors;
746
747                 //file too small to divide by processors
748                 if (chunkSize == 0)  {  processors = 1; filePos.push_back(size); return filePos;        }
749                 
750                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
751                 for (int i = 0; i < processors; i++) {
752                         unsigned long long spot = (i+1) * chunkSize;
753                         
754                         ifstream in;
755                         m->openInputFile(flowFileName, in);
756                         in.seekg(spot);
757                         
758                         string dummy = m->getline(in);
759                         
760                         //there was not another sequence before the end of the file
761                         unsigned long long sanityPos = in.tellg();
762                         
763 //                      if (sanityPos == -1) {  break;  }
764 //                      else {  filePos.push_back(newSpot);  }
765                         if (sanityPos == -1) {  break;  }
766                         else {  filePos.push_back(sanityPos);  }
767                         
768                         in.close();
769                 }
770                 
771                 //save end pos
772                 filePos.push_back(size);
773                 
774                 //sanity check filePos
775                 for (int i = 0; i < (filePos.size()-1); i++) {
776                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
777                 }
778
779                 ifstream in;
780                 m->openInputFile(flowFileName, in);
781                 in >> numFlows;
782                 m->gobble(in);
783                 //unsigned long long spot = in.tellg();
784                 //filePos[0] = spot;
785                 in.close();
786                 
787                 processors = (filePos.size() - 1);
788                 
789                 return filePos; 
790         }
791         catch(exception& e) {
792                 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
793                 exit(1);
794         }
795 }
796
797 /**************************************************************************************************/
798
799 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
800
801         try {
802                 processIDS.clear();
803                 int exitCommand = 1;
804                 
805 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
806                 int process = 1;
807                 
808                 //loop through and create all the processes you want
809                 while (process != processors) {
810                         int pid = fork();
811                         
812                         if (pid > 0) {
813                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
814                                 process++;
815                         }else if (pid == 0){
816                                 
817                                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
818                                 if(allFiles){
819                                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
820                                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
821                             if (tempBarcodePrimerComboFileNames[i][j] != "") {
822                                 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
823                                 ofstream temp;
824                                 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
825                                 temp.close();
826                             }
827                                                 }
828                                         }
829                                 }
830                                 driverCreateTrim(flowFileName,
831                                                                  (trimFlowFileName + toString(getpid()) + ".temp"),
832                                                                  (scrapFlowFileName + toString(getpid()) + ".temp"),
833                                                                  (fastaFileName + toString(getpid()) + ".temp"),
834                                                                  tempBarcodePrimerComboFileNames, lines[process]);
835
836                                 exit(0);
837                         }else { 
838                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
839                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
840                                 exit(0);
841                         }
842                 }
843                 
844                 //parent do my part
845                 ofstream temp;
846                 m->openOutputFile(trimFlowFileName, temp);
847                 temp.close();
848
849                 m->openOutputFile(scrapFlowFileName, temp);
850                 temp.close();
851                 
852                 if(fasta){
853                         m->openOutputFile(fastaFileName, temp);
854                         temp.close();
855                 }
856                 
857                 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
858
859                 //force parent to wait until all the processes are done
860                 for (int i=0;i<processIDS.size();i++) { 
861                         int temp = processIDS[i];
862                         wait(&temp);
863                 }
864 #else
865                 //////////////////////////////////////////////////////////////////////////////////////////////////////
866                 //Windows version shared memory, so be careful when passing variables through the trimFlowData struct. 
867                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
868                 //////////////////////////////////////////////////////////////////////////////////////////////////////
869                 
870                 vector<trimFlowData*> pDataArray; 
871                 DWORD   dwThreadIdArray[processors-1];
872                 HANDLE  hThreadArray[processors-1]; 
873                 
874                 //Create processor worker threads.
875                 for( int i=0; i<processors-1; i++ ){
876                         // Allocate memory for thread data.
877                         string extension = "";
878                         if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
879                         
880                         vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
881                         if(allFiles){
882                                 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
883                                         for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
884                         if (tempBarcodePrimerComboFileNames[i][j] != "") {
885                             tempBarcodePrimerComboFileNames[i][j] += extension;
886                             ofstream temp;
887                             m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
888                             temp.close();
889                                                 }
890                                         }
891                                 }
892                         }
893                         
894                         trimFlowData* tempflow = new trimFlowData(flowFileName, (trimFlowFileName + extension), (scrapFlowFileName + extension), fastaFileName, flowOrder, tempBarcodePrimerComboFileNames, barcodes, primers, revPrimer, fasta, allFiles, lines[i]->start, lines[i]->end, m, signal, noise, numFlows, maxFlows, minFlows, maxHomoP, tdiffs, bdiffs, pdiffs, i);
895                         pDataArray.push_back(tempflow);
896                         
897                         //MyTrimFlowThreadFunction is in header. It must be global or static to work with the threads.
898                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
899                         hThreadArray[i] = CreateThread(NULL, 0, MyTrimFlowThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
900                 }
901                 
902                 //using the main process as a worker saves time and memory
903                 ofstream temp;
904                 m->openOutputFile(trimFlowFileName, temp);
905                 temp.close();
906                 
907                 m->openOutputFile(scrapFlowFileName, temp);
908                 temp.close();
909                 
910                 if(fasta){
911                         m->openOutputFile(fastaFileName, temp);
912                         temp.close();
913                 }
914                 
915                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
916                 if(allFiles){
917                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
918                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
919                     if (tempBarcodePrimerComboFileNames[i][j] != "") {
920                         tempBarcodePrimerComboFileNames[i][j] += toString(processors-1) + ".temp";
921                         ofstream temp;
922                         m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
923                         temp.close();
924                     }
925                                         
926                                 }
927                         }
928                 }
929                 
930                 //do my part - do last piece because windows is looking for eof
931                 int num = driverCreateTrim(flowFileName, (trimFlowFileName  + toString(processors-1) + ".temp"), (scrapFlowFileName  + toString(processors-1) + ".temp"), (fastaFileName + toString(processors-1) + ".temp"), tempBarcodePrimerComboFileNames, lines[processors-1]);
932                 processIDS.push_back((processors-1)); 
933                 
934                 //Wait until all threads have terminated.
935                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
936                 
937                 //Close all thread handles and free memory allocations.
938                 for(int i=0; i < pDataArray.size(); i++){
939                         num += pDataArray[i]->count;
940                         CloseHandle(hThreadArray[i]);
941                         delete pDataArray[i];
942                 }
943                 
944                 
945 #endif  
946                 //append files
947                 m->mothurOutEndLine();
948                 for(int i=0;i<processIDS.size();i++){
949                         
950                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
951                         
952                         m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
953                         m->mothurRemove((trimFlowFileName + toString(processIDS[i]) + ".temp"));
954 //                      m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
955
956                         m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
957                         m->mothurRemove((scrapFlowFileName + toString(processIDS[i]) + ".temp"));
958 //                      m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
959
960                         if(fasta){
961                                 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
962                                 m->mothurRemove((fastaFileName + toString(processIDS[i]) + ".temp"));
963 //                              m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
964                         }
965                         if(allFiles){                                           
966                                 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
967                                         for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
968                         if (barcodePrimerComboFileNames[j][k] != "") {
969                             m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
970                             m->mothurRemove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"));
971                         }
972                                         }
973                                 }
974                         }
975                 }
976                 
977                 return exitCommand;
978         
979         }
980         catch(exception& e) {
981                 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
982                 exit(1);
983         }
984 }
985
986 //***************************************************************************************************************