]> git.donarmstrong.com Git - mothur.git/blob - mothur.h
1.10.0
[mothur.git] / mothur.h
1 #ifndef MOTHUR_H
2 #define MOTHUR_H
3
4
5
6 /*
7  *  mothur.h
8  *  Mothur
9  *
10  *  Created by Sarah Westcott on 2/19/09.
11  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
12  *
13  */
14
15 /* This file contains all the standard incudes we use in the project as well as some common utilities. */
16
17 //#include <cstddef>
18
19 //io libraries
20 #include <iostream>
21 #include <iomanip>
22 #include <fstream>
23 #include <sstream>
24 #include <signal.h>
25
26
27 //exception
28 #include <stdexcept>
29 #include <exception>
30 #include <cstdlib> 
31
32
33 //containers
34 #include <vector>
35 #include <set>
36 #include <map>
37 #include <string>
38 #include <list>
39
40 //math
41 #include <cmath>
42 #include <math.h>
43 #include <algorithm>
44
45 //misc
46 #include <cerrno>
47 #include <ctime>
48 #include <limits>
49
50 #ifdef USE_MPI
51         #include "mpi.h"
52 #endif
53 /***********************************************************************/
54
55 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
56         #include <sys/wait.h>
57         #include <unistd.h>
58         
59         #ifdef USE_READLINE
60                 #include <readline/readline.h>
61                 #include <readline/history.h>
62         #endif
63
64 #else
65         #include <conio.h> //allows unbuffered screen capture from stdin
66         #include <direct.h> //get cwd
67 #endif
68
69 using namespace std;
70
71 #define exp(x) (exp((double) x))
72 #define sqrt(x) (sqrt((double) x))
73 #define log10(x) (log10((double) x))
74 #define log2(x) (log10(x)/log10(2))
75 #define isnan(x) ((x) != (x))
76 #define isinf(x) (fabs(x) == std::numeric_limits<double>::infinity())
77
78 typedef unsigned long ull;
79
80 struct IntNode {
81         int lvalue;
82         int rvalue;
83         int lcoef;
84         int rcoef;
85         IntNode* left;
86         IntNode* right;
87         
88         IntNode(int lv, int rv, IntNode* l, IntNode* r) : lvalue(lv), rvalue(rv), left(l), right(r) {};
89         IntNode() {};
90 };
91
92 struct ThreadNode {
93         int* pid;
94         IntNode* left;
95         IntNode* right;
96 };
97
98 /************************************************************/
99 struct clusterNode {
100         int numSeq;
101         int parent;
102         int smallChild; //used to make linkTable work with list and rabund. represents bin number of this cluster node
103         clusterNode(int num, int par, int kid) : numSeq(num), parent(par), smallChild(kid) {};
104 };
105 /************************************************************/
106 struct seqDist {
107         int seq1;
108         int seq2;
109         float dist;
110         seqDist() {}
111         seqDist(int s1, int s2, float d) : seq1(s1), seq2(s2), dist(d) {}
112         ~seqDist() {}
113 };
114 //********************************************************************************************************************
115 //sorts lowest to highest
116 inline bool compareSequenceDistance(seqDist left, seqDist right){
117         return (left.dist < right.dist);        
118
119 /***********************************************************************/
120
121 // snagged from http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
122 // works for now, but there should be a way to do it without killing the whole program
123
124 class BadConversion : public runtime_error {
125 public:
126         BadConversion(const string& s) : runtime_error(s){ }
127 };
128
129 //**********************************************************************************************************************
130
131 template<typename T>
132 inline void convert(const string& s, T& x, bool failIfLeftoverChars = true){
133         istringstream i(s);
134         char c;
135         if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
136                 throw BadConversion(s);
137 }
138
139 //**********************************************************************************************************************
140
141 template<typename T>
142 inline bool convertTestFloat(const string& s, T& x, bool failIfLeftoverChars = true){
143         istringstream i(s);
144         char c;
145         if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
146         {
147                 return false;
148         } 
149         return true;
150 }
151
152 //**********************************************************************************************************************
153
154 template<typename T>
155 inline bool convertTest(const string& s, T& x, bool failIfLeftoverChars = true){
156         istringstream i(s);
157         char c;
158         if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
159         {
160                 cout << "unable to be converted into an integer.\n" << endl;
161                 return false;
162         } 
163         return true;
164 }
165
166 //**********************************************************************************************************************
167
168 template<typename T>
169 string toString(const T&x){
170     stringstream output;
171     output << x;
172     return output.str();
173 }
174
175 //**********************************************************************************************************************
176
177 template<typename T>
178 string toHex(const T&x){
179         stringstream output;
180         
181         output << hex << x;
182
183     return output.str();
184 }
185 //**********************************************************************************************************************
186
187 template<typename T>
188 string toString(const T&x, int i){
189         stringstream output;
190         
191         output.precision(i);
192     output << fixed << x;
193         
194     return output.str();
195 }
196 /***********************************************************************/
197 inline int openOutputFileAppend(string fileName, ofstream& fileHandle){
198         
199         fileHandle.open(fileName.c_str(), ios::app);
200         if(!fileHandle) {
201                 cout << "Error: Could not open " << fileName << endl;
202                 return 1;
203         }
204         else {
205                 return 0;
206         }
207
208 }
209 /***********************************************************************/
210
211 inline void gobble(istream& f){
212         
213         char d;
214     while(isspace(d=f.get()))           {;}
215         f.putback(d);
216         
217 }
218 /***********************************************************************/
219
220 inline string getline(ifstream& fileHandle) {
221         try {
222         
223                 string line = "";
224                 
225                 while (!fileHandle.eof())       {
226                         //get next character
227                         char c = fileHandle.get(); 
228                         
229                         //are you at the end of the line
230                         if ((c == '\n') || (c == '\r') || (c == '\f')){  break; }       
231                         else {          line += c;              }
232                 }
233                 
234                 return line;
235                 
236         }
237         catch(exception& e) {
238                 cout << "Error in mothur function getline" << endl;
239                 exit(1);
240         }
241 }
242
243 /***********************************************************************/
244
245 inline bool isTrue(string f){
246         
247         if ((f == "TRUE") || (f == "T") || (f == "true") || (f == "t")) {       return true;    }
248         else {  return false;  }
249 }
250
251 /***********************************************************************/
252
253 inline float roundDist(float dist, int precision){
254         
255         return int(dist * precision + 0.5)/float(precision);
256         
257 }
258
259 /***********************************************************************/
260
261 inline int getNumNames(string names){
262         
263         int count = 0;
264         
265         if(names != ""){
266                 count = 1;
267                 for(int i=0;i<names.size();i++){
268                         if(names[i] == ','){
269                                 count++;
270                         }
271                 }
272         }
273         
274         return count;
275         
276 }
277
278 /**************************************************************************************************/
279
280 inline vector<vector<double> > binomial(int maxOrder){
281         
282         vector<vector<double> > binomial(maxOrder+1);
283         
284     for(int i=0;i<=maxOrder;i++){
285                 binomial[i].resize(maxOrder+1);
286                 binomial[i][0]=1;
287                 binomial[0][i]=0;
288     }
289     binomial[0][0]=1;
290         
291     binomial[1][0]=1;
292     binomial[1][1]=1;
293         
294     for(int i=2;i<=maxOrder;i++){
295                 binomial[1][i]=0;
296     }
297         
298     for(int i=2;i<=maxOrder;i++){
299                 for(int j=1;j<=maxOrder;j++){
300                         if(i==j){       binomial[i][j]=1;                                                                       }
301                         if(j>i) {       binomial[i][j]=0;                                                                       }
302                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
303                 }
304     }
305         
306         return binomial;
307 }
308
309 /***********************************************************************/
310
311 inline string getRootName(string longName){
312  
313         string rootName = longName;
314         
315         if(longName.find_last_of(".") != longName.npos){
316                 int pos = longName.find_last_of('.')+1;
317                 rootName = longName.substr(0, pos);
318         }
319
320         return rootName;
321 }
322 /***********************************************************************/
323
324 inline string getSimpleName(string longName){
325  
326         string simpleName = longName;
327         
328         size_t found;
329         found=longName.find_last_of("/\\");
330
331         if(found != longName.npos){
332                 simpleName = longName.substr(found+1);
333         }
334         
335                 //if(longName.find_last_of("/") != longName.npos){
336                 //      int pos = longName.find_last_of('/')+1;
337                 //      simpleName = longName.substr(pos, longName.length());
338                 //}
339         
340         return simpleName;
341 }
342
343 /***********************************************************************/
344
345 inline int factorial(int num){
346         int total = 1;
347         
348         for (int i = 1; i <= num; i++) {
349                 total *= i;
350         }
351         
352         return total;
353 }
354 /**************************************************************************************************
355
356 double min(double x, double y)
357 {
358     if(x<y){    return x;    }
359     else   {    return y;    }
360 }
361
362 /***********************************************************************/
363
364 inline string getPathName(string longName){
365  
366         string rootPathName = longName;
367         
368         if(longName.find_last_of("/\\") != longName.npos){
369                 int pos = longName.find_last_of("/\\")+1;
370                 rootPathName = longName.substr(0, pos);
371         }
372         
373         return rootPathName;
374 }
375 /***********************************************************************/
376
377 inline string hasPath(string longName){
378         
379         string path = "";
380         
381         size_t found;
382         found=longName.find_last_of("~/\\");
383
384         if(found != longName.npos){
385                 path = longName.substr(0, found+1);
386         }
387         
388         return path;
389 }
390
391 /***********************************************************************/
392
393 inline string getExtension(string longName){
394         
395         string extension = longName;
396         
397         if(longName.find_last_of('.') != longName.npos){
398                 int pos = longName.find_last_of('.');
399                 extension = longName.substr(pos, longName.length());
400         }
401         
402         return extension;
403 }
404 /***********************************************************************/
405 inline bool isBlank(string fileName){
406         
407         ifstream fileHandle;
408         fileHandle.open(fileName.c_str());
409         if(!fileHandle) {
410                 cout << "Error: Could not open " << fileName << endl;
411                 return false;
412         }else {
413                 //check for blank file
414                 gobble(fileHandle);
415                 if (fileHandle.eof()) { fileHandle.close(); return true;  }
416         }
417         return false;
418 }
419 /***********************************************************************/
420
421 inline string getFullPathName(string fileName){
422         try{
423         
424         string path = hasPath(fileName);
425         string newFileName;
426         int pos;
427         
428         if (path == "") { return fileName; } //its a simple name
429         else { //we need to complete the pathname
430                 // ex. ../../../filename 
431                 // cwd = /user/work/desktop
432                                 
433                 string cwd;
434                 //get current working directory 
435                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)   
436                         
437                         if (path.find("~") != -1) { //go to home directory
438                                 string homeDir = getenv ("HOME");
439                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
440                                 return newFileName;
441                         }else { //find path
442                                 if (path.rfind("./") == -1) { return fileName; } //already complete name
443                                 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
444                                 
445                                 char* cwdpath = new char[1024];
446
447                                 size_t size;
448                                 cwdpath=getcwd(cwdpath,size);
449                         
450                                 cwd = cwdpath;
451                                 
452                                 //rip off first '/'
453                                 string simpleCWD;
454                                 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
455                                 
456                                 //break apart the current working directory
457                                 vector<string> dirs;
458                                 while (simpleCWD.find_first_of('/') != -1) {
459                                         string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
460                                         simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
461                                         dirs.push_back(dir);
462                                 }
463                                 //get last one              // ex. ../../../filename = /user/work/desktop/filename
464                                 dirs.push_back(simpleCWD);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
465                                 
466                         
467                                 int index = dirs.size()-1;
468                 
469                                 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
470                                         if (pos == 0) { break;  //you are at the end
471                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
472                                                 path = path.substr(0, pos-1);
473                                                 index--;
474                                                 if (index == 0) {  break; }
475                                         }else if (path[(pos-1)] == '/') { //you want the current working dir ./
476                                                 path = path.substr(0, pos);
477                                         }else if (pos == 1) { break;  //you are at the end
478                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
479                                 }
480                         
481                                 for (int i = index; i >= 0; i--) {
482                                         newFileName = dirs[i] +  "/" + newFileName;             
483                                 }
484                                 
485                                 newFileName =  "/" +  newFileName;
486                                 return newFileName;
487                         }       
488                 #else
489                         if (path.find("~") != -1) { //go to home directory
490                                 string homeDir = getenv ("HOMEPATH");
491                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
492                                 return newFileName;
493                         }else { //find path
494                                 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
495                                 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
496                                                         
497                                 char *cwdpath = NULL;
498                                 cwdpath = getcwd(NULL, 0); // or _getcwd
499                                 if ( cwdpath != NULL) { cwd = cwdpath; }
500                                 else { cwd = "";  }
501                                 
502                                 //break apart the current working directory
503                                 vector<string> dirs;
504                                 while (cwd.find_first_of('\\') != -1) {
505                                         string dir = cwd.substr(0,cwd.find_first_of('\\'));
506                                         cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
507                                         dirs.push_back(dir);
508                 
509                                 }
510                                 //get last one
511                                 dirs.push_back(cwd);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
512                                         
513                                 int index = dirs.size()-1;
514                                         
515                                 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
516                                         if (pos == 0) { break;  //you are at the end
517                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
518                                                 path = path.substr(0, pos-1);
519                                                 index--;
520                                                 if (index == 0) {  break; }
521                                         }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
522                                                 path = path.substr(0, pos);
523                                         }else if (pos == 1) { break;  //you are at the end
524                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
525                                 }
526                         
527                                 for (int i = index; i >= 0; i--) {
528                                         newFileName = dirs[i] +  "\\" + newFileName;            
529                                 }
530                                 
531                                 return newFileName;
532                         }
533                         
534                 #endif
535         }
536         }
537         catch(exception& e) {
538                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function getFullPathName. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
539                 exit(1);
540         }       
541 }
542 /***********************************************************************/
543
544 inline int openInputFile(string fileName, ifstream& fileHandle, string m){
545         
546         //get full path name
547         string completeFileName = getFullPathName(fileName);
548
549         fileHandle.open(completeFileName.c_str());
550         if(!fileHandle) {
551                 return 1;
552         }else {
553                 //check for blank file
554                 gobble(fileHandle);
555                 return 0;
556         }       
557 }
558 /***********************************************************************/
559
560 inline int openInputFile(string fileName, ifstream& fileHandle){
561         
562         //get full path name
563         string completeFileName = getFullPathName(fileName);
564
565         fileHandle.open(completeFileName.c_str());
566         if(!fileHandle) {
567                 cout << "Error: Could not open " << completeFileName << endl;
568                 return 1;
569         }
570         else {
571                 //check for blank file
572                 gobble(fileHandle);
573                 if (fileHandle.eof()) { cout << completeFileName << " is blank. Please correct." << endl;  return 1;  }
574                 
575                 return 0;
576         }
577         
578 }
579 /***********************************************************************/
580
581 inline int renameFile(string oldName, string newName){
582         
583         ifstream inTest;
584         int exist = openInputFile(newName, inTest, "");
585         
586 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
587         if (exist == 0) { //you could open it so you want to delete it
588                 inTest.close();
589                 string command = "rm " + newName;
590                 system(command.c_str());
591         }
592                         
593         string command = "mv " + oldName + " " + newName;
594         system(command.c_str());
595 #else
596         remove(newName.c_str());
597         int renameOk = rename(oldName.c_str(), newName.c_str());
598 #endif
599         return 0;
600 }
601
602 /***********************************************************************/
603
604 inline int openOutputFile(string fileName, ofstream& fileHandle){
605         
606         string completeFileName = getFullPathName(fileName);
607         
608         fileHandle.open(completeFileName.c_str(), ios::trunc);
609         if(!fileHandle) {
610                 cout << "Error: Could not open " << completeFileName << endl;
611                 return 1;
612         }
613         else {
614                 return 0;
615         }
616
617 }
618
619 /***********************************************************************/
620
621 inline int getNumSeqs(ifstream& file){
622         
623         int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
624         file.seekg(0);
625         return numSeqs;
626
627 }
628 /***********************************************************************/
629
630 inline bool inVector(string member, vector<string> group){
631         
632         for (int i = 0; i < group.size(); i++) {
633                 if (group[i] == member) {  return true;         }
634         }
635         
636         return false;
637 }
638 /***********************************************************************/
639
640 //This function parses the estimator options and puts them in a vector
641 inline void splitAtDash(string& estim, vector<string>& container) {
642         try {
643                 string individual;
644                 
645                 while (estim.find_first_of('-') != -1) {
646                         individual = estim.substr(0,estim.find_first_of('-'));
647                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
648                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
649                                 container.push_back(individual);
650                         }
651                 }
652                 //get last one
653                 container.push_back(estim);
654         }
655         catch(exception& e) {
656                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
657                 exit(1);
658         }       
659 }
660
661 /***********************************************************************/
662 //This function parses the label options and puts them in a set
663 inline void splitAtDash(string& estim, set<string>& container) {
664         try {
665                 string individual;
666                 
667                 while (estim.find_first_of('-') != -1) {
668                         individual = estim.substr(0,estim.find_first_of('-'));
669                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
670                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
671                                 container.insert(individual);
672                         }
673                 }
674                 //get last one
675                 container.insert(estim);
676         }
677         catch(exception& e) {
678                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
679                 exit(1);
680         }       
681 }
682 /***********************************************************************/
683 //This function parses the line options and puts them in a set
684 inline void splitAtDash(string& estim, set<int>& container) {
685         try {
686                 string individual;
687                 int lineNum;
688                 
689                 while (estim.find_first_of('-') != -1) {
690                         individual = estim.substr(0,estim.find_first_of('-'));
691                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
692                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
693                                 convert(individual, lineNum); //convert the string to int
694                                 container.insert(lineNum);
695                         }
696                 }
697                 //get last one
698                 convert(estim, lineNum); //convert the string to int
699                 container.insert(lineNum);
700         }
701         catch(exception& e) {
702                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
703                 exit(1);
704         }       
705 }
706 /***********************************************************************/
707 //This function parses the a string and puts peices in a vector
708 inline void splitAtComma(string& estim, vector<string>& container) {
709         try {
710                 string individual;
711                 
712                 while (estim.find_first_of(',') != -1) {
713                         individual = estim.substr(0,estim.find_first_of(','));
714                         if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
715                                 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
716                                 container.push_back(individual);
717                         }
718                 }
719                 //get last one
720                 container.push_back(estim);
721         }
722         catch(exception& e) {
723                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
724                 exit(1);
725         }       
726 }
727 /***********************************************************************/
728
729 //This function splits up the various option parameters
730 inline void splitAtComma(string& prefix, string& suffix){
731         try {
732                 prefix = suffix.substr(0,suffix.find_first_of(','));
733                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
734                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
735                         string space = " ";
736                         while(suffix.at(0) == ' ')
737                                 suffix = suffix.substr(1, suffix.length());
738                 }
739
740         }
741         catch(exception& e) {
742                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
743                 exit(1);
744         }       
745 }
746 /***********************************************************************/
747
748 //This function separates the key value from the option value i.e. dist=96_...
749 inline void splitAtEquals(string& key, string& value){          
750         try {
751                 if(value.find_first_of('=') != -1){
752                         key = value.substr(0,value.find_first_of('='));
753                         if ((value.find_first_of('=')+1) <= value.length()) {
754                                 value = value.substr(value.find_first_of('=')+1, value.length());
755                         }
756                 }else{
757                         key = value;
758                         value = 1;
759                 }
760         }
761         catch(exception& e) {
762                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtEquals. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
763                 exit(1);
764         }       
765 }
766 /**************************************************************************************************/
767
768 inline bool inUsersGroups(string groupname, vector<string> Groups) {
769         try {
770                 for (int i = 0; i < Groups.size(); i++) {
771                         if (groupname == Groups[i]) { return true; }
772                 }
773                 return false;
774         }
775         catch(exception& e) {
776                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
777                 exit(1);
778         }       
779 }
780 /**************************************************************************************************/
781 //returns true if any of the strings in first vector are in second vector
782 inline bool inUsersGroups(vector<string> groupnames, vector<string> Groups) {
783         try {
784                 
785                 for (int i = 0; i < groupnames.size(); i++) {
786                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
787                 }
788                 return false;
789         }
790         catch(exception& e) {
791                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
792                 exit(1);
793         }       
794 }
795 /***********************************************************************/
796 //this function determines if the user has given us labels that are smaller than the given label.
797 //if so then it returns true so that the calling function can run the previous valid distance.
798 //it's a "smart" distance function.  It also checks for invalid labels.
799 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
800         try {
801                 
802                 set<string>::iterator it;
803                 vector<float> orderFloat;
804                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
805                 map<string, float>::iterator it2;
806                 float labelFloat;
807                 bool smaller = false;
808                 
809                 //unique is the smallest line
810                 if (label == "unique") {  return false;  }
811                 else { convert(label, labelFloat); }
812                 
813                 //go through users set and make them floats
814                 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
815                         
816                         float temp;
817                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
818                                 convert(*it, temp);
819                                 orderFloat.push_back(temp);
820                                 userMap[*it] = temp;
821                         }else if (*it == "unique") { 
822                                 orderFloat.push_back(-1.0);
823                                 userMap["unique"] = -1.0;
824                         }else {
825                                 if (errorOff == "") {  cout << *it << " is not a valid label." << endl;  }
826                                 userLabels.erase(*it); 
827                                 it--;
828                         }
829                 }
830                 
831                 //sort order
832                 sort(orderFloat.begin(), orderFloat.end());
833                 
834                 /*************************************************/
835                 //is this label bigger than any of the users labels
836                 /*************************************************/
837                                 
838                 //loop through order until you find a label greater than label
839                 for (int i = 0; i < orderFloat.size(); i++) {
840                         if (orderFloat[i] < labelFloat) {
841                                 smaller = true;
842                                 if (orderFloat[i] == -1) { 
843                                         if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
844                                         userLabels.erase("unique");
845                                 }
846                                 else {  
847                                         if (errorOff == "") { cout << "Your file does not include the label " << endl; }
848                                         string s = "";
849                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
850                                                 if (it2->second == orderFloat[i]) {  
851                                                         s = it2->first;  
852                                                         //remove small labels
853                                                         userLabels.erase(s);
854                                                         break;
855                                                 }
856                                         }
857                                         if (errorOff == "") {cout << s <<  ". I will use the next smallest distance. " << endl; }
858                                 }
859                         //since they are sorted once you find a bigger one stop looking
860                         }else { break; }
861                 }
862                 
863                 return smaller;
864                                                 
865         }
866         catch(exception& e) {
867                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function anyLabelsToProcess. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
868                 exit(1);
869         }       
870 }
871
872 /**************************************************************************************************/
873 inline void appendFiles(string temp, string filename) {
874         try{
875                 ofstream output;
876                 ifstream input;
877         
878                 //open output file in append mode
879                 openOutputFileAppend(filename, output);
880                 int ableToOpen = openInputFile(temp, input, "no error");
881                 
882                 if (ableToOpen == 0) { //you opened it
883                         while(char c = input.get()){
884                                 if(input.eof())         {       break;                  }
885                                 else                            {       output << c;    }
886                         }
887                         input.close();
888                 }
889                 
890                 output.close();
891         }
892         catch(exception& e) {
893                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function appendFiles. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
894                 exit(1);
895         }       
896 }
897
898 /**************************************************************************************************/
899 inline string sortFile(string distFile, string outputDir){
900         try {   
901         
902                 //if (outputDir == "") {  outputDir += hasPath(distFile);  }
903                 string outfile = getRootName(distFile) + "sorted.dist";
904
905                 
906                 //if you can, use the unix sort since its been optimized for years
907                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
908                         string command = "sort -n -k +3 " + distFile + " -o " + outfile;
909                         system(command.c_str());
910                 #else //you are stuck with my best attempt...
911                         //windows sort does not have a way to specify a column, only a character in the line
912                         //since we cannot assume that the distance will always be at the the same character location on each line
913                         //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
914                 
915                         //read in file line by file and put distance first
916                         string tempDistFile = distFile + ".temp";
917                         ifstream input;
918                         ofstream output;
919                         openInputFile(distFile, input);
920                         openOutputFile(tempDistFile, output);
921
922                         string firstName, secondName;
923                         float dist;
924                         while (input) {
925                                 input >> firstName >> secondName >> dist;
926                                 output << dist << '\t' << firstName << '\t' << secondName << endl;
927                                 gobble(input);
928                         }
929                         input.close();
930                         output.close();
931                 
932         
933                         //sort using windows sort
934                         string tempOutfile = outfile + ".temp";
935                         string command = "sort " + tempDistFile + " /O " + tempOutfile;
936                         system(command.c_str());
937                 
938                         //read in sorted file and put distance at end again
939                         ifstream input2;
940                         openInputFile(tempOutfile, input2);
941                         openOutputFile(outfile, output);
942                 
943                         while (input2) {
944                                 input2 >> dist >> firstName >> secondName;
945                                 output << firstName << '\t' << secondName << '\t' << dist << endl;
946                                 gobble(input2);
947                         }
948                         input2.close();
949                         output.close();
950                 
951                         //remove temp files
952                         remove(tempDistFile.c_str());
953                         remove(tempOutfile.c_str());
954                 #endif
955                 
956                 return outfile;
957         }
958         catch(exception& e) {
959                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function sortfile. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
960                 exit(1);
961         }       
962 }
963 /**************************************************************************************************/
964 inline vector<long> setFilePosFasta(string filename, int& num) {
965
966                         vector<long> positions;
967                         ifstream inFASTA;
968                         openInputFile(filename, inFASTA);
969                                 
970                         string input;
971                         while(!inFASTA.eof()){
972                                 input = getline(inFASTA); gobble(inFASTA);
973                                 if (input.length() != 0) {
974                                         if(input[0] == '>'){    long pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);      }
975                                 }
976                         }
977                         inFASTA.close();
978                 
979                         num = positions.size();
980                 
981                         /*FILE * pFile;
982                         long size;
983                 
984                         //get num bytes in file
985                         pFile = fopen (filename.c_str(),"rb");
986                         if (pFile==NULL) perror ("Error opening file");
987                         else{
988                                 fseek (pFile, 0, SEEK_END);
989                                 size=ftell (pFile);
990                                 fclose (pFile);
991                         }*/
992                         
993                         long size = positions[(positions.size()-1)];
994                         ifstream in;
995                         openInputFile(filename, in);
996                         
997                         in.seekg(size);
998                 
999                         while(char c = in.get()){
1000                                 if(in.eof())            {       break;  }
1001                                 else                            {       size++; }
1002                         }
1003                         in.close();
1004                 
1005                         positions.push_back(size);
1006                 
1007                         return positions;
1008 }
1009 /**************************************************************************************************/
1010 inline vector<long> setFilePosEachLine(string filename, int& num) {
1011
1012                         vector<long> positions;
1013                         ifstream in;
1014                         openInputFile(filename, in);
1015                                 
1016                         string input;
1017                         while(!in.eof()){
1018                                 long lastpos = in.tellg();
1019                                 input = getline(in); gobble(in);
1020                                 if (input.length() != 0) {
1021                                         long pos = in.tellg(); 
1022                                         if (pos != -1) { positions.push_back(pos - input.length() - 1); }
1023                                         else {  positions.push_back(lastpos);  }
1024                                 }
1025                         }
1026                         in.close();
1027                 
1028                         num = positions.size();
1029                 
1030                         FILE * pFile;
1031                         long size;
1032                 
1033                         //get num bytes in file
1034                         pFile = fopen (filename.c_str(),"rb");
1035                         if (pFile==NULL) perror ("Error opening file");
1036                         else{
1037                                 fseek (pFile, 0, SEEK_END);
1038                                 size=ftell (pFile);
1039                                 fclose (pFile);
1040                         }
1041                 
1042                         positions.push_back(size);
1043                 
1044                         return positions;
1045 }
1046
1047 /**************************************************************************************************/
1048 #endif
1049