]> git.donarmstrong.com Git - mothur.git/blob - mothur.h
changed hard parameter in cluster commands
[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 inline float ceilDist(float dist, int precision){
261         
262         return int(ceil(dist * precision))/float(precision);
263         
264 }
265
266 /***********************************************************************/
267
268 inline int getNumNames(string names){
269         
270         int count = 0;
271         
272         if(names != ""){
273                 count = 1;
274                 for(int i=0;i<names.size();i++){
275                         if(names[i] == ','){
276                                 count++;
277                         }
278                 }
279         }
280         
281         return count;
282         
283 }
284
285 /**************************************************************************************************/
286
287 inline vector<vector<double> > binomial(int maxOrder){
288         
289         vector<vector<double> > binomial(maxOrder+1);
290         
291     for(int i=0;i<=maxOrder;i++){
292                 binomial[i].resize(maxOrder+1);
293                 binomial[i][0]=1;
294                 binomial[0][i]=0;
295     }
296     binomial[0][0]=1;
297         
298     binomial[1][0]=1;
299     binomial[1][1]=1;
300         
301     for(int i=2;i<=maxOrder;i++){
302                 binomial[1][i]=0;
303     }
304         
305     for(int i=2;i<=maxOrder;i++){
306                 for(int j=1;j<=maxOrder;j++){
307                         if(i==j){       binomial[i][j]=1;                                                                       }
308                         if(j>i) {       binomial[i][j]=0;                                                                       }
309                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
310                 }
311     }
312         
313         return binomial;
314 }
315
316 /***********************************************************************/
317
318 inline string getRootName(string longName){
319  
320         string rootName = longName;
321         
322         if(longName.find_last_of(".") != longName.npos){
323                 int pos = longName.find_last_of('.')+1;
324                 rootName = longName.substr(0, pos);
325         }
326
327         return rootName;
328 }
329 /***********************************************************************/
330
331 inline string getSimpleName(string longName){
332  
333         string simpleName = longName;
334         
335         size_t found;
336         found=longName.find_last_of("/\\");
337
338         if(found != longName.npos){
339                 simpleName = longName.substr(found+1);
340         }
341         
342                 //if(longName.find_last_of("/") != longName.npos){
343                 //      int pos = longName.find_last_of('/')+1;
344                 //      simpleName = longName.substr(pos, longName.length());
345                 //}
346         
347         return simpleName;
348 }
349
350 /***********************************************************************/
351
352 inline int factorial(int num){
353         int total = 1;
354         
355         for (int i = 1; i <= num; i++) {
356                 total *= i;
357         }
358         
359         return total;
360 }
361 /**************************************************************************************************
362
363 double min(double x, double y)
364 {
365     if(x<y){    return x;    }
366     else   {    return y;    }
367 }
368
369 /***********************************************************************/
370
371 inline string getPathName(string longName){
372  
373         string rootPathName = longName;
374         
375         if(longName.find_last_of("/\\") != longName.npos){
376                 int pos = longName.find_last_of("/\\")+1;
377                 rootPathName = longName.substr(0, pos);
378         }
379         
380         return rootPathName;
381 }
382 /***********************************************************************/
383
384 inline string hasPath(string longName){
385         
386         string path = "";
387         
388         size_t found;
389         found=longName.find_last_of("~/\\");
390
391         if(found != longName.npos){
392                 path = longName.substr(0, found+1);
393         }
394         
395         return path;
396 }
397
398 /***********************************************************************/
399
400 inline string getExtension(string longName){
401         
402         string extension = longName;
403         
404         if(longName.find_last_of('.') != longName.npos){
405                 int pos = longName.find_last_of('.');
406                 extension = longName.substr(pos, longName.length());
407         }
408         
409         return extension;
410 }
411 /***********************************************************************/
412 inline bool isBlank(string fileName){
413         
414         ifstream fileHandle;
415         fileHandle.open(fileName.c_str());
416         if(!fileHandle) {
417                 cout << "Error: Could not open " << fileName << endl;
418                 return false;
419         }else {
420                 //check for blank file
421                 gobble(fileHandle);
422                 if (fileHandle.eof()) { fileHandle.close(); return true;  }
423         }
424         return false;
425 }
426 /***********************************************************************/
427
428 inline string getFullPathName(string fileName){
429         try{
430         
431         string path = hasPath(fileName);
432         string newFileName;
433         int pos;
434         
435         if (path == "") { return fileName; } //its a simple name
436         else { //we need to complete the pathname
437                 // ex. ../../../filename 
438                 // cwd = /user/work/desktop
439                                 
440                 string cwd;
441                 //get current working directory 
442                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)   
443                         
444                         if (path.find("~") != -1) { //go to home directory
445                                 string homeDir = getenv ("HOME");
446                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
447                                 return newFileName;
448                         }else { //find path
449                                 if (path.rfind("./") == -1) { return fileName; } //already complete name
450                                 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
451                                 
452                                 char* cwdpath = new char[1024];
453
454                                 size_t size;
455                                 cwdpath=getcwd(cwdpath,size);
456                         
457                                 cwd = cwdpath;
458                                 
459                                 //rip off first '/'
460                                 string simpleCWD;
461                                 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
462                                 
463                                 //break apart the current working directory
464                                 vector<string> dirs;
465                                 while (simpleCWD.find_first_of('/') != -1) {
466                                         string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
467                                         simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
468                                         dirs.push_back(dir);
469                                 }
470                                 //get last one              // ex. ../../../filename = /user/work/desktop/filename
471                                 dirs.push_back(simpleCWD);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
472                                 
473                         
474                                 int index = dirs.size()-1;
475                 
476                                 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
477                                         if (pos == 0) { break;  //you are at the end
478                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
479                                                 path = path.substr(0, pos-1);
480                                                 index--;
481                                                 if (index == 0) {  break; }
482                                         }else if (path[(pos-1)] == '/') { //you want the current working dir ./
483                                                 path = path.substr(0, pos);
484                                         }else if (pos == 1) { break;  //you are at the end
485                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
486                                 }
487                         
488                                 for (int i = index; i >= 0; i--) {
489                                         newFileName = dirs[i] +  "/" + newFileName;             
490                                 }
491                                 
492                                 newFileName =  "/" +  newFileName;
493                                 return newFileName;
494                         }       
495                 #else
496                         if (path.find("~") != -1) { //go to home directory
497                                 string homeDir = getenv ("HOMEPATH");
498                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
499                                 return newFileName;
500                         }else { //find path
501                                 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
502                                 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
503                                                         
504                                 char *cwdpath = NULL;
505                                 cwdpath = getcwd(NULL, 0); // or _getcwd
506                                 if ( cwdpath != NULL) { cwd = cwdpath; }
507                                 else { cwd = "";  }
508                                 
509                                 //break apart the current working directory
510                                 vector<string> dirs;
511                                 while (cwd.find_first_of('\\') != -1) {
512                                         string dir = cwd.substr(0,cwd.find_first_of('\\'));
513                                         cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
514                                         dirs.push_back(dir);
515                 
516                                 }
517                                 //get last one
518                                 dirs.push_back(cwd);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
519                                         
520                                 int index = dirs.size()-1;
521                                         
522                                 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
523                                         if (pos == 0) { break;  //you are at the end
524                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
525                                                 path = path.substr(0, pos-1);
526                                                 index--;
527                                                 if (index == 0) {  break; }
528                                         }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
529                                                 path = path.substr(0, pos);
530                                         }else if (pos == 1) { break;  //you are at the end
531                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
532                                 }
533                         
534                                 for (int i = index; i >= 0; i--) {
535                                         newFileName = dirs[i] +  "\\" + newFileName;            
536                                 }
537                                 
538                                 return newFileName;
539                         }
540                         
541                 #endif
542         }
543         }
544         catch(exception& e) {
545                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function getFullPathName. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
546                 exit(1);
547         }       
548 }
549 /***********************************************************************/
550
551 inline int openInputFile(string fileName, ifstream& fileHandle, string m){
552         
553         //get full path name
554         string completeFileName = getFullPathName(fileName);
555
556         fileHandle.open(completeFileName.c_str());
557         if(!fileHandle) {
558                 return 1;
559         }else {
560                 //check for blank file
561                 gobble(fileHandle);
562                 return 0;
563         }       
564 }
565 /***********************************************************************/
566
567 inline int openInputFile(string fileName, ifstream& fileHandle){
568         
569         //get full path name
570         string completeFileName = getFullPathName(fileName);
571
572         fileHandle.open(completeFileName.c_str());
573         if(!fileHandle) {
574                 cout << "Error: Could not open " << completeFileName << endl;
575                 return 1;
576         }
577         else {
578                 //check for blank file
579                 gobble(fileHandle);
580                 if (fileHandle.eof()) { cout << completeFileName << " is blank. Please correct." << endl;  return 1;  }
581                 
582                 return 0;
583         }
584         
585 }
586 /***********************************************************************/
587
588 inline int renameFile(string oldName, string newName){
589         
590         ifstream inTest;
591         int exist = openInputFile(newName, inTest, "");
592         
593 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
594         if (exist == 0) { //you could open it so you want to delete it
595                 inTest.close();
596                 string command = "rm " + newName;
597                 system(command.c_str());
598         }
599                         
600         string command = "mv " + oldName + " " + newName;
601         system(command.c_str());
602 #else
603         remove(newName.c_str());
604         int renameOk = rename(oldName.c_str(), newName.c_str());
605 #endif
606         return 0;
607 }
608
609 /***********************************************************************/
610
611 inline int openOutputFile(string fileName, ofstream& fileHandle){
612         
613         string completeFileName = getFullPathName(fileName);
614         
615         fileHandle.open(completeFileName.c_str(), ios::trunc);
616         if(!fileHandle) {
617                 cout << "Error: Could not open " << completeFileName << endl;
618                 return 1;
619         }
620         else {
621                 return 0;
622         }
623
624 }
625
626 /***********************************************************************/
627
628 inline int getNumSeqs(ifstream& file){
629         
630         int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
631         file.seekg(0);
632         return numSeqs;
633
634 }
635 /***********************************************************************/
636
637 inline bool inVector(string member, vector<string> group){
638         
639         for (int i = 0; i < group.size(); i++) {
640                 if (group[i] == member) {  return true;         }
641         }
642         
643         return false;
644 }
645 /***********************************************************************/
646
647 //This function parses the estimator options and puts them in a vector
648 inline void splitAtDash(string& estim, vector<string>& container) {
649         try {
650                 string individual;
651                 
652                 while (estim.find_first_of('-') != -1) {
653                         individual = estim.substr(0,estim.find_first_of('-'));
654                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
655                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
656                                 container.push_back(individual);
657                         }
658                 }
659                 //get last one
660                 container.push_back(estim);
661         }
662         catch(exception& e) {
663                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
664                 exit(1);
665         }       
666 }
667
668 /***********************************************************************/
669 //This function parses the label options and puts them in a set
670 inline void splitAtDash(string& estim, set<string>& container) {
671         try {
672                 string individual;
673                 
674                 while (estim.find_first_of('-') != -1) {
675                         individual = estim.substr(0,estim.find_first_of('-'));
676                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
677                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
678                                 container.insert(individual);
679                         }
680                 }
681                 //get last one
682                 container.insert(estim);
683         }
684         catch(exception& e) {
685                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
686                 exit(1);
687         }       
688 }
689 /***********************************************************************/
690 //This function parses the line options and puts them in a set
691 inline void splitAtDash(string& estim, set<int>& container) {
692         try {
693                 string individual;
694                 int lineNum;
695                 
696                 while (estim.find_first_of('-') != -1) {
697                         individual = estim.substr(0,estim.find_first_of('-'));
698                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
699                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
700                                 convert(individual, lineNum); //convert the string to int
701                                 container.insert(lineNum);
702                         }
703                 }
704                 //get last one
705                 convert(estim, lineNum); //convert the string to int
706                 container.insert(lineNum);
707         }
708         catch(exception& e) {
709                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
710                 exit(1);
711         }       
712 }
713 /***********************************************************************/
714 //This function parses the a string and puts peices in a vector
715 inline void splitAtComma(string& estim, vector<string>& container) {
716         try {
717                 string individual;
718                 
719                 while (estim.find_first_of(',') != -1) {
720                         individual = estim.substr(0,estim.find_first_of(','));
721                         if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
722                                 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
723                                 container.push_back(individual);
724                         }
725                 }
726                 //get last one
727                 container.push_back(estim);
728         }
729         catch(exception& e) {
730                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
731                 exit(1);
732         }       
733 }
734 /***********************************************************************/
735
736 //This function splits up the various option parameters
737 inline void splitAtComma(string& prefix, string& suffix){
738         try {
739                 prefix = suffix.substr(0,suffix.find_first_of(','));
740                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
741                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
742                         string space = " ";
743                         while(suffix.at(0) == ' ')
744                                 suffix = suffix.substr(1, suffix.length());
745                 }
746
747         }
748         catch(exception& e) {
749                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
750                 exit(1);
751         }       
752 }
753 /***********************************************************************/
754
755 //This function separates the key value from the option value i.e. dist=96_...
756 inline void splitAtEquals(string& key, string& value){          
757         try {
758                 if(value.find_first_of('=') != -1){
759                         key = value.substr(0,value.find_first_of('='));
760                         if ((value.find_first_of('=')+1) <= value.length()) {
761                                 value = value.substr(value.find_first_of('=')+1, value.length());
762                         }
763                 }else{
764                         key = value;
765                         value = 1;
766                 }
767         }
768         catch(exception& e) {
769                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtEquals. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
770                 exit(1);
771         }       
772 }
773 /**************************************************************************************************/
774
775 inline bool inUsersGroups(string groupname, vector<string> Groups) {
776         try {
777                 for (int i = 0; i < Groups.size(); i++) {
778                         if (groupname == Groups[i]) { return true; }
779                 }
780                 return false;
781         }
782         catch(exception& e) {
783                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
784                 exit(1);
785         }       
786 }
787 /**************************************************************************************************/
788 //returns true if any of the strings in first vector are in second vector
789 inline bool inUsersGroups(vector<string> groupnames, vector<string> Groups) {
790         try {
791                 
792                 for (int i = 0; i < groupnames.size(); i++) {
793                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
794                 }
795                 return false;
796         }
797         catch(exception& e) {
798                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
799                 exit(1);
800         }       
801 }
802 /***********************************************************************/
803 //this function determines if the user has given us labels that are smaller than the given label.
804 //if so then it returns true so that the calling function can run the previous valid distance.
805 //it's a "smart" distance function.  It also checks for invalid labels.
806 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
807         try {
808                 
809                 set<string>::iterator it;
810                 vector<float> orderFloat;
811                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
812                 map<string, float>::iterator it2;
813                 float labelFloat;
814                 bool smaller = false;
815                 
816                 //unique is the smallest line
817                 if (label == "unique") {  return false;  }
818                 else { convert(label, labelFloat); }
819                 
820                 //go through users set and make them floats
821                 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
822                         
823                         float temp;
824                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
825                                 convert(*it, temp);
826                                 orderFloat.push_back(temp);
827                                 userMap[*it] = temp;
828                         }else if (*it == "unique") { 
829                                 orderFloat.push_back(-1.0);
830                                 userMap["unique"] = -1.0;
831                         }else {
832                                 if (errorOff == "") {  cout << *it << " is not a valid label." << endl;  }
833                                 userLabels.erase(*it); 
834                                 it--;
835                         }
836                 }
837                 
838                 //sort order
839                 sort(orderFloat.begin(), orderFloat.end());
840                 
841                 /*************************************************/
842                 //is this label bigger than any of the users labels
843                 /*************************************************/
844                                 
845                 //loop through order until you find a label greater than label
846                 for (int i = 0; i < orderFloat.size(); i++) {
847                         if (orderFloat[i] < labelFloat) {
848                                 smaller = true;
849                                 if (orderFloat[i] == -1) { 
850                                         if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
851                                         userLabels.erase("unique");
852                                 }
853                                 else {  
854                                         if (errorOff == "") { cout << "Your file does not include the label " << endl; }
855                                         string s = "";
856                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
857                                                 if (it2->second == orderFloat[i]) {  
858                                                         s = it2->first;  
859                                                         //remove small labels
860                                                         userLabels.erase(s);
861                                                         break;
862                                                 }
863                                         }
864                                         if (errorOff == "") {cout << s <<  ". I will use the next smallest distance. " << endl; }
865                                 }
866                         //since they are sorted once you find a bigger one stop looking
867                         }else { break; }
868                 }
869                 
870                 return smaller;
871                                                 
872         }
873         catch(exception& e) {
874                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function anyLabelsToProcess. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
875                 exit(1);
876         }       
877 }
878
879 /**************************************************************************************************/
880 inline void appendFiles(string temp, string filename) {
881         try{
882                 ofstream output;
883                 ifstream input;
884         
885                 //open output file in append mode
886                 openOutputFileAppend(filename, output);
887                 int ableToOpen = openInputFile(temp, input, "no error");
888                 
889                 if (ableToOpen == 0) { //you opened it
890                         while(char c = input.get()){
891                                 if(input.eof())         {       break;                  }
892                                 else                            {       output << c;    }
893                         }
894                         input.close();
895                 }
896                 
897                 output.close();
898         }
899         catch(exception& e) {
900                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function appendFiles. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
901                 exit(1);
902         }       
903 }
904
905 /**************************************************************************************************/
906 inline string sortFile(string distFile, string outputDir){
907         try {   
908         
909                 //if (outputDir == "") {  outputDir += hasPath(distFile);  }
910                 string outfile = getRootName(distFile) + "sorted.dist";
911
912                 
913                 //if you can, use the unix sort since its been optimized for years
914                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
915                         string command = "sort -n -k +3 " + distFile + " -o " + outfile;
916                         system(command.c_str());
917                 #else //you are stuck with my best attempt...
918                         //windows sort does not have a way to specify a column, only a character in the line
919                         //since we cannot assume that the distance will always be at the the same character location on each line
920                         //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
921                 
922                         //read in file line by file and put distance first
923                         string tempDistFile = distFile + ".temp";
924                         ifstream input;
925                         ofstream output;
926                         openInputFile(distFile, input);
927                         openOutputFile(tempDistFile, output);
928
929                         string firstName, secondName;
930                         float dist;
931                         while (input) {
932                                 input >> firstName >> secondName >> dist;
933                                 output << dist << '\t' << firstName << '\t' << secondName << endl;
934                                 gobble(input);
935                         }
936                         input.close();
937                         output.close();
938                 
939         
940                         //sort using windows sort
941                         string tempOutfile = outfile + ".temp";
942                         string command = "sort " + tempDistFile + " /O " + tempOutfile;
943                         system(command.c_str());
944                 
945                         //read in sorted file and put distance at end again
946                         ifstream input2;
947                         openInputFile(tempOutfile, input2);
948                         openOutputFile(outfile, output);
949                 
950                         while (input2) {
951                                 input2 >> dist >> firstName >> secondName;
952                                 output << firstName << '\t' << secondName << '\t' << dist << endl;
953                                 gobble(input2);
954                         }
955                         input2.close();
956                         output.close();
957                 
958                         //remove temp files
959                         remove(tempDistFile.c_str());
960                         remove(tempOutfile.c_str());
961                 #endif
962                 
963                 return outfile;
964         }
965         catch(exception& e) {
966                 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function sortfile. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
967                 exit(1);
968         }       
969 }
970 /**************************************************************************************************/
971 inline vector<long> setFilePosFasta(string filename, int& num) {
972
973                         vector<long> positions;
974                         ifstream inFASTA;
975                         openInputFile(filename, inFASTA);
976                                 
977                         string input;
978                         while(!inFASTA.eof()){
979                                 input = getline(inFASTA); gobble(inFASTA);
980                                 if (input.length() != 0) {
981                                         if(input[0] == '>'){    long pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);      }
982                                 }
983                         }
984                         inFASTA.close();
985                 
986                         num = positions.size();
987                 
988                         /*FILE * pFile;
989                         long size;
990                 
991                         //get num bytes in file
992                         pFile = fopen (filename.c_str(),"rb");
993                         if (pFile==NULL) perror ("Error opening file");
994                         else{
995                                 fseek (pFile, 0, SEEK_END);
996                                 size=ftell (pFile);
997                                 fclose (pFile);
998                         }*/
999                         
1000                         long size = positions[(positions.size()-1)];
1001                         ifstream in;
1002                         openInputFile(filename, in);
1003                         
1004                         in.seekg(size);
1005                 
1006                         while(char c = in.get()){
1007                                 if(in.eof())            {       break;  }
1008                                 else                            {       size++; }
1009                         }
1010                         in.close();
1011                 
1012                         positions.push_back(size);
1013                 
1014                         return positions;
1015 }
1016 /**************************************************************************************************/
1017 inline vector<long> setFilePosEachLine(string filename, int& num) {
1018
1019                         vector<long> positions;
1020                         ifstream in;
1021                         openInputFile(filename, in);
1022                                 
1023                         string input;
1024                         while(!in.eof()){
1025                                 long lastpos = in.tellg();
1026                                 input = getline(in); gobble(in);
1027                                 if (input.length() != 0) {
1028                                         long pos = in.tellg(); 
1029                                         if (pos != -1) { positions.push_back(pos - input.length() - 1); }
1030                                         else {  positions.push_back(lastpos);  }
1031                                 }
1032                         }
1033                         in.close();
1034                 
1035                         num = positions.size();
1036                 
1037                         FILE * pFile;
1038                         long size;
1039                 
1040                         //get num bytes in file
1041                         pFile = fopen (filename.c_str(),"rb");
1042                         if (pFile==NULL) perror ("Error opening file");
1043                         else{
1044                                 fseek (pFile, 0, SEEK_END);
1045                                 size=ftell (pFile);
1046                                 fclose (pFile);
1047                         }
1048                 
1049                         positions.push_back(size);
1050                 
1051                         return positions;
1052 }
1053
1054 /**************************************************************************************************/
1055 #endif
1056