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