]> git.donarmstrong.com Git - mothur.git/blob - mothurout.cpp
fixed phylo.diversity
[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 MothurOut* MothurOut::getInstance() {
14         if( _uniqueInstance == 0) {
15                 _uniqueInstance = new MothurOut();
16         }
17         return _uniqueInstance;
18 }
19 /*********************************************************************************************/
20 void MothurOut::setFileName(string filename)  {
21         try {
22                 logFileName = filename;
23                 
24                 #ifdef USE_MPI
25                         int pid;
26                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
27                                         
28                         if (pid == 0) { //only one process should output to screen
29                 #endif
30                 
31                 openOutputFile(filename, out);
32                 
33                 #ifdef USE_MPI
34                         }
35                 #endif
36         }
37         catch(exception& e) {
38                 errorOut(e, "MothurOut", "setFileName");
39                 exit(1);
40         }
41 }
42 /*********************************************************************************************/
43 void MothurOut::setDefaultPath(string pathname)  {
44         try {
45         
46                 //add / to name if needed
47                 string lastChar = pathname.substr(pathname.length()-1);
48                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
49                         if (lastChar != "/") { pathname += "/"; }
50                 #else
51                         if (lastChar != "\\") { pathname += "\\"; }     
52                 #endif
53                 
54                 defaultPath = pathname;
55                 
56         }
57         catch(exception& e) {
58                 errorOut(e, "MothurOut", "setDefaultPath");
59                 exit(1);
60         }
61 }
62 /*********************************************************************************************/
63 void MothurOut::closeLog()  {
64         try {
65                 
66                 #ifdef USE_MPI
67                         int pid;
68                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
69                                         
70                         if (pid == 0) { //only one process should output to screen
71                 #endif
72                 
73                 out.close();
74                 
75                 #ifdef USE_MPI
76                         }
77                 #endif
78         }
79         catch(exception& e) {
80                 errorOut(e, "MothurOut", "closeLog");
81                 exit(1);
82         }
83 }
84
85 /*********************************************************************************************/
86 MothurOut::~MothurOut() {
87         try {
88                 _uniqueInstance = 0;
89                 
90         }
91         catch(exception& e) {
92                 errorOut(e, "MothurOut", "MothurOut");
93                 exit(1);
94         }
95 }
96 /*********************************************************************************************/
97 void MothurOut::mothurOut(string output) {
98         try {
99                 
100                 #ifdef USE_MPI
101                         int pid;
102                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
103                                         
104                         if (pid == 0) { //only one process should output to screen
105                 #endif
106                 
107                 cout << output;
108                 out << output;
109                 
110                 #ifdef USE_MPI
111                         }
112                 #endif
113         }
114         catch(exception& e) {
115                 errorOut(e, "MothurOut", "MothurOut");
116                 exit(1);
117         }
118 }
119 /*********************************************************************************************/
120 void MothurOut::mothurOutEndLine() {
121         try {
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                 cout << endl;
130                 out << endl;
131                 
132                 #ifdef USE_MPI
133                         }
134                 #endif
135         }
136         catch(exception& e) {
137                 errorOut(e, "MothurOut", "MothurOutEndLine");
138                 exit(1);
139         }
140 }
141 /*********************************************************************************************/
142 void MothurOut::mothurOutJustToLog(string output) {
143         try {
144                 #ifdef USE_MPI
145                         int pid;
146                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
147                                         
148                         if (pid == 0) { //only one process should output to screen
149                 #endif
150                 
151                 out << output;
152                 
153                 #ifdef USE_MPI
154                         }
155                 #endif
156         }
157         catch(exception& e) {
158                 errorOut(e, "MothurOut", "MothurOutJustToLog");
159                 exit(1);
160         }
161 }
162 /*********************************************************************************************/
163 void MothurOut::errorOut(exception& e, string object, string function) {
164         //double vm, rss;
165         //mem_usage(vm, rss);
166         
167         mothurOut("[ERROR]: ");
168         mothurOut(toString(e.what()));
169         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.");
170         mothurOutEndLine();
171 }
172 /*********************************************************************************************/
173 //The following was originally from http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c 
174 // process_mem_usage(double &, double &) - takes two doubles by reference,
175 // attempts to read the system-dependent data for a process' virtual memory
176 // size and resident set size, and return the results in KB.
177 //
178 // On failure, returns 0.0, 0.0
179 int MothurOut::mem_usage(double& vm_usage, double& resident_set) {
180   #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
181   
182            vm_usage     = 0.0;
183            resident_set = 0.0;
184
185            // 'file' stat seems to give the most reliable results
186            //
187            ifstream stat_stream("/proc/self/stat",ios_base::in);
188
189            // dummy vars for leading entries in stat that we don't care about
190            //
191            string pid, comm, state, ppid, pgrp, session, tty_nr;
192            string tpgid, flags, minflt, cminflt, majflt, cmajflt;
193            string utime, stime, cutime, cstime, priority, nice;
194            string O, itrealvalue, starttime;
195
196            // the two fields we want
197            //
198            unsigned long vsize;
199            long rss;
200
201            stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
202                                    >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
203                                    >> utime >> stime >> cutime >> cstime >> priority >> nice
204                                    >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
205
206            long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
207            vm_usage     = vsize / 1024.0;
208            resident_set = rss * page_size_kb;
209            
210            mothurOut("Memory Usage: vm = " + toString(vm_usage) + " rss = " + toString(resident_set) + "\n");
211                 return 0;
212
213         #else
214 /*              //windows memory usage
215                 // Get the list of process identifiers.
216                 DWORD aProcesses[1024], cbNeeded, cProcesses;
217                 
218                 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){ return 1; }
219
220                 // Calculate how many process identifiers were returned.
221                 cProcesses = cbNeeded / sizeof(DWORD);
222
223                 // Print the memory usage for each process
224                 for (int i = 0; i < cProcesses; i++ ) {
225                         DWORD processID = aProcesses[i];
226                         
227                         PROCESS_MEMORY_COUNTERS pmc;
228
229                         HANDLE hProcess = OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), FALSE, processID);
230
231                         // Print the process identifier.
232                         printf( "\nProcess ID: %u\n", processID);
233                         
234                         if (NULL != hProcess) {
235
236                                 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) {
237                                         printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
238                                         printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );
239                                         printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
240                                         printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );
241                                         printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );
242                                         printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );
243                                         printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );
244                                         printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage ); 
245                                         printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );
246                                 }
247                                 CloseHandle(hProcess);
248                         }
249                 }
250 */
251                         return 0;
252
253         #endif
254 }
255
256
257 /***********************************************************************/
258 int MothurOut::openOutputFileAppend(string fileName, ofstream& fileHandle){
259         try {
260                 fileName = getFullPathName(fileName);
261                 
262                 fileHandle.open(fileName.c_str(), ios::app);
263                 if(!fileHandle) {
264                         mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
265                         return 1;
266                 }
267                 else {
268                         return 0;
269                 }
270         }
271         catch(exception& e) {
272                 errorOut(e, "MothurOut", "openOutputFileAppend");
273                 exit(1);
274         }
275 }
276 /***********************************************************************/
277 void MothurOut::gobble(istream& f){
278         try {
279                 char d;
280                 while(isspace(d=f.get()))               {;}
281                 f.putback(d);
282         }
283         catch(exception& e) {
284                 errorOut(e, "MothurOut", "gobble");
285                 exit(1);
286         }
287 }
288 /***********************************************************************/
289 void MothurOut::gobble(istringstream& f){
290         try {
291                 char d;
292                 while(isspace(d=f.get()))               {;}
293                 f.putback(d);
294         }
295         catch(exception& e) {
296                 errorOut(e, "MothurOut", "gobble");
297                 exit(1);
298         }
299 }
300
301 /***********************************************************************/
302
303 string MothurOut::getline(istringstream& fileHandle) {
304         try {
305         
306                 string line = "";
307                 
308                 while (!fileHandle.eof())       {
309                         //get next character
310                         char c = fileHandle.get(); 
311                         
312                         //are you at the end of the line
313                         if ((c == '\n') || (c == '\r') || (c == '\f')){  break; }       
314                         else {          line += c;              }
315                 }
316                 
317                 return line;
318                 
319         }
320         catch(exception& e) {
321                 errorOut(e, "MothurOut", "getline");
322                 exit(1);
323         }
324 }
325 /***********************************************************************/
326
327 string MothurOut::getline(ifstream& fileHandle) {
328         try {
329         
330                 string line = "";
331                 
332                 while (!fileHandle.eof())       {
333                         //get next character
334                         char c = fileHandle.get(); 
335                         
336                         //are you at the end of the line
337                         if ((c == '\n') || (c == '\r') || (c == '\f')){  break; }       
338                         else {          line += c;              }
339                 }
340                 
341                 return line;
342                 
343         }
344         catch(exception& e) {
345                 errorOut(e, "MothurOut", "getline");
346                 exit(1);
347         }
348 }
349 /***********************************************************************/
350
351 string MothurOut::getRootName(string longName){
352         try {
353         
354                 string rootName = longName;
355                 
356                 if(longName.find_last_of(".") != longName.npos){
357                         int pos = longName.find_last_of('.')+1;
358                         rootName = longName.substr(0, pos);
359                 }
360
361                 return rootName;
362         }
363         catch(exception& e) {
364                 errorOut(e, "MothurOut", "getRootName");
365                 exit(1);
366         }
367 }
368 /***********************************************************************/
369
370 string MothurOut::getSimpleName(string longName){
371         try {
372                 string simpleName = longName;
373                 
374                 size_t found;
375                 found=longName.find_last_of("/\\");
376
377                 if(found != longName.npos){
378                         simpleName = longName.substr(found+1);
379                 }
380                 
381                 return simpleName;
382         }
383         catch(exception& e) {
384                 errorOut(e, "MothurOut", "getSimpleName");
385                 exit(1);
386         }
387 }
388
389 /***********************************************************************/
390
391 string MothurOut::getPathName(string longName){
392         try {
393                 string rootPathName = longName;
394                 
395                 if(longName.find_last_of("/\\") != longName.npos){
396                         int pos = longName.find_last_of("/\\")+1;
397                         rootPathName = longName.substr(0, pos);
398                 }
399                 
400                 return rootPathName;
401         }
402         catch(exception& e) {
403                 errorOut(e, "MothurOut", "getPathName");
404                 exit(1);
405         }       
406
407 }
408 /***********************************************************************/
409
410 string MothurOut::hasPath(string longName){
411         try {
412                 string path = "";
413                 
414                 size_t found;
415                 found=longName.find_last_of("~/\\");
416
417                 if(found != longName.npos){
418                         path = longName.substr(0, found+1);
419                 }
420                 
421                 return path;
422         }
423         catch(exception& e) {
424                 errorOut(e, "MothurOut", "hasPath");
425                 exit(1);
426         }       
427 }
428
429 /***********************************************************************/
430
431 string MothurOut::getExtension(string longName){
432         try {
433                 string extension = longName;
434                 
435                 if(longName.find_last_of('.') != longName.npos){
436                         int pos = longName.find_last_of('.');
437                         extension = longName.substr(pos, longName.length());
438                 }
439                 
440                 return extension;
441         }
442         catch(exception& e) {
443                 errorOut(e, "MothurOut", "getExtension");
444                 exit(1);
445         }       
446 }
447 /***********************************************************************/
448 bool MothurOut::isBlank(string fileName){
449         try {
450                 
451                 fileName = getFullPathName(fileName);
452                 
453                 ifstream fileHandle;
454                 fileHandle.open(fileName.c_str());
455                 if(!fileHandle) {
456                         mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
457                         return false;
458                 }else {
459                         //check for blank file
460                         gobble(fileHandle);
461                         if (fileHandle.eof()) { fileHandle.close(); return true;  }
462                 }
463                 return false;
464         }
465         catch(exception& e) {
466                 errorOut(e, "MothurOut", "isBlank");
467                 exit(1);
468         }       
469 }
470 /***********************************************************************/
471
472 string MothurOut::getFullPathName(string fileName){
473         try{
474         
475         string path = hasPath(fileName);
476         string newFileName;
477         int pos;
478         
479         if (path == "") { return fileName; } //its a simple name
480         else { //we need to complete the pathname
481                 // ex. ../../../filename 
482                 // cwd = /user/work/desktop
483                                 
484                 string cwd;
485                 //get current working directory 
486                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)   
487                         
488                         if (path.find("~") != -1) { //go to home directory
489                                 string homeDir = getenv ("HOME");
490                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
491                                 return newFileName;
492                         }else { //find path
493                                 if (path.rfind("./") == -1) { return fileName; } //already complete name
494                                 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
495                                 
496                                 char* cwdpath = new char[1024];
497
498                                 size_t size;
499                                 cwdpath=getcwd(cwdpath,size);
500                         
501                                 cwd = cwdpath;
502                                 
503                                 //rip off first '/'
504                                 string simpleCWD;
505                                 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
506                                 
507                                 //break apart the current working directory
508                                 vector<string> dirs;
509                                 while (simpleCWD.find_first_of('/') != -1) {
510                                         string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
511                                         simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
512                                         dirs.push_back(dir);
513                                 }
514                                 //get last one              // ex. ../../../filename = /user/work/desktop/filename
515                                 dirs.push_back(simpleCWD);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
516                                 
517                         
518                                 int index = dirs.size()-1;
519                 
520                                 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
521                                         if (pos == 0) { break;  //you are at the end
522                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
523                                                 path = path.substr(0, pos-1);
524                                                 index--;
525                                                 if (index == 0) {  break; }
526                                         }else if (path[(pos-1)] == '/') { //you want the current working dir ./
527                                                 path = path.substr(0, pos);
528                                         }else if (pos == 1) { break;  //you are at the end
529                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
530                                 }
531                         
532                                 for (int i = index; i >= 0; i--) {
533                                         newFileName = dirs[i] +  "/" + newFileName;             
534                                 }
535                                 
536                                 newFileName =  "/" +  newFileName;
537                                 return newFileName;
538                         }       
539                 #else
540                         if (path.find("~") != -1) { //go to home directory
541                                 string homeDir = getenv ("HOMEPATH");
542                                 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
543                                 return newFileName;
544                         }else { //find path
545                                 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
546                                 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
547                                                         
548                                 char *cwdpath = NULL;
549                                 cwdpath = getcwd(NULL, 0); // or _getcwd
550                                 if ( cwdpath != NULL) { cwd = cwdpath; }
551                                 else { cwd = "";  }
552                                 
553                                 //break apart the current working directory
554                                 vector<string> dirs;
555                                 while (cwd.find_first_of('\\') != -1) {
556                                         string dir = cwd.substr(0,cwd.find_first_of('\\'));
557                                         cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
558                                         dirs.push_back(dir);
559                 
560                                 }
561                                 //get last one
562                                 dirs.push_back(cwd);  //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
563                                         
564                                 int index = dirs.size()-1;
565                                         
566                                 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
567                                         if (pos == 0) { break;  //you are at the end
568                                         }else if (path[(pos-1)] == '.') { //you want your parent directory ../
569                                                 path = path.substr(0, pos-1);
570                                                 index--;
571                                                 if (index == 0) {  break; }
572                                         }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
573                                                 path = path.substr(0, pos);
574                                         }else if (pos == 1) { break;  //you are at the end
575                                         }else { cout << "cannot resolve path for " <<  fileName << endl; return fileName; }
576                                 }
577                         
578                                 for (int i = index; i >= 0; i--) {
579                                         newFileName = dirs[i] +  "\\" + newFileName;            
580                                 }
581                                 
582                                 return newFileName;
583                         }
584                         
585                 #endif
586         }
587         }
588         catch(exception& e) {
589                 errorOut(e, "MothurOut", "getFullPathName");
590                 exit(1);
591         }       
592 }
593 /***********************************************************************/
594
595 int MothurOut::openInputFile(string fileName, ifstream& fileHandle, string m){
596         try {
597                         //get full path name
598                         string completeFileName = getFullPathName(fileName);
599
600                         fileHandle.open(completeFileName.c_str());
601                         if(!fileHandle) {
602                                 return 1;
603                         }else {
604                                 //check for blank file
605                                 gobble(fileHandle);
606                                 return 0;
607                         }
608         }
609         catch(exception& e) {
610                 errorOut(e, "MothurOut", "openInputFile - no Error");
611                 exit(1);
612         }
613 }
614 /***********************************************************************/
615
616 int MothurOut::openInputFile(string fileName, ifstream& fileHandle){
617         try {
618                 //get full path name
619                 string completeFileName = getFullPathName(fileName);
620
621                 fileHandle.open(completeFileName.c_str());
622                 if(!fileHandle) {
623                         mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
624                         return 1;
625                 }
626                 else {
627                         //check for blank file
628                         gobble(fileHandle);
629                         if (fileHandle.eof()) { mothurOut("[ERROR]: " + completeFileName + " is blank. Please correct."); mothurOutEndLine();  }
630                         
631                         return 0;
632                 }
633         }
634         catch(exception& e) {
635                 errorOut(e, "MothurOut", "openInputFile");
636                 exit(1);
637         }       
638 }
639 /***********************************************************************/
640
641 int MothurOut::renameFile(string oldName, string newName){
642         try {
643                 ifstream inTest;
644                 int exist = openInputFile(newName, inTest, "");
645                 
646         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
647                 if (exist == 0) { //you could open it so you want to delete it
648                         inTest.close();
649                         string command = "rm " + newName;
650                         system(command.c_str());
651                 }
652                                 
653                 string command = "mv " + oldName + " " + newName;
654                 system(command.c_str());
655         #else
656                 remove(newName.c_str());
657                 int renameOk = rename(oldName.c_str(), newName.c_str());
658         #endif
659                 return 0;
660                 
661         }
662         catch(exception& e) {
663                 errorOut(e, "MothurOut", "renameFile");
664                 exit(1);
665         }       
666 }
667
668 /***********************************************************************/
669
670 int MothurOut::openOutputFile(string fileName, ofstream& fileHandle){
671         try { 
672         
673                 string completeFileName = getFullPathName(fileName);
674                 
675                 fileHandle.open(completeFileName.c_str(), ios::trunc);
676                 if(!fileHandle) {
677                         mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
678                         return 1;
679                 }
680                 else {
681                         return 0;
682                 }
683         }
684         catch(exception& e) {
685                 errorOut(e, "MothurOut", "openOutputFile");
686                 exit(1);
687         }       
688
689 }
690
691 /**************************************************************************************************/
692 void MothurOut::appendFiles(string temp, string filename) {
693         try{
694                 ofstream output;
695                 ifstream input;
696         
697                 //open output file in append mode
698                 openOutputFileAppend(filename, output);
699                 int ableToOpen = openInputFile(temp, input, "no error");
700                 
701                 if (ableToOpen == 0) { //you opened it
702                         while(char c = input.get()){
703                                 if(input.eof())         {       break;                  }
704                                 else                            {       output << c;    }
705                         }
706                         input.close();
707                 }
708                 
709                 output.close();
710         }
711         catch(exception& e) {
712                 errorOut(e, "MothurOut", "appendFiles");
713                 exit(1);
714         }       
715 }
716
717 /**************************************************************************************************/
718 string MothurOut::sortFile(string distFile, string outputDir){
719         try {   
720         
721                 //if (outputDir == "") {  outputDir += hasPath(distFile);  }
722                 string outfile = getRootName(distFile) + "sorted.dist";
723
724                 
725                 //if you can, use the unix sort since its been optimized for years
726                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
727                         string command = "sort -n -k +3 " + distFile + " -o " + outfile;
728                         system(command.c_str());
729                 #else //you are stuck with my best attempt...
730                         //windows sort does not have a way to specify a column, only a character in the line
731                         //since we cannot assume that the distance will always be at the the same character location on each line
732                         //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
733                 
734                         //read in file line by file and put distance first
735                         string tempDistFile = distFile + ".temp";
736                         ifstream input;
737                         ofstream output;
738                         openInputFile(distFile, input);
739                         openOutputFile(tempDistFile, output);
740
741                         string firstName, secondName;
742                         float dist;
743                         while (input) {
744                                 input >> firstName >> secondName >> dist;
745                                 output << dist << '\t' << firstName << '\t' << secondName << endl;
746                                 gobble(input);
747                         }
748                         input.close();
749                         output.close();
750                 
751         
752                         //sort using windows sort
753                         string tempOutfile = outfile + ".temp";
754                         string command = "sort " + tempDistFile + " /O " + tempOutfile;
755                         system(command.c_str());
756                 
757                         //read in sorted file and put distance at end again
758                         ifstream input2;
759                         openInputFile(tempOutfile, input2);
760                         openOutputFile(outfile, output);
761                 
762                         while (input2) {
763                                 input2 >> dist >> firstName >> secondName;
764                                 output << firstName << '\t' << secondName << '\t' << dist << endl;
765                                 gobble(input2);
766                         }
767                         input2.close();
768                         output.close();
769                 
770                         //remove temp files
771                         remove(tempDistFile.c_str());
772                         remove(tempOutfile.c_str());
773                 #endif
774                 
775                 return outfile;
776         }
777         catch(exception& e) {
778                 errorOut(e, "MothurOut", "sortFile");
779                 exit(1);
780         }       
781 }
782 /**************************************************************************************************/
783 vector<unsigned long int> MothurOut::setFilePosFasta(string filename, int& num) {
784         try {
785                         vector<unsigned long int> positions;
786                         ifstream inFASTA;
787                         openInputFile(filename, inFASTA);
788                                                 
789                         string input;
790                         while(!inFASTA.eof()){
791                                 input = getline(inFASTA); 
792                                 if (input.length() != 0) {
793                                         if(input[0] == '>'){    unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
794                                 }
795                                 gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
796                         }
797                         inFASTA.close();
798                 
799                         num = positions.size();
800                 
801                         /*FILE * pFile;
802                         long size;
803                 
804                         //get num bytes in file
805                         pFile = fopen (filename.c_str(),"rb");
806                         if (pFile==NULL) perror ("Error opening file");
807                         else{
808                                 fseek (pFile, 0, SEEK_END);
809                                 size=ftell (pFile);
810                                 fclose (pFile);
811                         }*/
812                         
813                         unsigned long int size = positions[(positions.size()-1)];
814                         ifstream in;
815                         openInputFile(filename, in);
816                         
817                         in.seekg(size);
818                 
819                         while(char c = in.get()){
820                                 if(in.eof())            {       break;  }
821                                 else                            {       size++; }
822                         }
823                         in.close();
824                 
825                         positions.push_back(size);
826                 
827                         return positions;
828         }
829         catch(exception& e) {
830                 errorOut(e, "MothurOut", "setFilePosFasta");
831                 exit(1);
832         }
833 }
834 /**************************************************************************************************/
835 vector<unsigned long int> MothurOut::setFilePosEachLine(string filename, int& num) {
836         try {
837                         filename = getFullPathName(filename);
838                         
839                         vector<unsigned long int> positions;
840                         ifstream in;
841                         openInputFile(filename, in);
842                                 
843                         string input;
844                         while(!in.eof()){
845                                 unsigned long int lastpos = in.tellg();
846                                 input = getline(in); 
847                                 if (input.length() != 0) {
848                                         unsigned long int pos = in.tellg(); 
849                                         if (pos != -1) { positions.push_back(pos - input.length() - 1); }
850                                         else {  positions.push_back(lastpos);  }
851                                 }
852                                 gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
853                         }
854                         in.close();
855                 
856                         num = positions.size();
857                 
858                         FILE * pFile;
859                         unsigned long int size;
860                         
861                         //get num bytes in file
862                         pFile = fopen (filename.c_str(),"rb");
863                         if (pFile==NULL) perror ("Error opening file");
864                         else{
865                                 fseek (pFile, 0, SEEK_END);
866                                 size=ftell (pFile);
867                                 fclose (pFile);
868                         }
869                 
870                         positions.push_back(size);
871                 
872                         return positions;
873         }
874         catch(exception& e) {
875                 errorOut(e, "MothurOut", "setFilePosEachLine");
876                 exit(1);
877         }
878 }
879 /**************************************************************************************************/
880
881 vector<unsigned long int> MothurOut::divideFile(string filename, int& proc) {
882         try{
883         
884                 vector<unsigned long int> filePos;
885                 filePos.push_back(0);
886                 
887                 FILE * pFile;
888                 unsigned long int size;
889                 
890                 filename = getFullPathName(filename);
891                 
892                 //get num bytes in file
893                 pFile = fopen (filename.c_str(),"rb");
894                 if (pFile==NULL) perror ("Error opening file");
895                 else{
896                         fseek (pFile, 0, SEEK_END);
897                         size=ftell (pFile);
898                         fclose (pFile);
899                 }
900         
901                 //estimate file breaks
902                 unsigned long int chunkSize = 0;
903                 chunkSize = size / proc;
904         
905                 //file to small to divide by processors
906                 if (chunkSize == 0)  {  proc = 1;       filePos.push_back(size); return filePos;        }
907         
908                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
909                 for (int i = 0; i < proc; i++) {
910                         unsigned long int spot = (i+1) * chunkSize;
911                         
912                         ifstream in;
913                         openInputFile(filename, in);
914                         in.seekg(spot);
915                         
916                         //look for next '>'
917                         unsigned long int newSpot = spot;
918                         while (!in.eof()) {
919                            char c = in.get();
920                            if (c == '>') {   in.putback(c); newSpot = in.tellg(); break;  }
921                         }
922                         
923                         //there was not another sequence before the end of the file
924                         unsigned long int sanityPos = in.tellg();
925
926                         if (sanityPos == -1) {  break;  }
927                         else {  filePos.push_back(newSpot);  }
928                         
929                         in.close();
930                 }
931                 
932                 //save end pos
933                 filePos.push_back(size);
934
935                 //sanity check filePos
936                 for (int i = 0; i < (filePos.size()-1); i++) {
937                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
938                 }
939
940                 proc = (filePos.size() - 1);
941                 
942                 return filePos;
943         }
944         catch(exception& e) {
945                 errorOut(e, "MothurOut", "divideFile");
946                 exit(1);
947         }
948 }
949
950 /***********************************************************************/
951
952 bool MothurOut::isTrue(string f){
953         try {
954                 
955                 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
956                 
957                 if ((f == "TRUE") || (f == "T")) {      return true;    }
958                 else {  return false;  }
959         }
960         catch(exception& e) {
961                 errorOut(e, "MothurOut", "isTrue");
962                 exit(1);
963         }
964 }
965
966 /***********************************************************************/
967
968 float MothurOut::roundDist(float dist, int precision){
969         try {
970                 return int(dist * precision + 0.5)/float(precision);
971         }
972         catch(exception& e) {
973                 errorOut(e, "MothurOut", "roundDist");
974                 exit(1);
975         }
976 }
977 /***********************************************************************/
978
979 float MothurOut::ceilDist(float dist, int precision){
980         try {
981                 return int(ceil(dist * precision))/float(precision);
982         }
983         catch(exception& e) {
984                 errorOut(e, "MothurOut", "ceilDist");
985                 exit(1);
986         }
987 }
988
989 /***********************************************************************/
990
991 int MothurOut::getNumNames(string names){
992         try {
993                 int count = 0;
994                 
995                 if(names != ""){
996                         count = 1;
997                         for(int i=0;i<names.size();i++){
998                                 if(names[i] == ','){
999                                         count++;
1000                                 }
1001                         }
1002                 }
1003                 
1004                 return count;
1005         }
1006         catch(exception& e) {
1007                 errorOut(e, "MothurOut", "getNumNames");
1008                 exit(1);
1009         }
1010 }
1011
1012 /**************************************************************************************************/
1013
1014 vector<vector<double> > MothurOut::binomial(int maxOrder){
1015         try {
1016         vector<vector<double> > binomial(maxOrder+1);
1017         
1018     for(int i=0;i<=maxOrder;i++){
1019                 binomial[i].resize(maxOrder+1);
1020                 binomial[i][0]=1;
1021                 binomial[0][i]=0;
1022     }
1023     binomial[0][0]=1;
1024         
1025     binomial[1][0]=1;
1026     binomial[1][1]=1;
1027         
1028     for(int i=2;i<=maxOrder;i++){
1029                 binomial[1][i]=0;
1030     }
1031         
1032     for(int i=2;i<=maxOrder;i++){
1033                 for(int j=1;j<=maxOrder;j++){
1034                         if(i==j){       binomial[i][j]=1;                                                                       }
1035                         if(j>i) {       binomial[i][j]=0;                                                                       }
1036                         else    {       binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j];     }
1037                 }
1038     }
1039         
1040         return binomial;
1041         
1042         }
1043         catch(exception& e) {
1044                 errorOut(e, "MothurOut", "binomial");
1045                 exit(1);
1046         }
1047 }
1048
1049 /***********************************************************************/
1050
1051 int MothurOut::factorial(int num){
1052         try {
1053                 int total = 1;
1054                 
1055                 for (int i = 1; i <= num; i++) {
1056                         total *= i;
1057                 }
1058                 
1059                 return total;
1060         }
1061         catch(exception& e) {
1062                 errorOut(e, "MothurOut", "factorial");
1063                 exit(1);
1064         }
1065 }
1066 /***********************************************************************/
1067
1068 int MothurOut::getNumSeqs(ifstream& file){
1069         try {
1070                 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1071                 file.seekg(0);
1072                 return numSeqs;
1073         }
1074         catch(exception& e) {
1075                 errorOut(e, "MothurOut", "getNumSeqs");
1076                 exit(1);
1077         }       
1078 }
1079 /***********************************************************************/
1080 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1081         try {
1082                 string input;
1083                 numSeqs = 0;
1084                 while(!file.eof()){
1085                         input = getline(file);
1086                         if (input.length() != 0) {
1087                                 if(input[0] == '>'){ numSeqs++; }
1088                         }
1089                 }
1090         }
1091         catch(exception& e) {
1092                 errorOut(e, "MothurOut", "getNumSeqs");
1093                 exit(1);
1094         }       
1095 }
1096 /***********************************************************************/
1097
1098 //This function parses the estimator options and puts them in a vector
1099 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1100         try {
1101                 string individual;
1102                 
1103                 while (estim.find_first_of(symbol) != -1) {
1104                         individual = estim.substr(0,estim.find_first_of(symbol));
1105                         if ((estim.find_first_of(symbol)+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1106                                 estim = estim.substr(estim.find_first_of(symbol)+1, estim.length());
1107                                 container.push_back(individual);
1108                         }
1109                 }
1110                 //get last one
1111                 container.push_back(estim);
1112         }
1113         catch(exception& e) {
1114                 errorOut(e, "MothurOut", "splitAtChar");
1115                 exit(1);
1116         }       
1117 }
1118
1119 /***********************************************************************/
1120
1121 //This function parses the estimator options and puts them in a vector
1122 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1123         try {
1124                 string individual = "";
1125                 int estimLength = estim.size();
1126                 for(int i=0;i<estimLength;i++){
1127                         if(estim[i] == '-'){
1128                                 container.push_back(individual);
1129                                 individual = "";                                
1130                         }
1131                         else{
1132                                 individual += estim[i];
1133                         }
1134                 }
1135                 container.push_back(individual);
1136
1137         
1138         /*      string individual;
1139                 
1140                 while (estim.find_first_of('-') != -1) {
1141                         individual = estim.substr(0,estim.find_first_of('-'));
1142                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1143                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1144                                 container.push_back(individual);
1145                         }
1146                 }
1147                 //get last one
1148                 container.push_back(estim); */
1149         }
1150         catch(exception& e) {
1151                 errorOut(e, "MothurOut", "splitAtDash");
1152                 exit(1);
1153         }       
1154 }
1155
1156 /***********************************************************************/
1157 //This function parses the label options and puts them in a set
1158 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1159         try {
1160                 string individual = "";
1161                 int estimLength = estim.size();
1162                 for(int i=0;i<estimLength;i++){
1163                         if(estim[i] == '-'){
1164                                 container.insert(individual);
1165                                 individual = "";                                
1166                         }
1167                         else{
1168                                 individual += estim[i];
1169                         }
1170                 }
1171                 container.insert(individual);
1172
1173         //      string individual;
1174                 
1175         //      while (estim.find_first_of('-') != -1) {
1176         //              individual = estim.substr(0,estim.find_first_of('-'));
1177         //              if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1178         //                      estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1179         //                      container.insert(individual);
1180         //              }
1181         //      }
1182                 //get last one
1183         //      container.insert(estim);
1184         
1185         }
1186         catch(exception& e) {
1187                 errorOut(e, "MothurOut", "splitAtDash");
1188                 exit(1);
1189         }       
1190 }
1191 /***********************************************************************/
1192 //This function parses the line options and puts them in a set
1193 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1194         try {
1195                 string individual;
1196                 int lineNum;
1197                 
1198                 while (estim.find_first_of('-') != -1) {
1199                         individual = estim.substr(0,estim.find_first_of('-'));
1200                         if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1201                                 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1202                                 convert(individual, lineNum); //convert the string to int
1203                                 container.insert(lineNum);
1204                         }
1205                 }
1206                 //get last one
1207                 convert(estim, lineNum); //convert the string to int
1208                 container.insert(lineNum);
1209         }
1210         catch(exception& e) {
1211                 errorOut(e, "MothurOut", "splitAtDash");
1212                 exit(1);
1213         }       
1214 }
1215 /***********************************************************************/
1216 //This function parses the a string and puts peices in a vector
1217 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1218         try {
1219                 string individual = "";
1220                 int estimLength = estim.size();
1221                 for(int i=0;i<estimLength;i++){
1222                         if(estim[i] == ','){
1223                                 container.push_back(individual);
1224                                 individual = "";                                
1225                         }
1226                         else{
1227                                 individual += estim[i];
1228                         }
1229                 }
1230                 container.push_back(individual);
1231                 
1232                 
1233                 
1234                 
1235 //              string individual;
1236 //              
1237 //              while (estim.find_first_of(',') != -1) {
1238 //                      individual = estim.substr(0,estim.find_first_of(','));
1239 //                      if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1240 //                              estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1241 //                              container.push_back(individual);
1242 //                      }
1243 //              }
1244 //              //get last one
1245 //              container.push_back(estim);
1246         }
1247         catch(exception& e) {
1248                 errorOut(e, "MothurOut", "splitAtComma");
1249                 exit(1);
1250         }       
1251 }
1252 /***********************************************************************/
1253
1254 //This function splits up the various option parameters
1255 void MothurOut::splitAtComma(string& prefix, string& suffix){
1256         try {
1257                 prefix = suffix.substr(0,suffix.find_first_of(','));
1258                 if ((suffix.find_first_of(',')+2) <= suffix.length()) {  //checks to make sure you don't have comma at end of string
1259                         suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1260                         string space = " ";
1261                         while(suffix.at(0) == ' ')
1262                                 suffix = suffix.substr(1, suffix.length());
1263                 }
1264
1265         }
1266         catch(exception& e) {
1267                 errorOut(e, "MothurOut", "splitAtComma");
1268                 exit(1);
1269         }       
1270 }
1271 /***********************************************************************/
1272
1273 //This function separates the key value from the option value i.e. dist=96_...
1274 void MothurOut::splitAtEquals(string& key, string& value){              
1275         try {
1276                 if(value.find_first_of('=') != -1){
1277                         key = value.substr(0,value.find_first_of('='));
1278                         if ((value.find_first_of('=')+1) <= value.length()) {
1279                                 value = value.substr(value.find_first_of('=')+1, value.length());
1280                         }
1281                 }else{
1282                         key = value;
1283                         value = 1;
1284                 }
1285         }
1286         catch(exception& e) {
1287                 errorOut(e, "MothurOut", "splitAtEquals");
1288                 exit(1);
1289         }       
1290 }
1291
1292 /**************************************************************************************************/
1293
1294 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1295         try {
1296                 for (int i = 0; i < Groups.size(); i++) {
1297                         if (groupname == Groups[i]) { return true; }
1298                 }
1299                 return false;
1300         }
1301         catch(exception& e) {
1302                 errorOut(e, "MothurOut", "inUsersGroups");
1303                 exit(1);
1304         }       
1305 }
1306 /**************************************************************************************************/
1307 //returns true if any of the strings in first vector are in second vector
1308 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1309         try {
1310                 
1311                 for (int i = 0; i < groupnames.size(); i++) {
1312                         if (inUsersGroups(groupnames[i], Groups)) { return true; }
1313                 }
1314                 return false;
1315         }
1316         catch(exception& e) {
1317                 errorOut(e, "MothurOut", "inUsersGroups");
1318                 exit(1);
1319         }       
1320 }
1321 /***********************************************************************/
1322 //this function determines if the user has given us labels that are smaller than the given label.
1323 //if so then it returns true so that the calling function can run the previous valid distance.
1324 //it's a "smart" distance function.  It also checks for invalid labels.
1325 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1326         try {
1327                 
1328                 set<string>::iterator it;
1329                 vector<float> orderFloat;
1330                 map<string, float> userMap;  //the conversion process removes trailing 0's which we need to put back
1331                 map<string, float>::iterator it2;
1332                 float labelFloat;
1333                 bool smaller = false;
1334                 
1335                 //unique is the smallest line
1336                 if (label == "unique") {  return false;  }
1337                 else { 
1338                         if (convertTestFloat(label, labelFloat)) {
1339                                 convert(label, labelFloat); 
1340                         }else { //cant convert 
1341                                 return false;
1342                         }
1343                 }
1344                 
1345                 //go through users set and make them floats
1346                 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
1347                         
1348                         float temp;
1349                         if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1350                                 convert(*it, temp);
1351                                 orderFloat.push_back(temp);
1352                                 userMap[*it] = temp;
1353                         }else if (*it == "unique") { 
1354                                 orderFloat.push_back(-1.0);
1355                                 userMap["unique"] = -1.0;
1356                         }else {
1357                                 if (errorOff == "") {  cout << *it << " is not a valid label." << endl;  }
1358                                 userLabels.erase(*it); 
1359                                 it--;
1360                         }
1361                 }
1362                 
1363                 //sort order
1364                 sort(orderFloat.begin(), orderFloat.end());
1365                 
1366                 /*************************************************/
1367                 //is this label bigger than any of the users labels
1368                 /*************************************************/
1369                                 
1370                 //loop through order until you find a label greater than label
1371                 for (int i = 0; i < orderFloat.size(); i++) {
1372                         if (orderFloat[i] < labelFloat) {
1373                                 smaller = true;
1374                                 if (orderFloat[i] == -1) { 
1375                                         if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
1376                                         userLabels.erase("unique");
1377                                 }
1378                                 else {  
1379                                         if (errorOff == "") { cout << "Your file does not include the label " << endl; }
1380                                         string s = "";
1381                                         for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {  
1382                                                 if (it2->second == orderFloat[i]) {  
1383                                                         s = it2->first;  
1384                                                         //remove small labels
1385                                                         userLabels.erase(s);
1386                                                         break;
1387                                                 }
1388                                         }
1389                                         if (errorOff == "") {cout << s <<  ". I will use the next smallest distance. " << endl; }
1390                                 }
1391                         //since they are sorted once you find a bigger one stop looking
1392                         }else { break; }
1393                 }
1394                 
1395                 return smaller;
1396                                                 
1397         }
1398         catch(exception& e) {
1399                 errorOut(e, "MothurOut", "anyLabelsToProcess");
1400                 exit(1);
1401         }       
1402 }
1403
1404 /**************************************************************************************************/
1405 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1406         try {
1407                 
1408                 bool good = true;
1409                 
1410                 string line = getline(file);  
1411
1412                 //before we added this check
1413                 if (line[0] != '#') {  good = false;  }
1414                 else {
1415                         //rip off #
1416                         line = line.substr(1);
1417                         
1418                         vector<string> versionVector;
1419                         splitAtChar(version, versionVector, '.');
1420                         
1421                         //check file version
1422                         vector<string> linesVector;
1423                         splitAtChar(line, linesVector, '.');
1424                         
1425                         if (versionVector.size() != linesVector.size()) { good = false; }
1426                         else {
1427                                 for (int j = 0; j < versionVector.size(); j++) {
1428                                         int num1, num2;
1429                                         convert(versionVector[j], num1);
1430                                         convert(linesVector[j], num2);
1431                                         
1432                                         //if mothurs version is newer than this files version, then we want to remake it
1433                                         if (num1 > num2) {  good = false; break;  }
1434                                 }
1435                         }
1436                         
1437                 }
1438                 
1439                 if (!good) {  file.close();  }
1440                 else { file.seekg(0);  }
1441                 
1442                 return good;
1443         }
1444         catch(exception& e) {
1445                 errorOut(e, "MothurOut", "checkReleaseVersion");                
1446                 exit(1);
1447         }
1448 }
1449 /**************************************************************************************************/
1450
1451
1452
1453
1454