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