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