]> git.donarmstrong.com Git - mothur.git/blob - mothurout.cpp
changed reading of name file to use buffered reads. note the splitAtWhiteSpace functi...
[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             
1096             char buffer[4096];        
1097             while (!input.eof()) {
1098                 input.read(buffer, 4096);
1099                 output.write(buffer, input.gcount());
1100                 //count number of lines
1101                 for (int i = 0; i < input.gcount(); i++) {  if (buffer[i] == '\n') {numLines++;} }
1102             }
1103                         input.close();
1104                 }
1105                 
1106                 output.close();
1107                 
1108                 return numLines;
1109         }
1110         catch(exception& e) {
1111                 errorOut(e, "MothurOut", "appendFiles");
1112                 exit(1);
1113         }       
1114 }
1115
1116 /**************************************************************************************************/
1117 string MothurOut::sortFile(string distFile, string outputDir){
1118         try {   
1119         
1120                 //if (outputDir == "") {  outputDir += hasPath(distFile);  }
1121                 string outfile = getRootName(distFile) + "sorted.dist";
1122
1123                 
1124                 //if you can, use the unix sort since its been optimized for years
1125                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1126                         string command = "sort -n -k +3 " + distFile + " -o " + outfile;
1127                         system(command.c_str());
1128                 #else //you are stuck with my best attempt...
1129                         //windows sort does not have a way to specify a column, only a character in the line
1130                         //since we cannot assume that the distance will always be at the the same character location on each line
1131                         //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
1132                 
1133                         //read in file line by file and put distance first
1134                         string tempDistFile = distFile + ".temp";
1135                         ifstream input;
1136                         ofstream output;
1137                         openInputFile(distFile, input);
1138                         openOutputFile(tempDistFile, output);
1139
1140                         string firstName, secondName;
1141                         float dist;
1142                         while (input) {
1143                                 input >> firstName >> secondName >> dist;
1144                                 output << dist << '\t' << firstName << '\t' << secondName << endl;
1145                                 gobble(input);
1146                         }
1147                         input.close();
1148                         output.close();
1149                 
1150         
1151                         //sort using windows sort
1152                         string tempOutfile = outfile + ".temp";
1153                         string command = "sort " + tempDistFile + " /O " + tempOutfile;
1154                         system(command.c_str());
1155                 
1156                         //read in sorted file and put distance at end again
1157                         ifstream input2;
1158                         openInputFile(tempOutfile, input2);
1159                         openOutputFile(outfile, output);
1160                 
1161                         while (input2) {
1162                                 input2 >> dist >> firstName >> secondName;
1163                                 output << firstName << '\t' << secondName << '\t' << dist << endl;
1164                                 gobble(input2);
1165                         }
1166                         input2.close();
1167                         output.close();
1168                 
1169                         //remove temp files
1170                         mothurRemove(tempDistFile);
1171                         mothurRemove(tempOutfile);
1172                 #endif
1173                 
1174                 return outfile;
1175         }
1176         catch(exception& e) {
1177                 errorOut(e, "MothurOut", "sortFile");
1178                 exit(1);
1179         }       
1180 }
1181 /**************************************************************************************************/
1182 vector<unsigned long long> MothurOut::setFilePosFasta(string filename, int& num) {
1183         try {
1184                         vector<unsigned long long> positions;
1185                         ifstream inFASTA;
1186                         //openInputFile(filename, inFASTA);
1187                         inFASTA.open(filename.c_str(), ios::binary);
1188                                                 
1189                         string input;
1190                         unsigned long long count = 0;
1191                         while(!inFASTA.eof()){
1192                                 //input = getline(inFASTA); 
1193                                 //cout << input << '\t' << inFASTA.tellg() << endl;
1194                                 //if (input.length() != 0) {
1195                                 //      if(input[0] == '>'){    unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);  cout << (pos - input.length() - 1) << endl; }
1196                                 //}
1197                                 //gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
1198                                 char c = inFASTA.get(); count++;
1199                                 if (c == '>') {
1200                                         positions.push_back(count-1);
1201                                         //cout << count << endl;
1202                                 }
1203                         }
1204                         inFASTA.close();
1205                 
1206                         num = positions.size();
1207                 
1208                         /*FILE * pFile;
1209                         long size;
1210                 
1211                         //get num bytes in file
1212                         pFile = fopen (filename.c_str(),"rb");
1213                         if (pFile==NULL) perror ("Error opening file");
1214                         else{
1215                                 fseek (pFile, 0, SEEK_END);
1216                                 size=ftell (pFile);
1217                                 fclose (pFile);
1218                         }*/
1219                         
1220                         unsigned long long size = positions[(positions.size()-1)];
1221                         ifstream in;
1222                         openInputFile(filename, in);
1223                         
1224                         in.seekg(size);
1225                 
1226                         while(in.get()){
1227                                 if(in.eof())            {       break;  }
1228                                 else                            {       size++; }
1229                         }
1230                         in.close();
1231                 
1232                         positions.push_back(size);
1233                         positions[0] = 0;
1234                 
1235                         return positions;
1236         }
1237         catch(exception& e) {
1238                 errorOut(e, "MothurOut", "setFilePosFasta");
1239                 exit(1);
1240         }
1241 }
1242 /**************************************************************************************************/
1243 vector<unsigned long long> MothurOut::setFilePosEachLine(string filename, int& num) {
1244         try {
1245                         filename = getFullPathName(filename);
1246                         
1247                         vector<unsigned long long> positions;
1248                         ifstream in;
1249                         //openInputFile(filename, in);
1250                         in.open(filename.c_str(), ios::binary);
1251                 
1252                         string input;
1253                         unsigned long long count = 0;
1254                         positions.push_back(0);
1255                 
1256                         while(!in.eof()){
1257                                 //unsigned long long lastpos = in.tellg();
1258                                 //input = getline(in); 
1259                                 //if (input.length() != 0) {
1260                                         //unsigned long long pos = in.tellg(); 
1261                                         //if (pos != -1) { positions.push_back(pos - input.length() - 1);       }
1262                                         //else {  positions.push_back(lastpos);  }
1263                                 //}
1264                                 //gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
1265                                 
1266                                 
1267                                 //getline counting reads
1268                                 char d = in.get(); count++;
1269                                 while ((d != '\n') && (d != '\r') && (d != '\f') && (d != in.eof()))    {
1270                                         //get next character
1271                                         d = in.get(); 
1272                                         count++;
1273                                 }
1274                                 
1275                                 if (!in.eof()) {
1276                                         d=in.get(); count++;
1277                                         while(isspace(d) && (d != in.eof()))            { d=in.get(); count++;}
1278                                 }
1279                                 positions.push_back(count-1);
1280                                 //cout << count-1 << endl;
1281                         }
1282                         in.close();
1283                 
1284                         num = positions.size()-1;
1285                 
1286                         FILE * pFile;
1287                         unsigned long long size;
1288                         
1289                         //get num bytes in file
1290                         pFile = fopen (filename.c_str(),"rb");
1291                         if (pFile==NULL) perror ("Error opening file");
1292                         else{
1293                                 fseek (pFile, 0, SEEK_END);
1294                                 size=ftell (pFile);
1295                                 fclose (pFile);
1296                         }
1297                 
1298                         positions[(positions.size()-1)] = size;
1299                 
1300                         return positions;
1301         }
1302         catch(exception& e) {
1303                 errorOut(e, "MothurOut", "setFilePosEachLine");
1304                 exit(1);
1305         }
1306 }
1307 /**************************************************************************************************/
1308
1309 vector<unsigned long long> MothurOut::divideFile(string filename, int& proc) {
1310         try{
1311                 vector<unsigned long long> filePos;
1312                 filePos.push_back(0);
1313                 
1314                 FILE * pFile;
1315                 unsigned long long size;
1316                 
1317                 filename = getFullPathName(filename);
1318         
1319                 //get num bytes in file
1320                 pFile = fopen (filename.c_str(),"rb");
1321                 if (pFile==NULL) perror ("Error opening file");
1322                 else{
1323                         fseek (pFile, 0, SEEK_END);
1324                         size=ftell (pFile);
1325                         fclose (pFile);
1326                 }
1327                 
1328         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1329                                 
1330                 //estimate file breaks
1331                 unsigned long long chunkSize = 0;
1332                 chunkSize = size / proc;
1333
1334                 //file to small to divide by processors
1335                 if (chunkSize == 0)  {  proc = 1;       filePos.push_back(size); return filePos;        }
1336         
1337                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
1338                 for (int i = 0; i < proc; i++) {
1339                         unsigned long long spot = (i+1) * chunkSize;
1340                         
1341                         ifstream in;
1342                         openInputFile(filename, in);
1343                         in.seekg(spot);
1344                         
1345                         //look for next '>'
1346                         unsigned long long newSpot = spot;
1347                         while (!in.eof()) {
1348                            char c = in.get();
1349                                 
1350                            if (c == '>') {   in.putback(c); newSpot = in.tellg(); break;  }
1351                            else if (int(c) == -1) { break; }
1352                                 
1353                         }
1354                 
1355                         //there was not another sequence before the end of the file
1356                         unsigned long long sanityPos = in.tellg();
1357
1358                         if (sanityPos == -1) {  break;  }
1359                         else {  filePos.push_back(newSpot);  }
1360                         
1361                         in.close();
1362                 }
1363                 
1364                 //save end pos
1365                 filePos.push_back(size);
1366                 
1367                 //sanity check filePos
1368                 for (int i = 0; i < (filePos.size()-1); i++) {
1369                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
1370                 }
1371
1372                 proc = (filePos.size() - 1);
1373 #else
1374                 mothurOut("[ERROR]: Windows version should not be calling the divideFile function."); mothurOutEndLine();
1375                 proc=1;
1376                 filePos.push_back(size);
1377 #endif
1378                 return filePos;
1379         }
1380         catch(exception& e) {
1381                 errorOut(e, "MothurOut", "divideFile");
1382                 exit(1);
1383         }
1384 }
1385 /**************************************************************************************************/
1386 int MothurOut::divideFile(string filename, int& proc, vector<string>& files) {
1387         try{
1388                 
1389                 vector<unsigned long long> filePos = divideFile(filename, proc);
1390                 
1391                 for (int i = 0; i < (filePos.size()-1); i++) {
1392                         
1393                         //read file chunk
1394                         ifstream in;
1395                         openInputFile(filename, in);
1396                         in.seekg(filePos[i]);
1397                         unsigned long long size = filePos[(i+1)] - filePos[i];
1398                         char* chunk = new char[size];
1399                         in.read(chunk, size);
1400                         in.close();
1401                         
1402                         //open new file
1403                         string fileChunkName = filename + "." + toString(i) + ".tmp";
1404                         ofstream out; 
1405                         openOutputFile(fileChunkName, out);
1406                         
1407                         out << chunk << endl;
1408                         out.close();
1409                         delete[] chunk;
1410                         
1411                         //save name
1412                         files.push_back(fileChunkName);
1413                 }
1414                                 
1415                 return 0;
1416         }
1417         catch(exception& e) {
1418                 errorOut(e, "MothurOut", "divideFile");
1419                 exit(1);
1420         }
1421 }
1422 /***********************************************************************/
1423
1424 bool MothurOut::isTrue(string f){
1425         try {
1426                 
1427                 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
1428                 
1429                 if ((f == "TRUE") || (f == "T")) {      return true;    }
1430                 else {  return false;  }
1431         }
1432         catch(exception& e) {
1433                 errorOut(e, "MothurOut", "isTrue");
1434                 exit(1);
1435         }
1436 }
1437
1438 /***********************************************************************/
1439
1440 float MothurOut::roundDist(float dist, int precision){
1441         try {
1442                 return int(dist * precision + 0.5)/float(precision);
1443         }
1444         catch(exception& e) {
1445                 errorOut(e, "MothurOut", "roundDist");
1446                 exit(1);
1447         }
1448 }
1449 /***********************************************************************/
1450
1451 float MothurOut::ceilDist(float dist, int precision){
1452         try {
1453                 return int(ceil(dist * precision))/float(precision);
1454         }
1455         catch(exception& e) {
1456                 errorOut(e, "MothurOut", "ceilDist");
1457                 exit(1);
1458         }
1459 }
1460 /***********************************************************************/
1461
1462 vector<string> MothurOut::splitWhiteSpace(string& rest, char buffer[], int size){
1463         try {
1464         vector<string> pieces;
1465         
1466         for (int i = 0; i < size; i++) {
1467             if (!isspace(buffer[i]))  { rest += buffer[i];  }
1468             else {
1469                 pieces.push_back(rest);  rest = "";
1470                 while (i < size) {  //gobble white space
1471                     if (isspace(buffer[i])) { i++; }
1472                     else { rest = buffer[i];  break; } //cout << "next piece buffer = " << nextPiece << endl;
1473                 } 
1474             }
1475         }
1476         
1477         return pieces;
1478         }
1479         catch(exception& e) {
1480                 errorOut(e, "MothurOut", "parsePieces");
1481                 exit(1);
1482         }
1483 }
1484 /**********************************************************************************************************************/
1485 int MothurOut::readNames(string namefile, map<string, string>& nameMap) { 
1486         try {
1487                 
1488                 //open input file
1489                 ifstream in;
1490                 openInputFile(namefile, in);
1491
1492         string rest = "";
1493         char buffer[4096];
1494         bool pairDone = false;
1495         bool columnOne = true;
1496         string firstCol, secondCol;
1497         
1498                 while (!in.eof()) {
1499                         if (control_pressed) { break; }
1500                         
1501             in.read(buffer, 4096);
1502             vector<string> pieces = splitWhiteSpace(rest, buffer, in.gcount());
1503              
1504             for (int i = 0; i < pieces.size(); i++) {
1505                 if (columnOne) {  firstCol = pieces[i]; columnOne=false; }
1506                 else  { secondCol = pieces[i]; pairDone = true; columnOne=true; }
1507                 
1508                 if (pairDone) { nameMap[firstCol] = secondCol; pairDone = false; }
1509             }
1510                 }
1511                 in.close();
1512                 
1513                 return nameMap.size();
1514                 
1515         }
1516         catch(exception& e) {
1517                 errorOut(e, "MothurOut", "readNames");
1518                 exit(1);
1519         }
1520 }
1521 /**********************************************************************************************************************/
1522 int MothurOut::readNames(string namefile, map<string, vector<string> >& nameMap) { 
1523         try {
1524                 
1525                 //open input file
1526                 ifstream in;
1527                 openInputFile(namefile, in);
1528                 
1529         string rest = "";
1530         char buffer[4096];
1531         bool pairDone = false;
1532         bool columnOne = true;
1533         string firstCol, secondCol;
1534         
1535                 while (!in.eof()) {
1536                         if (control_pressed) { break; }
1537                         
1538             in.read(buffer, 4096);
1539             vector<string> pieces = splitWhiteSpace(rest, buffer, in.gcount());
1540             
1541             for (int i = 0; i < pieces.size(); i++) {
1542                 if (columnOne) {  firstCol = pieces[i]; columnOne=false; }
1543                 else  { secondCol = pieces[i]; pairDone = true; columnOne=true; }
1544                 
1545                 if (pairDone) { 
1546                     vector<string> temp;
1547                     splitAtComma(secondCol, temp);
1548                     nameMap[firstCol] = temp;
1549                     pairDone = false;  
1550                 } 
1551             }
1552                 }
1553                 in.close();
1554         
1555                 return nameMap.size();
1556         }
1557         catch(exception& e) {
1558                 errorOut(e, "MothurOut", "readNames");
1559                 exit(1);
1560         }
1561 }
1562 /**********************************************************************************************************************/
1563 map<string, int> MothurOut::readNames(string namefile) { 
1564         try {
1565                 
1566                 map<string, int> nameMap;
1567                 
1568                 //open input file
1569                 ifstream in;
1570                 openInputFile(namefile, in);
1571                 
1572         string rest = "";
1573         char buffer[4096];
1574         bool pairDone = false;
1575         bool columnOne = true;
1576         string firstCol, secondCol;
1577         
1578                 while (!in.eof()) {
1579                         if (control_pressed) { break; }
1580                         
1581             in.read(buffer, 4096);
1582             vector<string> pieces = splitWhiteSpace(rest, buffer, in.gcount());
1583             
1584             for (int i = 0; i < pieces.size(); i++) {
1585                 if (columnOne) {  firstCol = pieces[i]; columnOne=false; }
1586                 else  { secondCol = pieces[i]; pairDone = true; columnOne=true; }
1587                 
1588                 if (pairDone) { 
1589                     int num = getNumNames(secondCol);
1590                     nameMap[firstCol] = num;
1591                     pairDone = false;  
1592                 } 
1593             }
1594                 }
1595         in.close();
1596                 
1597                 return nameMap;
1598                 
1599         }
1600         catch(exception& e) {
1601                 errorOut(e, "MothurOut", "readNames");
1602                 exit(1);
1603         }
1604 }
1605 /**********************************************************************************************************************/
1606 int MothurOut::readNames(string namefile, vector<seqPriorityNode>& nameVector, map<string, string>& fastamap) { 
1607         try {
1608                 int error = 0;
1609                 
1610                 //open input file
1611                 ifstream in;
1612                 openInputFile(namefile, in);
1613                 
1614         string rest = "";
1615         char buffer[4096];
1616         bool pairDone = false;
1617         bool columnOne = true;
1618         string firstCol, secondCol;
1619         
1620                 while (!in.eof()) {
1621                         if (control_pressed) { break; }
1622                         
1623             in.read(buffer, 4096);
1624             vector<string> pieces = splitWhiteSpace(rest, buffer, in.gcount());
1625             
1626             for (int i = 0; i < pieces.size(); i++) {
1627                 if (columnOne) {  firstCol = pieces[i]; columnOne=false; }
1628                 else  { secondCol = pieces[i]; pairDone = true; columnOne=true; }
1629                 
1630                 if (pairDone) { 
1631                     int num = getNumNames(secondCol);
1632                     
1633                     map<string, string>::iterator it = fastamap.find(firstCol);
1634                     if (it == fastamap.end()) {
1635                         error = 1;
1636                         mothurOut("[ERROR]: " + firstCol + " is not in your fastafile, but is in your namesfile, please correct."); mothurOutEndLine();
1637                     }else {
1638                         seqPriorityNode temp(num, it->second, firstCol);
1639                         nameVector.push_back(temp);
1640                     }
1641                     
1642                     pairDone = false;  
1643                 } 
1644             }
1645                 }
1646         in.close();
1647         
1648                 return error;
1649         }
1650         catch(exception& e) {
1651                 errorOut(e, "MothurOut", "readNames");
1652                 exit(1);
1653         }
1654 }
1655
1656 /***********************************************************************/
1657
1658 int MothurOut::getNumNames(string names){
1659         try {
1660                 int count = 0;
1661                 
1662                 if(names != ""){
1663                         count = 1;
1664                         for(int i=0;i<names.size();i++){
1665                                 if(names[i] == ','){
1666                                         count++;
1667                                 }
1668                         }
1669                 }
1670                 
1671                 return count;
1672         }
1673         catch(exception& e) {
1674                 errorOut(e, "MothurOut", "getNumNames");
1675                 exit(1);
1676         }
1677 }
1678 /***********************************************************************/
1679
1680 int MothurOut::getNumChar(string line, char c){
1681         try {
1682                 int count = 0;
1683                 
1684                 if(line != ""){
1685                         for(int i=0;i<line.size();i++){
1686                                 if(line[i] == c){
1687                                         count++;
1688                                 }
1689                         }
1690                 }
1691                 
1692                 return count;
1693         }
1694         catch(exception& e) {
1695                 errorOut(e, "MothurOut", "getNumChar");
1696                 exit(1);
1697         }
1698 }
1699 /***********************************************************************/
1700 int MothurOut::mothurRemove(string filename){
1701         try {
1702                 filename = getFullPathName(filename);
1703                 int error = remove(filename.c_str());
1704                 //if (error != 0) { 
1705                 //      if (errno != ENOENT) { //ENOENT == file does not exist
1706                 //              string message = "Error deleting file " + filename;
1707                 //              perror(message.c_str()); 
1708                 //      }
1709                 //}
1710                 return error;
1711         }
1712         catch(exception& e) {
1713                 errorOut(e, "MothurOut", "mothurRemove");
1714                 exit(1);
1715         }
1716 }
1717 /***********************************************************************/
1718 bool MothurOut::mothurConvert(string item, int& num){
1719         try {
1720                 bool error = false;
1721                 
1722                 if (isNumeric1(item)) {
1723                         convert(item, num);
1724                 }else {
1725                         num = 0;
1726                         error = true;
1727                         mothurOut("[ERROR]: cannot convert " + item + " to an integer."); mothurOutEndLine();
1728                         commandInputsConvertError = true;
1729                 }
1730                 
1731                 return error;
1732         }
1733         catch(exception& e) {
1734                 errorOut(e, "MothurOut", "mothurConvert");
1735                 exit(1);
1736         }
1737 }
1738 /***********************************************************************/
1739 bool MothurOut::isNumeric1(string stringToCheck){
1740         try {
1741                 bool numeric = false;
1742                 
1743                 if(stringToCheck.find_first_not_of("0123456789.-") == string::npos) { numeric = true; }
1744                         
1745                 return numeric;
1746         }
1747         catch(exception& e) {
1748                 errorOut(e, "MothurOut", "isNumeric1");
1749                 exit(1);
1750         }
1751         
1752 }
1753 /***********************************************************************/
1754 bool MothurOut::mothurConvert(string item, float& num){
1755         try {
1756                 bool error = false;
1757                 
1758                 if (isNumeric1(item)) {
1759                         convert(item, num);
1760                 }else {
1761                         num = 0;
1762                         error = true;
1763                         mothurOut("[ERROR]: cannot convert " + item + " to a float."); mothurOutEndLine();
1764                         commandInputsConvertError = true;
1765                 }
1766                 
1767                 return error;
1768         }
1769         catch(exception& e) {
1770                 errorOut(e, "MothurOut", "mothurConvert");
1771                 exit(1);
1772         }
1773 }
1774 /***********************************************************************/
1775 bool MothurOut::mothurConvert(string item, double& num){
1776         try {
1777                 bool error = false;
1778                 
1779                 if (isNumeric1(item)) {
1780                         convert(item, num);
1781                 }else {
1782                         num = 0;
1783                         error = true;
1784                         mothurOut("[ERROR]: cannot convert " + item + " to a double."); mothurOutEndLine();
1785                         commandInputsConvertError = true;
1786                 }
1787                 
1788                 return error;
1789         }
1790         catch(exception& e) {
1791                 errorOut(e, "MothurOut", "mothurConvert");
1792                 exit(1);
1793         }
1794 }
1795 /**************************************************************************************************/
1796
1797 vector<vector<double> > MothurOut::binomial(int maxOrder){
1798         try {
1799         vector<vector<double> > binomial(maxOrder+1);
1800         
1801     for(int i=0;i<=maxOrder;i++){
1802                 binomial[i].resize(maxOrder+1);
1803                 binomial[i][0]=1;
1804                 binomial[0][i]=0;
1805     }
1806     binomial[0][0]=1;
1807         
1808     binomial[1][0]=1;
1809     binomial[1][1]=1;
1810         
1811     for(int i=2;i<=maxOrder;i++){
1812                 binomial[1][i]=0;
1813     }
1814         
1815     for(int i=2;i<=maxOrder;i++){
1816                 for(int j=1;j<=maxOrder;j++){
1817                         if(i==j){       binomial[i][j]=1;                                                                       }
1818                         if(j>i) {       binomial[i][j]=0;                                                                       }
1819                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
1820                 }
1821     }
1822         
1823         return binomial;
1824         
1825         }
1826         catch(exception& e) {
1827                 errorOut(e, "MothurOut", "binomial");
1828                 exit(1);
1829         }
1830 }
1831 /**************************************************************************************************/
1832 unsigned int MothurOut::fromBase36(string base36){
1833         try {
1834                 unsigned int num = 0;
1835                 
1836                 map<char, int> converts;
1837                 converts['A'] = 0;
1838                 converts['a'] = 0;
1839                 converts['B'] = 1;
1840                 converts['b'] = 1;
1841                 converts['C'] = 2;
1842                 converts['c'] = 2;
1843                 converts['D'] = 3;
1844                 converts['d'] = 3;
1845                 converts['E'] = 4;
1846                 converts['e'] = 4;
1847                 converts['F'] = 5;
1848                 converts['f'] = 5;
1849                 converts['G'] = 6;
1850                 converts['g'] = 6;
1851                 converts['H'] = 7;
1852                 converts['h'] = 7;
1853                 converts['I'] = 8;
1854                 converts['i'] = 8;
1855                 converts['J'] = 9;
1856                 converts['j'] = 9;
1857                 converts['K'] = 10;
1858                 converts['k'] = 10;
1859                 converts['L'] = 11;
1860                 converts['l'] = 11;
1861                 converts['M'] = 12;
1862                 converts['m'] = 12;
1863                 converts['N'] = 13;
1864                 converts['n'] = 13;
1865                 converts['O'] = 14;
1866                 converts['o'] = 14;
1867                 converts['P'] = 15;
1868                 converts['p'] = 15;
1869                 converts['Q'] = 16;
1870                 converts['q'] = 16;
1871                 converts['R'] = 17;
1872                 converts['r'] = 17;
1873                 converts['S'] = 18;
1874                 converts['s'] = 18;
1875                 converts['T'] = 19;
1876                 converts['t'] = 19;
1877                 converts['U'] = 20;
1878                 converts['u'] = 20;
1879                 converts['V'] = 21;
1880                 converts['v'] = 21;
1881                 converts['W'] = 22;
1882                 converts['w'] = 22;
1883                 converts['X'] = 23;
1884                 converts['x'] = 23;
1885                 converts['Y'] = 24;
1886                 converts['y'] = 24;
1887                 converts['Z'] = 25;
1888                 converts['z'] = 25;
1889                 converts['0'] = 26;
1890                 converts['1'] = 27;
1891                 converts['2'] = 28;
1892                 converts['3'] = 29;
1893                 converts['4'] = 30;
1894                 converts['5'] = 31;
1895                 converts['6'] = 32;
1896                 converts['7'] = 33;
1897                 converts['8'] = 34;
1898                 converts['9'] = 35;             
1899                 
1900                 int i = 0;
1901                 while (i < base36.length()) {
1902                         char c = base36[i];
1903                         num = 36 * num + converts[c];
1904                         i++;
1905                 }
1906                 
1907                 return num;
1908                 
1909         }
1910         catch(exception& e) {
1911                 errorOut(e, "MothurOut", "fromBase36");
1912                 exit(1);
1913         }
1914 }
1915 /***********************************************************************/
1916
1917 int MothurOut::factorial(int num){
1918         try {
1919                 int total = 1;
1920                 
1921                 for (int i = 1; i <= num; i++) {
1922                         total *= i;
1923                 }
1924                 
1925                 return total;
1926         }
1927         catch(exception& e) {
1928                 errorOut(e, "MothurOut", "factorial");
1929                 exit(1);
1930         }
1931 }
1932 /***********************************************************************/
1933
1934 int MothurOut::getNumSeqs(ifstream& file){
1935         try {
1936                 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1937                 file.seekg(0);
1938                 return numSeqs;
1939         }
1940         catch(exception& e) {
1941                 errorOut(e, "MothurOut", "getNumSeqs");
1942                 exit(1);
1943         }       
1944 }
1945 /***********************************************************************/
1946 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1947         try {
1948                 string input;
1949                 numSeqs = 0;
1950                 while(!file.eof()){
1951                         input = getline(file);
1952                         if (input.length() != 0) {
1953                                 if(input[0] == '>'){ numSeqs++; }
1954                         }
1955                 }
1956         }
1957         catch(exception& e) {
1958                 errorOut(e, "MothurOut", "getNumSeqs");
1959                 exit(1);
1960         }       
1961 }
1962 /***********************************************************************/
1963
1964 //This function parses the estimator options and puts them in a vector
1965 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1966         try {
1967                 string individual = "";
1968                 int estimLength = estim.size();
1969                 for(int i=0;i<estimLength;i++){
1970                         if(estim[i] == symbol){
1971                                 container.push_back(individual);
1972                                 individual = "";                                
1973                         }
1974                         else{
1975                                 individual += estim[i];
1976                         }
1977                 }
1978                 container.push_back(individual);
1979
1980         }
1981         catch(exception& e) {
1982                 errorOut(e, "MothurOut", "splitAtChar");
1983                 exit(1);
1984         }       
1985 }
1986
1987 /***********************************************************************/
1988
1989 //This function parses the estimator options and puts them in a vector
1990 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1991         try {
1992                 string individual = "";
1993                 int estimLength = estim.size();
1994                 for(int i=0;i<estimLength;i++){
1995                         if(estim[i] == '-'){
1996                                 container.push_back(individual);
1997                                 individual = "";                                
1998                         }
1999                         else{
2000                                 individual += estim[i];
2001                         }
2002                 }
2003                 container.push_back(individual);
2004
2005         
2006         /*      string individual;
2007                 
2008                 while (estim.find_first_of('-') != -1) {
2009                         individual = estim.substr(0,estim.find_first_of('-'));
2010                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
2011                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
2012                                 container.push_back(individual);
2013                         }
2014                 }
2015                 //get last one
2016                 container.push_back(estim); */
2017         }
2018         catch(exception& e) {
2019                 errorOut(e, "MothurOut", "splitAtDash");
2020                 exit(1);
2021         }       
2022 }
2023
2024 /***********************************************************************/
2025 //This function parses the label options and puts them in a set
2026 void MothurOut::splitAtDash(string& estim, set<string>& container) {
2027         try {
2028                 string individual = "";
2029                 int estimLength = estim.size();
2030                 for(int i=0;i<estimLength;i++){
2031                         if(estim[i] == '-'){
2032                                 container.insert(individual);
2033                                 individual = "";                                
2034                         }
2035                         else{
2036                                 individual += estim[i];
2037                         }
2038                 }
2039                 container.insert(individual);
2040
2041         //      string individual;
2042                 
2043         //      while (estim.find_first_of('-') != -1) {
2044         //              individual = estim.substr(0,estim.find_first_of('-'));
2045         //              if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
2046         //                      estim = estim.substr(estim.find_first_of('-')+1, estim.length());
2047         //                      container.insert(individual);
2048         //              }
2049         //      }
2050                 //get last one
2051         //      container.insert(estim);
2052         
2053         }
2054         catch(exception& e) {
2055                 errorOut(e, "MothurOut", "splitAtDash");
2056                 exit(1);
2057         }       
2058 }
2059 /***********************************************************************/
2060 //This function parses the line options and puts them in a set
2061 void MothurOut::splitAtDash(string& estim, set<int>& container) {
2062         try {
2063                 string individual;
2064                 int lineNum;
2065                 
2066                 while (estim.find_first_of('-') != -1) {
2067                         individual = estim.substr(0,estim.find_first_of('-'));
2068                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
2069                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
2070                                 convert(individual, lineNum); //convert the string to int
2071                                 container.insert(lineNum);
2072                         }
2073                 }
2074                 //get last one
2075                 convert(estim, lineNum); //convert the string to int
2076                 container.insert(lineNum);
2077         }
2078         catch(exception& e) {
2079                 errorOut(e, "MothurOut", "splitAtDash");
2080                 exit(1);
2081         }       
2082 }
2083 /***********************************************************************/
2084 string MothurOut::makeList(vector<string>& names) {
2085         try {
2086                 string list = "";
2087         
2088         if (names.size() == 0) { return list; }
2089                 
2090         for (int i = 0; i < names.size()-1; i++) { list += names[i] + ",";  }
2091         
2092         //get last name
2093         list += names[names.size()-1];
2094         
2095         return list;
2096     }
2097         catch(exception& e) {
2098                 errorOut(e, "MothurOut", "makeList");
2099                 exit(1);
2100         }       
2101 }
2102
2103 /***********************************************************************/
2104 //This function parses the a string and puts peices in a vector
2105 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
2106         try {
2107                 string individual = "";
2108                 int estimLength = estim.size();
2109                 for(int i=0;i<estimLength;i++){
2110                         if(estim[i] == ','){
2111                                 container.push_back(individual);
2112                                 individual = "";                                
2113                         }
2114                         else{
2115                                 individual += estim[i];
2116                         }
2117                 }
2118                 container.push_back(individual);
2119                 
2120                 
2121                 
2122                 
2123 //              string individual;
2124 //              
2125 //              while (estim.find_first_of(',') != -1) {
2126 //                      individual = estim.substr(0,estim.find_first_of(','));
2127 //                      if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
2128 //                              estim = estim.substr(estim.find_first_of(',')+1, estim.length());
2129 //                              container.push_back(individual);
2130 //                      }
2131 //              }
2132 //              //get last one
2133 //              container.push_back(estim);
2134         }
2135         catch(exception& e) {
2136                 errorOut(e, "MothurOut", "splitAtComma");
2137                 exit(1);
2138         }       
2139 }
2140 /***********************************************************************/
2141 //This function splits up the various option parameters
2142 void MothurOut::splitAtChar(string& prefix, string& suffix, char c){
2143         try {
2144                 prefix = suffix.substr(0,suffix.find_first_of(c));
2145                 if ((suffix.find_first_of(c)+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
2146                         suffix = suffix.substr(suffix.find_first_of(c)+1, suffix.length());
2147                         string space = " ";
2148                         while(suffix.at(0) == ' ')
2149                                 suffix = suffix.substr(1, suffix.length());
2150                 }
2151         
2152         }
2153         catch(exception& e) {
2154                 errorOut(e, "MothurOut", "splitAtComma");
2155                 exit(1);
2156         }       
2157 }
2158
2159 /***********************************************************************/
2160
2161 //This function splits up the various option parameters
2162 void MothurOut::splitAtComma(string& prefix, string& suffix){
2163         try {
2164                 prefix = suffix.substr(0,suffix.find_first_of(','));
2165                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
2166                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
2167                         string space = " ";
2168                         while(suffix.at(0) == ' ')
2169                                 suffix = suffix.substr(1, suffix.length());
2170                 }
2171
2172         }
2173         catch(exception& e) {
2174                 errorOut(e, "MothurOut", "splitAtComma");
2175                 exit(1);
2176         }       
2177 }
2178 /***********************************************************************/
2179
2180 //This function separates the key value from the option value i.e. dist=96_...
2181 void MothurOut::splitAtEquals(string& key, string& value){              
2182         try {
2183                 if(value.find_first_of('=') != -1){
2184                         key = value.substr(0,value.find_first_of('='));
2185                         if ((value.find_first_of('=')+1) <= value.length()) {
2186                                 value = value.substr(value.find_first_of('=')+1, value.length());
2187                         }
2188                 }else{
2189                         key = value;
2190                         value = 1;
2191                 }
2192         }
2193         catch(exception& e) {
2194                 errorOut(e, "MothurOut", "splitAtEquals");
2195                 exit(1);
2196         }       
2197 }
2198
2199 /**************************************************************************************************/
2200
2201 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
2202         try {
2203                 for (int i = 0; i < Groups.size(); i++) {
2204                         if (groupname == Groups[i]) { return true; }
2205                 }
2206                 return false;
2207         }
2208         catch(exception& e) {
2209                 errorOut(e, "MothurOut", "inUsersGroups");
2210                 exit(1);
2211         }       
2212 }
2213 /**************************************************************************************************/
2214 //returns true if any of the strings in first vector are in second vector
2215 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
2216         try {
2217                 
2218                 for (int i = 0; i < groupnames.size(); i++) {
2219                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
2220                 }
2221                 return false;
2222         }
2223         catch(exception& e) {
2224                 errorOut(e, "MothurOut", "inUsersGroups");
2225                 exit(1);
2226         }       
2227 }
2228 /***********************************************************************/
2229 //this function determines if the user has given us labels that are smaller than the given label.
2230 //if so then it returns true so that the calling function can run the previous valid distance.
2231 //it's a "smart" distance function.  It also checks for invalid labels.
2232 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
2233         try {
2234                 
2235                 set<string>::iterator it;
2236                 vector<float> orderFloat;
2237                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
2238                 map<string, float>::iterator it2;
2239                 float labelFloat;
2240                 bool smaller = false;
2241                 
2242                 //unique is the smallest line
2243                 if (label == "unique") {  return false;  }
2244                 else { 
2245                         if (convertTestFloat(label, labelFloat)) {
2246                                 convert(label, labelFloat); 
2247                         }else { //cant convert 
2248                                 return false;
2249                         }
2250                 }
2251                 
2252                 //go through users set and make them floats
2253                 for(it = userLabels.begin(); it != userLabels.end();) {
2254                         
2255                         float temp;
2256                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
2257                                 convert(*it, temp);
2258                                 orderFloat.push_back(temp);
2259                                 userMap[*it] = temp;
2260                                 it++;
2261                         }else if (*it == "unique") { 
2262                                 orderFloat.push_back(-1.0);
2263                                 userMap["unique"] = -1.0;
2264                                 it++;
2265                         }else {
2266                                 if (errorOff == "") {  mothurOut(*it + " is not a valid label."); mothurOutEndLine();  }
2267                                 userLabels.erase(it++); 
2268                         }
2269                 }
2270                 
2271                 //sort order
2272                 sort(orderFloat.begin(), orderFloat.end());
2273                 
2274                 /*************************************************/
2275                 //is this label bigger than any of the users labels
2276                 /*************************************************/
2277                                 
2278                 //loop through order until you find a label greater than label
2279                 for (int i = 0; i < orderFloat.size(); i++) {
2280                         if (orderFloat[i] < labelFloat) {
2281                                 smaller = true;
2282                                 if (orderFloat[i] == -1) { 
2283                                         if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
2284                                         userLabels.erase("unique");
2285                                 }
2286                                 else {  
2287                                         if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
2288                                         string s = "";
2289                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
2290                                                 if (it2->second == orderFloat[i]) {  
2291                                                         s = it2->first;  
2292                                                         //remove small labels
2293                                                         userLabels.erase(s);
2294                                                         break;
2295                                                 }
2296                                         }
2297                                         if (errorOff == "") {mothurOut( s +  ". I will use the next smallest distance. "); mothurOutEndLine(); }
2298                                 }
2299                         //since they are sorted once you find a bigger one stop looking
2300                         }else { break; }
2301                 }
2302                 
2303                 return smaller;
2304                                                 
2305         }
2306         catch(exception& e) {
2307                 errorOut(e, "MothurOut", "anyLabelsToProcess");
2308                 exit(1);
2309         }       
2310 }
2311
2312 /**************************************************************************************************/
2313 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
2314         try {
2315                 
2316                 bool good = true;
2317                 
2318                 string line = getline(file);  
2319
2320                 //before we added this check
2321                 if (line[0] != '#') {  good = false;  }
2322                 else {
2323                         //rip off #
2324                         line = line.substr(1);
2325                         
2326                         vector<string> versionVector;
2327                         splitAtChar(version, versionVector, '.');
2328                         
2329                         //check file version
2330                         vector<string> linesVector;
2331                         splitAtChar(line, linesVector, '.');
2332                         
2333                         if (versionVector.size() != linesVector.size()) { good = false; }
2334                         else {
2335                                 for (int j = 0; j < versionVector.size(); j++) {
2336                                         int num1, num2;
2337                                         convert(versionVector[j], num1);
2338                                         convert(linesVector[j], num2);
2339                                         
2340                                         //if mothurs version is newer than this files version, then we want to remake it
2341                                         if (num1 > num2) {  good = false; break;  }
2342                                 }
2343                         }
2344                         
2345                 }
2346                 
2347                 if (!good) {  file.close();  }
2348                 else { file.seekg(0);  }
2349                 
2350                 return good;
2351         }
2352         catch(exception& e) {
2353                 errorOut(e, "MothurOut", "checkReleaseVersion");                
2354                 exit(1);
2355         }
2356 }
2357 /**************************************************************************************************/
2358 bool MothurOut::isContainingOnlyDigits(string input) {
2359         try{
2360                 
2361                 //are you a digit in ascii code
2362                 for (int i = 0;i < input.length(); i++){
2363                         if( input[i]>47 && input[i]<58){}
2364                         else { return false; }
2365                 }
2366                 
2367                 return true;
2368         }
2369         catch(exception& e) {
2370                 errorOut(e, "MothurOut", "isContainingOnlyDigits");             
2371                 exit(1);
2372         }
2373 }
2374 /**************************************************************************************************/
2375 int MothurOut::removeConfidences(string& tax) {
2376         try {
2377                 
2378                 string taxon;
2379                 string newTax = "";
2380                 
2381                 while (tax.find_first_of(';') != -1) {
2382                         
2383                         if (control_pressed) { return 0; }
2384                         
2385                         //get taxon
2386                         taxon = tax.substr(0,tax.find_first_of(';'));
2387         
2388                         int pos = taxon.find_last_of('(');
2389                         if (pos != -1) {
2390                                 //is it a number?
2391                                 int pos2 = taxon.find_last_of(')');
2392                                 if (pos2 != -1) {
2393                                         string confidenceScore = taxon.substr(pos+1, (pos2-(pos+1)));
2394                                         if (isNumeric1(confidenceScore)) {
2395                                                 taxon = taxon.substr(0, pos); //rip off confidence 
2396                                         }
2397                                 }
2398                         }
2399                         taxon += ";";
2400                         
2401                         tax = tax.substr(tax.find_first_of(';')+1, tax.length());
2402                         newTax += taxon;
2403                 }
2404                 
2405                 tax = newTax;
2406                 
2407                 return 0;
2408         }
2409         catch(exception& e) {
2410                 errorOut(e, "MothurOut", "removeConfidences");
2411                 exit(1);
2412         }
2413 }
2414 /**************************************************************************************************/
2415
2416
2417
2418
2419