]> git.donarmstrong.com Git - mothur.git/blob - mothurout.cpp
Changed back to xcode build.
[mothur.git] / mothurout.cpp
1 /*
2  *  mothurOut.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 2/25/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "mothurout.h"
11
12
13 /******************************************************/
14 MothurOut* MothurOut::getInstance() {
15         if( _uniqueInstance == 0) {
16                 _uniqueInstance = new MothurOut();
17         }
18         return _uniqueInstance;
19 }
20 /*********************************************************************************************/
21 void MothurOut::setFileName(string filename)  {
22         try {
23                 logFileName = filename;
24                 
25                 #ifdef USE_MPI
26                         int pid;
27                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
28                                         
29                         if (pid == 0) { //only one process should output to screen
30                 #endif
31                 
32                 openOutputFile(filename, out);
33                 
34                 #ifdef USE_MPI
35                         }
36                 #endif
37         }
38         catch(exception& e) {
39                 errorOut(e, "MothurOut", "setFileName");
40                 exit(1);
41         }
42 }
43 /*********************************************************************************************/
44 void MothurOut::setDefaultPath(string pathname)  {
45         try {
46         
47                 //add / to name if needed
48                 string lastChar = pathname.substr(pathname.length()-1);
49                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
50                         if (lastChar != "/") { pathname += "/"; }
51                 #else
52                         if (lastChar != "\\") { pathname += "\\"; }     
53                 #endif
54                 
55                 defaultPath = pathname;
56                 
57         }
58         catch(exception& e) {
59                 errorOut(e, "MothurOut", "setDefaultPath");
60                 exit(1);
61         }
62 }
63 /*********************************************************************************************/
64 void MothurOut::setOutputDir(string pathname)  {
65         try {
66                 outputDir = pathname;
67         }
68         catch(exception& e) {
69                 errorOut(e, "MothurOut", "setOutputDir");
70                 exit(1);
71         }
72 }
73 /*********************************************************************************************/
74 void MothurOut::closeLog()  {
75         try {
76                 
77                 #ifdef USE_MPI
78                         int pid;
79                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
80                                         
81                         if (pid == 0) { //only one process should output to screen
82                 #endif
83                 
84                 out.close();
85                 
86                 #ifdef USE_MPI
87                         }
88                 #endif
89         }
90         catch(exception& e) {
91                 errorOut(e, "MothurOut", "closeLog");
92                 exit(1);
93         }
94 }
95
96 /*********************************************************************************************/
97 MothurOut::~MothurOut() {
98         try {
99                 _uniqueInstance = 0;
100                 
101         }
102         catch(exception& e) {
103                 errorOut(e, "MothurOut", "MothurOut");
104                 exit(1);
105         }
106 }
107 /*********************************************************************************************/
108 void MothurOut::mothurOut(string output) {
109         try {
110                 
111                 #ifdef USE_MPI
112                         int pid;
113                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
114                                         
115                         if (pid == 0) { //only one process should output to screen
116                 #endif
117                 
118                 cout << output;
119                 out << output;
120                 
121                 #ifdef USE_MPI
122                         }
123                 #endif
124         }
125         catch(exception& e) {
126                 errorOut(e, "MothurOut", "MothurOut");
127                 exit(1);
128         }
129 }
130 /*********************************************************************************************/
131 void MothurOut::mothurOutEndLine() {
132         try {
133                 #ifdef USE_MPI
134                         int pid;
135                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
136                                         
137                         if (pid == 0) { //only one process should output to screen
138                 #endif
139                 
140                 cout << endl;
141                 out << endl;
142                 
143                 #ifdef USE_MPI
144                         }
145                 #endif
146         }
147         catch(exception& e) {
148                 errorOut(e, "MothurOut", "MothurOutEndLine");
149                 exit(1);
150         }
151 }
152 /*********************************************************************************************/
153 void MothurOut::mothurOutJustToLog(string output) {
154         try {
155                 #ifdef USE_MPI
156                         int pid;
157                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
158                                         
159                         if (pid == 0) { //only one process should output to screen
160                 #endif
161                 
162                 out << output;
163                 
164                 #ifdef USE_MPI
165                         }
166                 #endif
167         }
168         catch(exception& e) {
169                 errorOut(e, "MothurOut", "MothurOutJustToLog");
170                 exit(1);
171         }
172 }
173 /*********************************************************************************************/
174 void MothurOut::errorOut(exception& e, string object, string function) {
175         //double vm, rss;
176         //mem_usage(vm, rss);
177         
178         mothurOut("[ERROR]: ");
179         mothurOut(toString(e.what()));
180         mothurOut(" has occurred in the " + object + " class function " + function + ". Please contact Pat Schloss at mothur.bugs@gmail.com, and be sure to include the mothur.logFile with your inquiry.");
181         mothurOutEndLine();
182 }
183 /*********************************************************************************************/
184 //The following was originally from http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c 
185 // process_mem_usage(double &, double &) - takes two doubles by reference,
186 // attempts to read the system-dependent data for a process' virtual memory
187 // size and resident set size, and return the results in KB.
188 //
189 // On failure, returns 0.0, 0.0
190 int MothurOut::mem_usage(double& vm_usage, double& resident_set) {
191   #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
192   
193            vm_usage     = 0.0;
194            resident_set = 0.0;
195
196            // 'file' stat seems to give the most reliable results
197            //
198            ifstream stat_stream("/proc/self/stat",ios_base::in);
199
200            // dummy vars for leading entries in stat that we don't care about
201            //
202            string pid, comm, state, ppid, pgrp, session, tty_nr;
203            string tpgid, flags, minflt, cminflt, majflt, cmajflt;
204            string utime, stime, cutime, cstime, priority, nice;
205            string O, itrealvalue, starttime;
206
207            // the two fields we want
208            //
209            unsigned long vsize;
210            long rss;
211
212            stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
213                                    >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
214                                    >> utime >> stime >> cutime >> cstime >> priority >> nice
215                                    >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
216
217            long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
218            vm_usage     = vsize / 1024.0;
219            resident_set = rss * page_size_kb;
220            
221            mothurOut("Memory Usage: vm = " + toString(vm_usage) + " rss = " + toString(resident_set) + "\n");
222                 return 0;
223
224         #else
225 /*              //windows memory usage
226                 // Get the list of process identifiers.
227                 DWORD aProcesses[1024], cbNeeded, cProcesses;
228                 
229                 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){ return 1; }
230
231                 // Calculate how many process identifiers were returned.
232                 cProcesses = cbNeeded / sizeof(DWORD);
233
234                 // Print the memory usage for each process
235                 for (int i = 0; i < cProcesses; i++ ) {
236                         DWORD processID = aProcesses[i];
237                         
238                         PROCESS_MEMORY_COUNTERS pmc;
239
240                         HANDLE hProcess = OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), FALSE, processID);
241
242                         // Print the process identifier.
243                         printf( "\nProcess ID: %u\n", processID);
244                         
245                         if (NULL != hProcess) {
246
247                                 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) {
248                                         printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
249                                         printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );
250                                         printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
251                                         printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );
252                                         printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );
253                                         printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );
254                                         printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );
255                                         printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage ); 
256                                         printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );
257                                 }
258                                 CloseHandle(hProcess);
259                         }
260                 }
261 */
262                         return 0;
263
264         #endif
265 }
266
267
268 /***********************************************************************/
269 int MothurOut::openOutputFileAppend(string fileName, ofstream& fileHandle){
270         try {
271                 fileName = getFullPathName(fileName);
272                 
273                 fileHandle.open(fileName.c_str(), ios::app);
274                 if(!fileHandle) {
275                         mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
276                         return 1;
277                 }
278                 else {
279                         return 0;
280                 }
281         }
282         catch(exception& e) {
283                 errorOut(e, "MothurOut", "openOutputFileAppend");
284                 exit(1);
285         }
286 }
287 /***********************************************************************/
288 void MothurOut::gobble(istream& f){
289         try {
290                 
291                 char d;
292                 while(isspace(d=f.get()))               { ;}
293                 f.putback(d);
294         }
295         catch(exception& e) {
296                 errorOut(e, "MothurOut", "gobble");
297                 exit(1);
298         }
299 }
300 /***********************************************************************/
301 void MothurOut::gobble(istringstream& f){
302         try {
303                 char d;
304                 while(isspace(d=f.get()))               {;}
305                 f.putback(d);
306         }
307         catch(exception& e) {
308                 errorOut(e, "MothurOut", "gobble");
309                 exit(1);
310         }
311 }
312
313 /***********************************************************************/
314
315 string MothurOut::getline(istringstream& fileHandle) {
316         try {
317         
318                 string line = "";
319                 
320                 while (!fileHandle.eof())       {
321                         //get next character
322                         char c = fileHandle.get(); 
323                         
324                         //are you at the end of the line
325                         if ((c == '\n') || (c == '\r') || (c == '\f')){  break; }       
326                         else {          line += c;              }
327                 }
328                 
329                 return line;
330                 
331         }
332         catch(exception& e) {
333                 errorOut(e, "MothurOut", "getline");
334                 exit(1);
335         }
336 }
337 /***********************************************************************/
338
339 string MothurOut::getline(ifstream& fileHandle) {
340         try {
341         
342                 string line = "";
343                 
344                 while (!fileHandle.eof())       {
345                         //get next character
346                         char c = fileHandle.get(); 
347                         
348                         //are you at the end of the line
349                         if ((c == '\n') || (c == '\r') || (c == '\f')){  break; }       
350                         else {          line += c;              }
351                 }
352                 
353                 return line;
354                 
355         }
356         catch(exception& e) {
357                 errorOut(e, "MothurOut", "getline");
358                 exit(1);
359         }
360 }
361 /***********************************************************************/
362
363 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
364 #ifdef USE_COMPRESSION
365 inline bool endsWith(string s, const char * suffix){
366   size_t suffixLength = strlen(suffix);
367   return s.size() >= suffixLength && s.substr(s.size() - suffixLength, suffixLength).compare(suffix) == 0;
368 }
369 #endif
370 #endif
371
372 string MothurOut::getRootName(string longName){
373         try {
374         
375                 string rootName = longName;
376
377 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
378 #ifdef USE_COMPRESSION
379     if (endsWith(rootName, ".gz") || endsWith(rootName, ".bz2")) {
380       int pos = rootName.find_last_of('.');
381       rootName = rootName.substr(0, pos);
382       cerr << "shortening " << longName << " to " << rootName << "\n";
383     }
384 #endif
385 #endif
386                 if(rootName.find_last_of(".") != rootName.npos){
387                         int pos = rootName.find_last_of('.')+1;
388                         rootName = rootName.substr(0, pos);
389                 }
390
391                 return rootName;
392         }
393         catch(exception& e) {
394                 errorOut(e, "MothurOut", "getRootName");
395                 exit(1);
396         }
397 }
398 /***********************************************************************/
399
400 string MothurOut::getSimpleName(string longName){
401         try {
402                 string simpleName = longName;
403                 
404                 size_t found;
405                 found=longName.find_last_of("/\\");
406
407                 if(found != longName.npos){
408                         simpleName = longName.substr(found+1);
409                 }
410                 
411                 return simpleName;
412         }
413         catch(exception& e) {
414                 errorOut(e, "MothurOut", "getSimpleName");
415                 exit(1);
416         }
417 }
418
419 /***********************************************************************/
420
421 string MothurOut::getPathName(string longName){
422         try {
423                 string rootPathName = longName;
424                 
425                 if(longName.find_last_of("/\\") != longName.npos){
426                         int pos = longName.find_last_of("/\\")+1;
427                         rootPathName = longName.substr(0, pos);
428                 }
429                 
430                 return rootPathName;
431         }
432         catch(exception& e) {
433                 errorOut(e, "MothurOut", "getPathName");
434                 exit(1);
435         }       
436
437 }
438 /***********************************************************************/
439
440 string MothurOut::hasPath(string longName){
441         try {
442                 string path = "";
443                 
444                 size_t found;
445                 found=longName.find_last_of("~/\\");
446
447                 if(found != longName.npos){
448                         path = longName.substr(0, found+1);
449                 }
450                 
451                 return path;
452         }
453         catch(exception& e) {
454                 errorOut(e, "MothurOut", "hasPath");
455                 exit(1);
456         }       
457 }
458
459 /***********************************************************************/
460
461 string MothurOut::getExtension(string longName){
462         try {
463                 string extension = longName;
464                 
465                 if(longName.find_last_of('.') != longName.npos){
466                         int pos = longName.find_last_of('.');
467                         extension = longName.substr(pos, longName.length());
468                 }
469                 
470                 return extension;
471         }
472         catch(exception& e) {
473                 errorOut(e, "MothurOut", "getExtension");
474                 exit(1);
475         }       
476 }
477 /***********************************************************************/
478 bool MothurOut::isBlank(string fileName){
479         try {
480                 
481                 fileName = getFullPathName(fileName);
482                 
483                 ifstream fileHandle;
484                 fileHandle.open(fileName.c_str());
485                 if(!fileHandle) {
486                         mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
487                         return false;
488                 }else {
489                         //check for blank file
490                         gobble(fileHandle);
491                         if (fileHandle.eof()) { fileHandle.close(); return true;  }
492                         fileHandle.close();
493                 }
494                 return false;
495         }
496         catch(exception& e) {
497                 errorOut(e, "MothurOut", "isBlank");
498                 exit(1);
499         }       
500 }
501 /***********************************************************************/
502
503 string MothurOut::getFullPathName(string fileName){
504         try{
505         
506         string path = hasPath(fileName);
507         string newFileName;
508         int pos;
509         
510         if (path == "") { return fileName; } //its a simple name
511         else { //we need to complete the pathname
512                 // ex. ../../../filename 
513                 // cwd = /user/work/desktop
514                                 
515                 string cwd;
516                 //get current working directory 
517                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)   
518                         
519                         if (path.find("~") != -1) { //go to home directory
520                                 string homeDir;
521                         
522                                 char *homepath = NULL;
523                                 homepath = getenv ("HOME");
524                                 if ( homepath != NULL) { homeDir = homepath; }
525                                 else { homeDir = "";  }
526
527                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
528                                 return newFileName;
529                         }else { //find path
530                                 if (path.rfind("./") == string::npos) { return fileName; } //already complete name
531                                 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
532                                 
533                                 //char* cwdpath = new char[1024];
534                                 //size_t size;
535                                 //cwdpath=getcwd(cwdpath,size);
536                                 //cwd = cwdpath;
537                                 
538                                 char *cwdpath = NULL;
539                                 cwdpath = getcwd(NULL, 0); // or _getcwd
540                                 if ( cwdpath != NULL) { cwd = cwdpath; }
541                                 else { cwd = "";  }
542
543                                 
544                                 //rip off first '/'
545                                 string simpleCWD;
546                                 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
547                                 
548                                 //break apart the current working directory
549                                 vector<string> dirs;
550                                 while (simpleCWD.find_first_of('/') != string::npos) {
551                                         string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
552                                         simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
553                                         dirs.push_back(dir);
554                                 }
555                                 //get last one              // ex. ../../../filename = /user/work/desktop/filename
556                                 dirs.push_back(simpleCWD);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
557                                 
558                         
559                                 int index = dirs.size()-1;
560                 
561                                 while((pos = path.rfind("./")) != string::npos) { //while you don't have a complete path
562                                         if (pos == 0) { break;  //you are at the end
563                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
564                                                 path = path.substr(0, pos-1);
565                                                 index--;
566                                                 if (index == 0) {  break; }
567                                         }else if (path[(pos-1)] == '/') { //you want the current working dir ./
568                                                 path = path.substr(0, pos);
569                                         }else if (pos == 1) { break;  //you are at the end
570                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
571                                 }
572                         
573                                 for (int i = index; i >= 0; i--) {
574                                         newFileName = dirs[i] +  "/" + newFileName;             
575                                 }
576                                 
577                                 newFileName =  "/" +  newFileName;
578                                 return newFileName;
579                         }       
580                 #else
581                         if (path.find("~") != string::npos) { //go to home directory
582                                 string homeDir = getenv ("HOMEPATH");
583                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
584                                 return newFileName;
585                         }else { //find path
586                                 if (path.rfind(".\\") == string::npos) { return fileName; } //already complete name
587                                 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
588                                                         
589                                 char *cwdpath = NULL;
590                                 cwdpath = getcwd(NULL, 0); // or _getcwd
591                                 if ( cwdpath != NULL) { cwd = cwdpath; }
592                                 else { cwd = "";  }
593                                 
594                                 //break apart the current working directory
595                                 vector<string> dirs;
596                                 while (cwd.find_first_of('\\') != -1) {
597                                         string dir = cwd.substr(0,cwd.find_first_of('\\'));
598                                         cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
599                                         dirs.push_back(dir);
600                 
601                                 }
602                                 //get last one
603                                 dirs.push_back(cwd);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
604                                         
605                                 int index = dirs.size()-1;
606                                         
607                                 while((pos = path.rfind(".\\")) != string::npos) { //while you don't have a complete path
608                                         if (pos == 0) { break;  //you are at the end
609                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
610                                                 path = path.substr(0, pos-1);
611                                                 index--;
612                                                 if (index == 0) {  break; }
613                                         }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
614                                                 path = path.substr(0, pos);
615                                         }else if (pos == 1) { break;  //you are at the end
616                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
617                                 }
618                         
619                                 for (int i = index; i >= 0; i--) {
620                                         newFileName = dirs[i] +  "\\" + newFileName;            
621                                 }
622                                 
623                                 return newFileName;
624                         }
625                         
626                 #endif
627         }
628         }
629         catch(exception& e) {
630                 errorOut(e, "MothurOut", "getFullPathName");
631                 exit(1);
632         }       
633 }
634 /***********************************************************************/
635
636 int MothurOut::openInputFile(string fileName, ifstream& fileHandle, string m){
637         try {
638                         //get full path name
639                         string completeFileName = getFullPathName(fileName);
640 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
641 #ifdef USE_COMPRESSION
642       // check for gzipped or bzipped file
643       if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
644         string tempName = string(tmpnam(0));
645         mkfifo(tempName.c_str(), 0666);
646         int fork_result = fork();
647         if (fork_result < 0) {
648           cerr << "Error forking.\n";
649           exit(1);
650         } else if (fork_result == 0) {
651           string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
652           cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
653           system(command.c_str());
654           cerr << "Done decompressing " << completeFileName << "\n";
655           remove(tempName.c_str());
656           exit(EXIT_SUCCESS);
657         } else {
658           cerr << "waiting on child process " << fork_result << "\n";
659           completeFileName = tempName;
660         }
661       }
662 #endif
663 #endif
664                         fileHandle.open(completeFileName.c_str());
665                         if(!fileHandle) {
666                                 //mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
667                                 return 1;
668                         }else {
669                                 //check for blank file
670                                 gobble(fileHandle);
671                                 return 0;
672                         }
673         }
674         catch(exception& e) {
675                 errorOut(e, "MothurOut", "openInputFile - no Error");
676                 exit(1);
677         }
678 }
679 /***********************************************************************/
680
681 int MothurOut::openInputFile(string fileName, ifstream& fileHandle){
682         try {
683
684                 //get full path name
685                 string completeFileName = getFullPathName(fileName);
686 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
687 #ifdef USE_COMPRESSION
688   // check for gzipped or bzipped file
689   if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
690     string tempName = string(tmpnam(0));
691     mkfifo(tempName.c_str(), 0666);
692     int fork_result = fork();
693     if (fork_result < 0) {
694       cerr << "Error forking.\n";
695       exit(1);
696     } else if (fork_result == 0) {
697       string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
698       cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
699       system(command.c_str());
700       cerr << "Done decompressing " << completeFileName << "\n";
701       remove(tempName.c_str());
702       exit(EXIT_SUCCESS);
703     } else {
704       cerr << "waiting on child process " << fork_result << "\n";
705       completeFileName = tempName;
706     }
707   }
708 #endif
709 #endif
710
711                 fileHandle.open(completeFileName.c_str());
712                 if(!fileHandle) {
713                         mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
714                         return 1;
715                 }
716                 else {
717                         //check for blank file
718                         gobble(fileHandle);
719                         if (fileHandle.eof()) { mothurOut("[ERROR]: " + completeFileName + " is blank. Please correct."); mothurOutEndLine();  }
720                         
721                         return 0;
722                 }
723         }
724         catch(exception& e) {
725                 errorOut(e, "MothurOut", "openInputFile");
726                 exit(1);
727         }       
728 }
729 /***********************************************************************/
730
731 int MothurOut::renameFile(string oldName, string newName){
732         try {
733                 ifstream inTest;
734                 int exist = openInputFile(newName, inTest, "");
735                 
736         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
737                 if (exist == 0) { //you could open it so you want to delete it
738                         inTest.close();
739                         string command = "rm " + newName;
740                         system(command.c_str());
741                 }
742                                 
743                 string command = "mv " + oldName + " " + newName;
744                 system(command.c_str());
745         #else
746                 remove(newName.c_str());
747                 int renameOk = rename(oldName.c_str(), newName.c_str());
748         #endif
749                 return 0;
750                 
751         }
752         catch(exception& e) {
753                 errorOut(e, "MothurOut", "renameFile");
754                 exit(1);
755         }       
756 }
757
758 /***********************************************************************/
759
760 int MothurOut::openOutputFile(string fileName, ofstream& fileHandle){
761         try { 
762         
763                 string completeFileName = getFullPathName(fileName);
764 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
765 #ifdef USE_COMPRESSION
766     // check for gzipped file
767     if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
768       string tempName = string(tmpnam(0));
769       mkfifo(tempName.c_str(), 0666);
770       cerr << "Compressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
771       int fork_result = fork();
772       if (fork_result < 0) {
773         cerr << "Error forking.\n";
774         exit(1);
775       } else if (fork_result == 0) {
776         string command = string(endsWith(completeFileName, ".gz") ?  "gzip" : "bzip2") + " -v > " + completeFileName + string(" < ") + tempName;
777         system(command.c_str());
778         exit(0);
779       } else {
780         completeFileName = tempName;
781       }
782     }
783 #endif
784 #endif
785                 fileHandle.open(completeFileName.c_str(), ios::trunc);
786                 if(!fileHandle) {
787                         mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
788                         return 1;
789                 }
790                 else {
791                         return 0;
792                 }
793         }
794         catch(exception& e) {
795                 errorOut(e, "MothurOut", "openOutputFile");
796                 exit(1);
797         }       
798
799 }
800
801 /**************************************************************************************************/
802 void MothurOut::appendFiles(string temp, string filename) {
803         try{
804                 ofstream output;
805                 ifstream input;
806         
807                 //open output file in append mode
808                 openOutputFileAppend(filename, output);
809                 int ableToOpen = openInputFile(temp, input, "no error");
810                 //int ableToOpen = openInputFile(temp, input);
811                 
812                 if (ableToOpen == 0) { //you opened it
813                         while(char c = input.get()){
814                                 if(input.eof())         {       break;                  }
815                                 else                            {       output << c;    }
816                         }
817                         input.close();
818                 }
819                 
820                 output.close();
821         }
822         catch(exception& e) {
823                 errorOut(e, "MothurOut", "appendFiles");
824                 exit(1);
825         }       
826 }
827
828 /**************************************************************************************************/
829 string MothurOut::sortFile(string distFile, string outputDir){
830         try {   
831         
832                 //if (outputDir == "") {  outputDir += hasPath(distFile);  }
833                 string outfile = getRootName(distFile) + "sorted.dist";
834
835                 
836                 //if you can, use the unix sort since its been optimized for years
837                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
838                         string command = "sort -n -k +3 " + distFile + " -o " + outfile;
839                         system(command.c_str());
840                 #else //you are stuck with my best attempt...
841                         //windows sort does not have a way to specify a column, only a character in the line
842                         //since we cannot assume that the distance will always be at the the same character location on each line
843                         //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
844                 
845                         //read in file line by file and put distance first
846                         string tempDistFile = distFile + ".temp";
847                         ifstream input;
848                         ofstream output;
849                         openInputFile(distFile, input);
850                         openOutputFile(tempDistFile, output);
851
852                         string firstName, secondName;
853                         float dist;
854                         while (input) {
855                                 input >> firstName >> secondName >> dist;
856                                 output << dist << '\t' << firstName << '\t' << secondName << endl;
857                                 gobble(input);
858                         }
859                         input.close();
860                         output.close();
861                 
862         
863                         //sort using windows sort
864                         string tempOutfile = outfile + ".temp";
865                         string command = "sort " + tempDistFile + " /O " + tempOutfile;
866                         system(command.c_str());
867                 
868                         //read in sorted file and put distance at end again
869                         ifstream input2;
870                         openInputFile(tempOutfile, input2);
871                         openOutputFile(outfile, output);
872                 
873                         while (input2) {
874                                 input2 >> dist >> firstName >> secondName;
875                                 output << firstName << '\t' << secondName << '\t' << dist << endl;
876                                 gobble(input2);
877                         }
878                         input2.close();
879                         output.close();
880                 
881                         //remove temp files
882                         remove(tempDistFile.c_str());
883                         remove(tempOutfile.c_str());
884                 #endif
885                 
886                 return outfile;
887         }
888         catch(exception& e) {
889                 errorOut(e, "MothurOut", "sortFile");
890                 exit(1);
891         }       
892 }
893 /**************************************************************************************************/
894 vector<unsigned long int> MothurOut::setFilePosFasta(string filename, int& num) {
895         try {
896                         vector<unsigned long int> positions;
897                         ifstream inFASTA;
898                         openInputFile(filename, inFASTA);
899                                                 
900                         string input;
901                         while(!inFASTA.eof()){
902                                 input = getline(inFASTA); 
903                                 if (input.length() != 0) {
904                                         if(input[0] == '>'){    unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
905                                 }
906                                 gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
907                         }
908                         inFASTA.close();
909                 
910                         num = positions.size();
911                 
912                         /*FILE * pFile;
913                         long size;
914                 
915                         //get num bytes in file
916                         pFile = fopen (filename.c_str(),"rb");
917                         if (pFile==NULL) perror ("Error opening file");
918                         else{
919                                 fseek (pFile, 0, SEEK_END);
920                                 size=ftell (pFile);
921                                 fclose (pFile);
922                         }*/
923                         
924                         unsigned long int size = positions[(positions.size()-1)];
925                         ifstream in;
926                         openInputFile(filename, in);
927                         
928                         in.seekg(size);
929                 
930                         while(in.get()){
931                                 if(in.eof())            {       break;  }
932                                 else                            {       size++; }
933                         }
934                         in.close();
935                 
936                         positions.push_back(size);
937                 
938                         return positions;
939         }
940         catch(exception& e) {
941                 errorOut(e, "MothurOut", "setFilePosFasta");
942                 exit(1);
943         }
944 }
945 /**************************************************************************************************/
946 vector<unsigned long int> MothurOut::setFilePosEachLine(string filename, int& num) {
947         try {
948                         filename = getFullPathName(filename);
949                         
950                         vector<unsigned long int> positions;
951                         ifstream in;
952                         openInputFile(filename, in);
953                                 
954                         string input;
955                         while(!in.eof()){
956                                 unsigned long int lastpos = in.tellg();
957                                 input = getline(in); 
958                                 if (input.length() != 0) {
959                                         unsigned long int pos = in.tellg(); 
960                                         if (pos != -1) { positions.push_back(pos - input.length() - 1); }
961                                         else {  positions.push_back(lastpos);  }
962                                 }
963                                 gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
964                         }
965                         in.close();
966                 
967                         num = positions.size();
968                 
969                         FILE * pFile;
970                         unsigned long int size;
971                         
972                         //get num bytes in file
973                         pFile = fopen (filename.c_str(),"rb");
974                         if (pFile==NULL) perror ("Error opening file");
975                         else{
976                                 fseek (pFile, 0, SEEK_END);
977                                 size=ftell (pFile);
978                                 fclose (pFile);
979                         }
980                 
981                         positions.push_back(size);
982                 
983                         return positions;
984         }
985         catch(exception& e) {
986                 errorOut(e, "MothurOut", "setFilePosEachLine");
987                 exit(1);
988         }
989 }
990 /**************************************************************************************************/
991
992 vector<unsigned long int> MothurOut::divideFile(string filename, int& proc) {
993         try{
994         
995                 vector<unsigned long int> filePos;
996                 filePos.push_back(0);
997                 
998                 FILE * pFile;
999                 unsigned long int size;
1000                 
1001                 filename = getFullPathName(filename);
1002                 
1003                 //get num bytes in file
1004                 pFile = fopen (filename.c_str(),"rb");
1005                 if (pFile==NULL) perror ("Error opening file");
1006                 else{
1007                         fseek (pFile, 0, SEEK_END);
1008                         size=ftell (pFile);
1009                         fclose (pFile);
1010                 }
1011         
1012                 //estimate file breaks
1013                 unsigned long int chunkSize = 0;
1014                 chunkSize = size / proc;
1015
1016                 //file to small to divide by processors
1017                 if (chunkSize == 0)  {  proc = 1;       filePos.push_back(size); return filePos;        }
1018         
1019                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
1020                 for (int i = 0; i < proc; i++) {
1021                         unsigned long int spot = (i+1) * chunkSize;
1022                         
1023                         ifstream in;
1024                         openInputFile(filename, in);
1025                         in.seekg(spot);
1026                         
1027                         //look for next '>'
1028                         unsigned long int newSpot = spot;
1029                         while (!in.eof()) {
1030                            char c = in.get();
1031                            if (c == '>') {   in.putback(c); newSpot = in.tellg(); break;  }
1032                         }
1033                 
1034                         //there was not another sequence before the end of the file
1035                         unsigned long int sanityPos = in.tellg();
1036
1037                         if (sanityPos == -1) {  break;  }
1038                         else {  filePos.push_back(newSpot);  }
1039                         
1040                         in.close();
1041                 }
1042                 
1043                 //save end pos
1044                 filePos.push_back(size);
1045
1046                 //sanity check filePos
1047                 for (int i = 0; i < (filePos.size()-1); i++) {
1048                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
1049                 }
1050
1051                 proc = (filePos.size() - 1);
1052                 
1053                 return filePos;
1054         }
1055         catch(exception& e) {
1056                 errorOut(e, "MothurOut", "divideFile");
1057                 exit(1);
1058         }
1059 }
1060
1061 /***********************************************************************/
1062
1063 bool MothurOut::isTrue(string f){
1064         try {
1065                 
1066                 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
1067                 
1068                 if ((f == "TRUE") || (f == "T")) {      return true;    }
1069                 else {  return false;  }
1070         }
1071         catch(exception& e) {
1072                 errorOut(e, "MothurOut", "isTrue");
1073                 exit(1);
1074         }
1075 }
1076
1077 /***********************************************************************/
1078
1079 float MothurOut::roundDist(float dist, int precision){
1080         try {
1081                 return int(dist * precision + 0.5)/float(precision);
1082         }
1083         catch(exception& e) {
1084                 errorOut(e, "MothurOut", "roundDist");
1085                 exit(1);
1086         }
1087 }
1088 /***********************************************************************/
1089
1090 float MothurOut::ceilDist(float dist, int precision){
1091         try {
1092                 return int(ceil(dist * precision))/float(precision);
1093         }
1094         catch(exception& e) {
1095                 errorOut(e, "MothurOut", "ceilDist");
1096                 exit(1);
1097         }
1098 }
1099
1100 /***********************************************************************/
1101
1102 int MothurOut::getNumNames(string names){
1103         try {
1104                 int count = 0;
1105                 
1106                 if(names != ""){
1107                         count = 1;
1108                         for(int i=0;i<names.size();i++){
1109                                 if(names[i] == ','){
1110                                         count++;
1111                                 }
1112                         }
1113                 }
1114                 
1115                 return count;
1116         }
1117         catch(exception& e) {
1118                 errorOut(e, "MothurOut", "getNumNames");
1119                 exit(1);
1120         }
1121 }
1122
1123 /**************************************************************************************************/
1124
1125 vector<vector<double> > MothurOut::binomial(int maxOrder){
1126         try {
1127         vector<vector<double> > binomial(maxOrder+1);
1128         
1129     for(int i=0;i<=maxOrder;i++){
1130                 binomial[i].resize(maxOrder+1);
1131                 binomial[i][0]=1;
1132                 binomial[0][i]=0;
1133     }
1134     binomial[0][0]=1;
1135         
1136     binomial[1][0]=1;
1137     binomial[1][1]=1;
1138         
1139     for(int i=2;i<=maxOrder;i++){
1140                 binomial[1][i]=0;
1141     }
1142         
1143     for(int i=2;i<=maxOrder;i++){
1144                 for(int j=1;j<=maxOrder;j++){
1145                         if(i==j){       binomial[i][j]=1;                                                                       }
1146                         if(j>i) {       binomial[i][j]=0;                                                                       }
1147                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
1148                 }
1149     }
1150         
1151         return binomial;
1152         
1153         }
1154         catch(exception& e) {
1155                 errorOut(e, "MothurOut", "binomial");
1156                 exit(1);
1157         }
1158 }
1159 /**************************************************************************************************/
1160 unsigned int MothurOut::fromBase36(string base36){
1161         try {
1162                 unsigned int num = 0;
1163                 
1164                 map<char, int> converts;
1165                 converts['A'] = 0;
1166                 converts['a'] = 0;
1167                 converts['B'] = 1;
1168                 converts['b'] = 1;
1169                 converts['C'] = 2;
1170                 converts['c'] = 2;
1171                 converts['D'] = 3;
1172                 converts['d'] = 3;
1173                 converts['E'] = 4;
1174                 converts['e'] = 4;
1175                 converts['F'] = 5;
1176                 converts['f'] = 5;
1177                 converts['G'] = 6;
1178                 converts['g'] = 6;
1179                 converts['H'] = 7;
1180                 converts['h'] = 7;
1181                 converts['I'] = 8;
1182                 converts['i'] = 8;
1183                 converts['J'] = 9;
1184                 converts['j'] = 9;
1185                 converts['K'] = 10;
1186                 converts['k'] = 10;
1187                 converts['L'] = 11;
1188                 converts['l'] = 11;
1189                 converts['M'] = 12;
1190                 converts['m'] = 12;
1191                 converts['N'] = 13;
1192                 converts['n'] = 13;
1193                 converts['O'] = 14;
1194                 converts['o'] = 14;
1195                 converts['P'] = 15;
1196                 converts['p'] = 15;
1197                 converts['Q'] = 16;
1198                 converts['q'] = 16;
1199                 converts['R'] = 17;
1200                 converts['r'] = 17;
1201                 converts['S'] = 18;
1202                 converts['s'] = 18;
1203                 converts['T'] = 19;
1204                 converts['t'] = 19;
1205                 converts['U'] = 20;
1206                 converts['u'] = 20;
1207                 converts['V'] = 21;
1208                 converts['v'] = 21;
1209                 converts['W'] = 22;
1210                 converts['w'] = 22;
1211                 converts['X'] = 23;
1212                 converts['x'] = 23;
1213                 converts['Y'] = 24;
1214                 converts['y'] = 24;
1215                 converts['Z'] = 25;
1216                 converts['z'] = 25;
1217                 converts['0'] = 26;
1218                 converts['1'] = 27;
1219                 converts['2'] = 28;
1220                 converts['3'] = 29;
1221                 converts['4'] = 30;
1222                 converts['5'] = 31;
1223                 converts['6'] = 32;
1224                 converts['7'] = 33;
1225                 converts['8'] = 34;
1226                 converts['9'] = 35;             
1227                 
1228                 int i = 0;
1229                 while (i < base36.length()) {
1230                         char c = base36[i];
1231                         num = 36 * num + converts[c];
1232                         i++;
1233                 }
1234                 
1235                 return num;
1236                 
1237         }
1238         catch(exception& e) {
1239                 errorOut(e, "MothurOut", "fromBase36");
1240                 exit(1);
1241         }
1242 }
1243 /***********************************************************************/
1244
1245 int MothurOut::factorial(int num){
1246         try {
1247                 int total = 1;
1248                 
1249                 for (int i = 1; i <= num; i++) {
1250                         total *= i;
1251                 }
1252                 
1253                 return total;
1254         }
1255         catch(exception& e) {
1256                 errorOut(e, "MothurOut", "factorial");
1257                 exit(1);
1258         }
1259 }
1260 /***********************************************************************/
1261
1262 int MothurOut::getNumSeqs(ifstream& file){
1263         try {
1264                 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1265                 file.seekg(0);
1266                 return numSeqs;
1267         }
1268         catch(exception& e) {
1269                 errorOut(e, "MothurOut", "getNumSeqs");
1270                 exit(1);
1271         }       
1272 }
1273 /***********************************************************************/
1274 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1275         try {
1276                 string input;
1277                 numSeqs = 0;
1278                 while(!file.eof()){
1279                         input = getline(file);
1280                         if (input.length() != 0) {
1281                                 if(input[0] == '>'){ numSeqs++; }
1282                         }
1283                 }
1284         }
1285         catch(exception& e) {
1286                 errorOut(e, "MothurOut", "getNumSeqs");
1287                 exit(1);
1288         }       
1289 }
1290 /***********************************************************************/
1291
1292 //This function parses the estimator options and puts them in a vector
1293 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1294         try {
1295                 string individual = "";
1296                 int estimLength = estim.size();
1297                 for(int i=0;i<estimLength;i++){
1298                         if(estim[i] == symbol){
1299                                 container.push_back(individual);
1300                                 individual = "";                                
1301                         }
1302                         else{
1303                                 individual += estim[i];
1304                         }
1305                 }
1306                 container.push_back(individual);
1307
1308         }
1309         catch(exception& e) {
1310                 errorOut(e, "MothurOut", "splitAtChar");
1311                 exit(1);
1312         }       
1313 }
1314
1315 /***********************************************************************/
1316
1317 //This function parses the estimator options and puts them in a vector
1318 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1319         try {
1320                 string individual = "";
1321                 int estimLength = estim.size();
1322                 for(int i=0;i<estimLength;i++){
1323                         if(estim[i] == '-'){
1324                                 container.push_back(individual);
1325                                 individual = "";                                
1326                         }
1327                         else{
1328                                 individual += estim[i];
1329                         }
1330                 }
1331                 container.push_back(individual);
1332
1333         
1334         /*      string individual;
1335                 
1336                 while (estim.find_first_of('-') != -1) {
1337                         individual = estim.substr(0,estim.find_first_of('-'));
1338                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1339                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1340                                 container.push_back(individual);
1341                         }
1342                 }
1343                 //get last one
1344                 container.push_back(estim); */
1345         }
1346         catch(exception& e) {
1347                 errorOut(e, "MothurOut", "splitAtDash");
1348                 exit(1);
1349         }       
1350 }
1351
1352 /***********************************************************************/
1353 //This function parses the label options and puts them in a set
1354 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1355         try {
1356                 string individual = "";
1357                 int estimLength = estim.size();
1358                 for(int i=0;i<estimLength;i++){
1359                         if(estim[i] == '-'){
1360                                 container.insert(individual);
1361                                 individual = "";                                
1362                         }
1363                         else{
1364                                 individual += estim[i];
1365                         }
1366                 }
1367                 container.insert(individual);
1368
1369         //      string individual;
1370                 
1371         //      while (estim.find_first_of('-') != -1) {
1372         //              individual = estim.substr(0,estim.find_first_of('-'));
1373         //              if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1374         //                      estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1375         //                      container.insert(individual);
1376         //              }
1377         //      }
1378                 //get last one
1379         //      container.insert(estim);
1380         
1381         }
1382         catch(exception& e) {
1383                 errorOut(e, "MothurOut", "splitAtDash");
1384                 exit(1);
1385         }       
1386 }
1387 /***********************************************************************/
1388 //This function parses the line options and puts them in a set
1389 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1390         try {
1391                 string individual;
1392                 int lineNum;
1393                 
1394                 while (estim.find_first_of('-') != -1) {
1395                         individual = estim.substr(0,estim.find_first_of('-'));
1396                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1397                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1398                                 convert(individual, lineNum); //convert the string to int
1399                                 container.insert(lineNum);
1400                         }
1401                 }
1402                 //get last one
1403                 convert(estim, lineNum); //convert the string to int
1404                 container.insert(lineNum);
1405         }
1406         catch(exception& e) {
1407                 errorOut(e, "MothurOut", "splitAtDash");
1408                 exit(1);
1409         }       
1410 }
1411 /***********************************************************************/
1412 //This function parses the a string and puts peices in a vector
1413 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1414         try {
1415                 string individual = "";
1416                 int estimLength = estim.size();
1417                 for(int i=0;i<estimLength;i++){
1418                         if(estim[i] == ','){
1419                                 container.push_back(individual);
1420                                 individual = "";                                
1421                         }
1422                         else{
1423                                 individual += estim[i];
1424                         }
1425                 }
1426                 container.push_back(individual);
1427                 
1428                 
1429                 
1430                 
1431 //              string individual;
1432 //              
1433 //              while (estim.find_first_of(',') != -1) {
1434 //                      individual = estim.substr(0,estim.find_first_of(','));
1435 //                      if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1436 //                              estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1437 //                              container.push_back(individual);
1438 //                      }
1439 //              }
1440 //              //get last one
1441 //              container.push_back(estim);
1442         }
1443         catch(exception& e) {
1444                 errorOut(e, "MothurOut", "splitAtComma");
1445                 exit(1);
1446         }       
1447 }
1448 /***********************************************************************/
1449
1450 //This function splits up the various option parameters
1451 void MothurOut::splitAtComma(string& prefix, string& suffix){
1452         try {
1453                 prefix = suffix.substr(0,suffix.find_first_of(','));
1454                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
1455                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1456                         string space = " ";
1457                         while(suffix.at(0) == ' ')
1458                                 suffix = suffix.substr(1, suffix.length());
1459                 }
1460
1461         }
1462         catch(exception& e) {
1463                 errorOut(e, "MothurOut", "splitAtComma");
1464                 exit(1);
1465         }       
1466 }
1467 /***********************************************************************/
1468
1469 //This function separates the key value from the option value i.e. dist=96_...
1470 void MothurOut::splitAtEquals(string& key, string& value){              
1471         try {
1472                 if(value.find_first_of('=') != -1){
1473                         key = value.substr(0,value.find_first_of('='));
1474                         if ((value.find_first_of('=')+1) <= value.length()) {
1475                                 value = value.substr(value.find_first_of('=')+1, value.length());
1476                         }
1477                 }else{
1478                         key = value;
1479                         value = 1;
1480                 }
1481         }
1482         catch(exception& e) {
1483                 errorOut(e, "MothurOut", "splitAtEquals");
1484                 exit(1);
1485         }       
1486 }
1487
1488 /**************************************************************************************************/
1489
1490 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1491         try {
1492                 for (int i = 0; i < Groups.size(); i++) {
1493                         if (groupname == Groups[i]) { return true; }
1494                 }
1495                 return false;
1496         }
1497         catch(exception& e) {
1498                 errorOut(e, "MothurOut", "inUsersGroups");
1499                 exit(1);
1500         }       
1501 }
1502 /**************************************************************************************************/
1503 //returns true if any of the strings in first vector are in second vector
1504 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1505         try {
1506                 
1507                 for (int i = 0; i < groupnames.size(); i++) {
1508                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
1509                 }
1510                 return false;
1511         }
1512         catch(exception& e) {
1513                 errorOut(e, "MothurOut", "inUsersGroups");
1514                 exit(1);
1515         }       
1516 }
1517 /***********************************************************************/
1518 //this function determines if the user has given us labels that are smaller than the given label.
1519 //if so then it returns true so that the calling function can run the previous valid distance.
1520 //it's a "smart" distance function.  It also checks for invalid labels.
1521 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1522         try {
1523                 
1524                 set<string>::iterator it;
1525                 vector<float> orderFloat;
1526                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
1527                 map<string, float>::iterator it2;
1528                 float labelFloat;
1529                 bool smaller = false;
1530                 
1531                 //unique is the smallest line
1532                 if (label == "unique") {  return false;  }
1533                 else { 
1534                         if (convertTestFloat(label, labelFloat)) {
1535                                 convert(label, labelFloat); 
1536                         }else { //cant convert 
1537                                 return false;
1538                         }
1539                 }
1540                 
1541                 //go through users set and make them floats
1542                 for(it = userLabels.begin(); it != userLabels.end();) {
1543                         
1544                         float temp;
1545                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1546                                 convert(*it, temp);
1547                                 orderFloat.push_back(temp);
1548                                 userMap[*it] = temp;
1549                                 it++;
1550                         }else if (*it == "unique") { 
1551                                 orderFloat.push_back(-1.0);
1552                                 userMap["unique"] = -1.0;
1553                                 it++;
1554                         }else {
1555                                 if (errorOff == "") {  mothurOut(*it + " is not a valid label."); mothurOutEndLine();  }
1556                                 userLabels.erase(it++); 
1557                         }
1558                 }
1559                 
1560                 //sort order
1561                 sort(orderFloat.begin(), orderFloat.end());
1562                 
1563                 /*************************************************/
1564                 //is this label bigger than any of the users labels
1565                 /*************************************************/
1566                                 
1567                 //loop through order until you find a label greater than label
1568                 for (int i = 0; i < orderFloat.size(); i++) {
1569                         if (orderFloat[i] < labelFloat) {
1570                                 smaller = true;
1571                                 if (orderFloat[i] == -1) { 
1572                                         if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
1573                                         userLabels.erase("unique");
1574                                 }
1575                                 else {  
1576                                         if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
1577                                         string s = "";
1578                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
1579                                                 if (it2->second == orderFloat[i]) {  
1580                                                         s = it2->first;  
1581                                                         //remove small labels
1582                                                         userLabels.erase(s);
1583                                                         break;
1584                                                 }
1585                                         }
1586                                         if (errorOff == "") {mothurOut( s +  ". I will use the next smallest distance. "); mothurOutEndLine(); }
1587                                 }
1588                         //since they are sorted once you find a bigger one stop looking
1589                         }else { break; }
1590                 }
1591                 
1592                 return smaller;
1593                                                 
1594         }
1595         catch(exception& e) {
1596                 errorOut(e, "MothurOut", "anyLabelsToProcess");
1597                 exit(1);
1598         }       
1599 }
1600
1601 /**************************************************************************************************/
1602 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1603         try {
1604                 
1605                 bool good = true;
1606                 
1607                 string line = getline(file);  
1608
1609                 //before we added this check
1610                 if (line[0] != '#') {  good = false;  }
1611                 else {
1612                         //rip off #
1613                         line = line.substr(1);
1614                         
1615                         vector<string> versionVector;
1616                         splitAtChar(version, versionVector, '.');
1617                         
1618                         //check file version
1619                         vector<string> linesVector;
1620                         splitAtChar(line, linesVector, '.');
1621                         
1622                         if (versionVector.size() != linesVector.size()) { good = false; }
1623                         else {
1624                                 for (int j = 0; j < versionVector.size(); j++) {
1625                                         int num1, num2;
1626                                         convert(versionVector[j], num1);
1627                                         convert(linesVector[j], num2);
1628                                         
1629                                         //if mothurs version is newer than this files version, then we want to remake it
1630                                         if (num1 > num2) {  good = false; break;  }
1631                                 }
1632                         }
1633                         
1634                 }
1635                 
1636                 if (!good) {  file.close();  }
1637                 else { file.seekg(0);  }
1638                 
1639                 return good;
1640         }
1641         catch(exception& e) {
1642                 errorOut(e, "MothurOut", "checkReleaseVersion");                
1643                 exit(1);
1644         }
1645 }
1646
1647 /**************************************************************************************************/
1648
1649
1650
1651
1652