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