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