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