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