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