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