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