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