]> git.donarmstrong.com Git - mothur.git/blob - mothurout.cpp
fixed bug with trim.seqs allfiles=t
[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 int MothurOut::readNames(string namefile, map<string, string>& nameMap) { 
1234         try {
1235                 
1236                 //open input file
1237                 ifstream in;
1238                 openInputFile(namefile, in);
1239                 
1240                 while (!in.eof()) {
1241                         if (control_pressed) { break; }
1242                         
1243                         string firstCol, secondCol;
1244                         in >> firstCol >> secondCol; gobble(in);
1245                         
1246                         nameMap[firstCol] = secondCol;
1247                 }
1248                 in.close();
1249                 
1250                 return 0;
1251                 
1252         }
1253         catch(exception& e) {
1254                 errorOut(e, "MothurOut", "readNames");
1255                 exit(1);
1256         }
1257 }
1258
1259 /**********************************************************************************************************************/
1260 map<string, int> MothurOut::readNames(string namefile) { 
1261         try {
1262                 
1263                 map<string, int> nameMap;
1264                 
1265                 //open input file
1266                 ifstream in;
1267                 openInputFile(namefile, in);
1268                 
1269                 while (!in.eof()) {
1270                         if (control_pressed) { break; }
1271                         
1272                         string firstCol, secondCol;
1273                         in >> firstCol >> secondCol; gobble(in);
1274                         
1275                         int num = getNumNames(secondCol);
1276                         
1277                         nameMap[firstCol] = num;
1278                 }
1279                 in.close();
1280                 
1281                 return nameMap;
1282                 
1283         }
1284         catch(exception& e) {
1285                 errorOut(e, "MothurOut", "readNames");
1286                 exit(1);
1287         }
1288 }
1289 /**********************************************************************************************************************/
1290 int MothurOut::readNames(string namefile, vector<seqPriorityNode>& nameVector, map<string, string>& fastamap) { 
1291         try {
1292                 int error = 0;
1293                 
1294                 //open input file
1295                 ifstream in;
1296                 openInputFile(namefile, in);
1297                 
1298                 while (!in.eof()) {
1299                         if (control_pressed) { break; }
1300                         
1301                         string firstCol, secondCol;
1302                         in >> firstCol >> secondCol; gobble(in);
1303                         
1304                         int num = getNumNames(secondCol);
1305                         
1306                         map<string, string>::iterator it = fastamap.find(firstCol);
1307                         if (it == fastamap.end()) {
1308                                 error = 1;
1309                                 mothurOut("[ERROR]: " + firstCol + " is not in your fastafile, but is in your namesfile, please correct."); mothurOutEndLine();
1310                         }else {
1311                                 seqPriorityNode temp(num, it->second, firstCol);
1312                                 nameVector.push_back(temp);
1313                         }
1314                 }
1315                 in.close();
1316                 
1317                 return error;
1318                 
1319         }
1320         catch(exception& e) {
1321                 errorOut(e, "MothurOut", "readNames");
1322                 exit(1);
1323         }
1324 }
1325
1326 /***********************************************************************/
1327
1328 int MothurOut::getNumNames(string names){
1329         try {
1330                 int count = 0;
1331                 
1332                 if(names != ""){
1333                         count = 1;
1334                         for(int i=0;i<names.size();i++){
1335                                 if(names[i] == ','){
1336                                         count++;
1337                                 }
1338                         }
1339                 }
1340                 
1341                 return count;
1342         }
1343         catch(exception& e) {
1344                 errorOut(e, "MothurOut", "getNumNames");
1345                 exit(1);
1346         }
1347 }
1348
1349 /**************************************************************************************************/
1350
1351 vector<vector<double> > MothurOut::binomial(int maxOrder){
1352         try {
1353         vector<vector<double> > binomial(maxOrder+1);
1354         
1355     for(int i=0;i<=maxOrder;i++){
1356                 binomial[i].resize(maxOrder+1);
1357                 binomial[i][0]=1;
1358                 binomial[0][i]=0;
1359     }
1360     binomial[0][0]=1;
1361         
1362     binomial[1][0]=1;
1363     binomial[1][1]=1;
1364         
1365     for(int i=2;i<=maxOrder;i++){
1366                 binomial[1][i]=0;
1367     }
1368         
1369     for(int i=2;i<=maxOrder;i++){
1370                 for(int j=1;j<=maxOrder;j++){
1371                         if(i==j){       binomial[i][j]=1;                                                                       }
1372                         if(j>i) {       binomial[i][j]=0;                                                                       }
1373                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
1374                 }
1375     }
1376         
1377         return binomial;
1378         
1379         }
1380         catch(exception& e) {
1381                 errorOut(e, "MothurOut", "binomial");
1382                 exit(1);
1383         }
1384 }
1385 /**************************************************************************************************/
1386 unsigned int MothurOut::fromBase36(string base36){
1387         try {
1388                 unsigned int num = 0;
1389                 
1390                 map<char, int> converts;
1391                 converts['A'] = 0;
1392                 converts['a'] = 0;
1393                 converts['B'] = 1;
1394                 converts['b'] = 1;
1395                 converts['C'] = 2;
1396                 converts['c'] = 2;
1397                 converts['D'] = 3;
1398                 converts['d'] = 3;
1399                 converts['E'] = 4;
1400                 converts['e'] = 4;
1401                 converts['F'] = 5;
1402                 converts['f'] = 5;
1403                 converts['G'] = 6;
1404                 converts['g'] = 6;
1405                 converts['H'] = 7;
1406                 converts['h'] = 7;
1407                 converts['I'] = 8;
1408                 converts['i'] = 8;
1409                 converts['J'] = 9;
1410                 converts['j'] = 9;
1411                 converts['K'] = 10;
1412                 converts['k'] = 10;
1413                 converts['L'] = 11;
1414                 converts['l'] = 11;
1415                 converts['M'] = 12;
1416                 converts['m'] = 12;
1417                 converts['N'] = 13;
1418                 converts['n'] = 13;
1419                 converts['O'] = 14;
1420                 converts['o'] = 14;
1421                 converts['P'] = 15;
1422                 converts['p'] = 15;
1423                 converts['Q'] = 16;
1424                 converts['q'] = 16;
1425                 converts['R'] = 17;
1426                 converts['r'] = 17;
1427                 converts['S'] = 18;
1428                 converts['s'] = 18;
1429                 converts['T'] = 19;
1430                 converts['t'] = 19;
1431                 converts['U'] = 20;
1432                 converts['u'] = 20;
1433                 converts['V'] = 21;
1434                 converts['v'] = 21;
1435                 converts['W'] = 22;
1436                 converts['w'] = 22;
1437                 converts['X'] = 23;
1438                 converts['x'] = 23;
1439                 converts['Y'] = 24;
1440                 converts['y'] = 24;
1441                 converts['Z'] = 25;
1442                 converts['z'] = 25;
1443                 converts['0'] = 26;
1444                 converts['1'] = 27;
1445                 converts['2'] = 28;
1446                 converts['3'] = 29;
1447                 converts['4'] = 30;
1448                 converts['5'] = 31;
1449                 converts['6'] = 32;
1450                 converts['7'] = 33;
1451                 converts['8'] = 34;
1452                 converts['9'] = 35;             
1453                 
1454                 int i = 0;
1455                 while (i < base36.length()) {
1456                         char c = base36[i];
1457                         num = 36 * num + converts[c];
1458                         i++;
1459                 }
1460                 
1461                 return num;
1462                 
1463         }
1464         catch(exception& e) {
1465                 errorOut(e, "MothurOut", "fromBase36");
1466                 exit(1);
1467         }
1468 }
1469 /***********************************************************************/
1470
1471 int MothurOut::factorial(int num){
1472         try {
1473                 int total = 1;
1474                 
1475                 for (int i = 1; i <= num; i++) {
1476                         total *= i;
1477                 }
1478                 
1479                 return total;
1480         }
1481         catch(exception& e) {
1482                 errorOut(e, "MothurOut", "factorial");
1483                 exit(1);
1484         }
1485 }
1486 /***********************************************************************/
1487
1488 int MothurOut::getNumSeqs(ifstream& file){
1489         try {
1490                 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1491                 file.seekg(0);
1492                 return numSeqs;
1493         }
1494         catch(exception& e) {
1495                 errorOut(e, "MothurOut", "getNumSeqs");
1496                 exit(1);
1497         }       
1498 }
1499 /***********************************************************************/
1500 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1501         try {
1502                 string input;
1503                 numSeqs = 0;
1504                 while(!file.eof()){
1505                         input = getline(file);
1506                         if (input.length() != 0) {
1507                                 if(input[0] == '>'){ numSeqs++; }
1508                         }
1509                 }
1510         }
1511         catch(exception& e) {
1512                 errorOut(e, "MothurOut", "getNumSeqs");
1513                 exit(1);
1514         }       
1515 }
1516 /***********************************************************************/
1517
1518 //This function parses the estimator options and puts them in a vector
1519 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1520         try {
1521                 string individual = "";
1522                 int estimLength = estim.size();
1523                 for(int i=0;i<estimLength;i++){
1524                         if(estim[i] == symbol){
1525                                 container.push_back(individual);
1526                                 individual = "";                                
1527                         }
1528                         else{
1529                                 individual += estim[i];
1530                         }
1531                 }
1532                 container.push_back(individual);
1533
1534         }
1535         catch(exception& e) {
1536                 errorOut(e, "MothurOut", "splitAtChar");
1537                 exit(1);
1538         }       
1539 }
1540
1541 /***********************************************************************/
1542
1543 //This function parses the estimator options and puts them in a vector
1544 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1545         try {
1546                 string individual = "";
1547                 int estimLength = estim.size();
1548                 for(int i=0;i<estimLength;i++){
1549                         if(estim[i] == '-'){
1550                                 container.push_back(individual);
1551                                 individual = "";                                
1552                         }
1553                         else{
1554                                 individual += estim[i];
1555                         }
1556                 }
1557                 container.push_back(individual);
1558
1559         
1560         /*      string individual;
1561                 
1562                 while (estim.find_first_of('-') != -1) {
1563                         individual = estim.substr(0,estim.find_first_of('-'));
1564                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1565                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1566                                 container.push_back(individual);
1567                         }
1568                 }
1569                 //get last one
1570                 container.push_back(estim); */
1571         }
1572         catch(exception& e) {
1573                 errorOut(e, "MothurOut", "splitAtDash");
1574                 exit(1);
1575         }       
1576 }
1577
1578 /***********************************************************************/
1579 //This function parses the label options and puts them in a set
1580 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1581         try {
1582                 string individual = "";
1583                 int estimLength = estim.size();
1584                 for(int i=0;i<estimLength;i++){
1585                         if(estim[i] == '-'){
1586                                 container.insert(individual);
1587                                 individual = "";                                
1588                         }
1589                         else{
1590                                 individual += estim[i];
1591                         }
1592                 }
1593                 container.insert(individual);
1594
1595         //      string individual;
1596                 
1597         //      while (estim.find_first_of('-') != -1) {
1598         //              individual = estim.substr(0,estim.find_first_of('-'));
1599         //              if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1600         //                      estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1601         //                      container.insert(individual);
1602         //              }
1603         //      }
1604                 //get last one
1605         //      container.insert(estim);
1606         
1607         }
1608         catch(exception& e) {
1609                 errorOut(e, "MothurOut", "splitAtDash");
1610                 exit(1);
1611         }       
1612 }
1613 /***********************************************************************/
1614 //This function parses the line options and puts them in a set
1615 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1616         try {
1617                 string individual;
1618                 int lineNum;
1619                 
1620                 while (estim.find_first_of('-') != -1) {
1621                         individual = estim.substr(0,estim.find_first_of('-'));
1622                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1623                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1624                                 convert(individual, lineNum); //convert the string to int
1625                                 container.insert(lineNum);
1626                         }
1627                 }
1628                 //get last one
1629                 convert(estim, lineNum); //convert the string to int
1630                 container.insert(lineNum);
1631         }
1632         catch(exception& e) {
1633                 errorOut(e, "MothurOut", "splitAtDash");
1634                 exit(1);
1635         }       
1636 }
1637 /***********************************************************************/
1638 //This function parses the a string and puts peices in a vector
1639 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1640         try {
1641                 string individual = "";
1642                 int estimLength = estim.size();
1643                 for(int i=0;i<estimLength;i++){
1644                         if(estim[i] == ','){
1645                                 container.push_back(individual);
1646                                 individual = "";                                
1647                         }
1648                         else{
1649                                 individual += estim[i];
1650                         }
1651                 }
1652                 container.push_back(individual);
1653                 
1654                 
1655                 
1656                 
1657 //              string individual;
1658 //              
1659 //              while (estim.find_first_of(',') != -1) {
1660 //                      individual = estim.substr(0,estim.find_first_of(','));
1661 //                      if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1662 //                              estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1663 //                              container.push_back(individual);
1664 //                      }
1665 //              }
1666 //              //get last one
1667 //              container.push_back(estim);
1668         }
1669         catch(exception& e) {
1670                 errorOut(e, "MothurOut", "splitAtComma");
1671                 exit(1);
1672         }       
1673 }
1674 /***********************************************************************/
1675
1676 //This function splits up the various option parameters
1677 void MothurOut::splitAtComma(string& prefix, string& suffix){
1678         try {
1679                 prefix = suffix.substr(0,suffix.find_first_of(','));
1680                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
1681                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1682                         string space = " ";
1683                         while(suffix.at(0) == ' ')
1684                                 suffix = suffix.substr(1, suffix.length());
1685                 }
1686
1687         }
1688         catch(exception& e) {
1689                 errorOut(e, "MothurOut", "splitAtComma");
1690                 exit(1);
1691         }       
1692 }
1693 /***********************************************************************/
1694
1695 //This function separates the key value from the option value i.e. dist=96_...
1696 void MothurOut::splitAtEquals(string& key, string& value){              
1697         try {
1698                 if(value.find_first_of('=') != -1){
1699                         key = value.substr(0,value.find_first_of('='));
1700                         if ((value.find_first_of('=')+1) <= value.length()) {
1701                                 value = value.substr(value.find_first_of('=')+1, value.length());
1702                         }
1703                 }else{
1704                         key = value;
1705                         value = 1;
1706                 }
1707         }
1708         catch(exception& e) {
1709                 errorOut(e, "MothurOut", "splitAtEquals");
1710                 exit(1);
1711         }       
1712 }
1713
1714 /**************************************************************************************************/
1715
1716 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1717         try {
1718                 for (int i = 0; i < Groups.size(); i++) {
1719                         if (groupname == Groups[i]) { return true; }
1720                 }
1721                 return false;
1722         }
1723         catch(exception& e) {
1724                 errorOut(e, "MothurOut", "inUsersGroups");
1725                 exit(1);
1726         }       
1727 }
1728 /**************************************************************************************************/
1729 //returns true if any of the strings in first vector are in second vector
1730 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1731         try {
1732                 
1733                 for (int i = 0; i < groupnames.size(); i++) {
1734                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
1735                 }
1736                 return false;
1737         }
1738         catch(exception& e) {
1739                 errorOut(e, "MothurOut", "inUsersGroups");
1740                 exit(1);
1741         }       
1742 }
1743 /***********************************************************************/
1744 //this function determines if the user has given us labels that are smaller than the given label.
1745 //if so then it returns true so that the calling function can run the previous valid distance.
1746 //it's a "smart" distance function.  It also checks for invalid labels.
1747 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1748         try {
1749                 
1750                 set<string>::iterator it;
1751                 vector<float> orderFloat;
1752                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
1753                 map<string, float>::iterator it2;
1754                 float labelFloat;
1755                 bool smaller = false;
1756                 
1757                 //unique is the smallest line
1758                 if (label == "unique") {  return false;  }
1759                 else { 
1760                         if (convertTestFloat(label, labelFloat)) {
1761                                 convert(label, labelFloat); 
1762                         }else { //cant convert 
1763                                 return false;
1764                         }
1765                 }
1766                 
1767                 //go through users set and make them floats
1768                 for(it = userLabels.begin(); it != userLabels.end();) {
1769                         
1770                         float temp;
1771                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1772                                 convert(*it, temp);
1773                                 orderFloat.push_back(temp);
1774                                 userMap[*it] = temp;
1775                                 it++;
1776                         }else if (*it == "unique") { 
1777                                 orderFloat.push_back(-1.0);
1778                                 userMap["unique"] = -1.0;
1779                                 it++;
1780                         }else {
1781                                 if (errorOff == "") {  mothurOut(*it + " is not a valid label."); mothurOutEndLine();  }
1782                                 userLabels.erase(it++); 
1783                         }
1784                 }
1785                 
1786                 //sort order
1787                 sort(orderFloat.begin(), orderFloat.end());
1788                 
1789                 /*************************************************/
1790                 //is this label bigger than any of the users labels
1791                 /*************************************************/
1792                                 
1793                 //loop through order until you find a label greater than label
1794                 for (int i = 0; i < orderFloat.size(); i++) {
1795                         if (orderFloat[i] < labelFloat) {
1796                                 smaller = true;
1797                                 if (orderFloat[i] == -1) { 
1798                                         if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
1799                                         userLabels.erase("unique");
1800                                 }
1801                                 else {  
1802                                         if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
1803                                         string s = "";
1804                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
1805                                                 if (it2->second == orderFloat[i]) {  
1806                                                         s = it2->first;  
1807                                                         //remove small labels
1808                                                         userLabels.erase(s);
1809                                                         break;
1810                                                 }
1811                                         }
1812                                         if (errorOff == "") {mothurOut( s +  ". I will use the next smallest distance. "); mothurOutEndLine(); }
1813                                 }
1814                         //since they are sorted once you find a bigger one stop looking
1815                         }else { break; }
1816                 }
1817                 
1818                 return smaller;
1819                                                 
1820         }
1821         catch(exception& e) {
1822                 errorOut(e, "MothurOut", "anyLabelsToProcess");
1823                 exit(1);
1824         }       
1825 }
1826
1827 /**************************************************************************************************/
1828 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1829         try {
1830                 
1831                 bool good = true;
1832                 
1833                 string line = getline(file);  
1834
1835                 //before we added this check
1836                 if (line[0] != '#') {  good = false;  }
1837                 else {
1838                         //rip off #
1839                         line = line.substr(1);
1840                         
1841                         vector<string> versionVector;
1842                         splitAtChar(version, versionVector, '.');
1843                         
1844                         //check file version
1845                         vector<string> linesVector;
1846                         splitAtChar(line, linesVector, '.');
1847                         
1848                         if (versionVector.size() != linesVector.size()) { good = false; }
1849                         else {
1850                                 for (int j = 0; j < versionVector.size(); j++) {
1851                                         int num1, num2;
1852                                         convert(versionVector[j], num1);
1853                                         convert(linesVector[j], num2);
1854                                         
1855                                         //if mothurs version is newer than this files version, then we want to remake it
1856                                         if (num1 > num2) {  good = false; break;  }
1857                                 }
1858                         }
1859                         
1860                 }
1861                 
1862                 if (!good) {  file.close();  }
1863                 else { file.seekg(0);  }
1864                 
1865                 return good;
1866         }
1867         catch(exception& e) {
1868                 errorOut(e, "MothurOut", "checkReleaseVersion");                
1869                 exit(1);
1870         }
1871 }
1872 /**************************************************************************************************/
1873 bool MothurOut::isContainingOnlyDigits(string input) {
1874         try{
1875                 
1876                 //are you a digit in ascii code
1877                 for (int i = 0;i < input.length(); i++){
1878                         if( input[i]>47 && input[i]<58){}
1879                         else { return false; }
1880                 }
1881                 
1882                 return true;
1883         }
1884         catch(exception& e) {
1885                 errorOut(e, "MothurOut", "isContainingOnlyDigits");             
1886                 exit(1);
1887         }
1888 }
1889 /**************************************************************************************************/
1890
1891
1892
1893
1894