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