]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
fixed bug in phylo.diversity rooting. added filename patterns and create filename...
[mothur.git] / chimeraslayercommand.cpp
1 /*
2  *  chimeraslayercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 3/31/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeraslayercommand.h"
11 #include "deconvolutecommand.h"
12 #include "referencedb.h"
13 #include "sequenceparser.h"
14 #include "counttable.h"
15
16 //**********************************************************************************************************************
17 vector<string> ChimeraSlayerCommand::setParameters(){   
18         try {
19                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptemplate);
20                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","chimera-accnos",false,true,true); parameters.push_back(pfasta);
21                 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
22          CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
23                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
24                 CommandParameter pwindow("window", "Number", "", "50", "", "", "","",false,false); parameters.push_back(pwindow);
25                 CommandParameter pksize("ksize", "Number", "", "7", "", "", "","",false,false); parameters.push_back(pksize);
26                 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "","",false,false); parameters.push_back(pmatch);
27                 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "","",false,false); parameters.push_back(pmismatch);
28                 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminsim);
29                 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "","",false,false); parameters.push_back(pmincov);
30                 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "","",false,false); parameters.push_back(pminsnp);
31                 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminbs);
32                 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "","",false,false); parameters.push_back(psearch);
33                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
34                 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(prealign);
35                 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "","fasta",false,false); parameters.push_back(ptrim);
36                 CommandParameter psplit("split", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psplit);
37                 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "","",false,false); parameters.push_back(pnumwanted);
38                 CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(piters);
39                 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "","",false,false); parameters.push_back(pdivergence);
40                 CommandParameter pparents("parents", "Number", "", "3", "", "", "","",false,false); parameters.push_back(pparents);
41                 CommandParameter pincrement("increment", "Number", "", "5", "", "", "","",false,false); parameters.push_back(pincrement);
42                 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "","",false,false); parameters.push_back(pblastlocation);
43                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
44                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
45                 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
46
47                 vector<string> myArray;
48                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
49                 return myArray;
50         }
51         catch(exception& e) {
52                 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
53                 exit(1);
54         }
55 }
56 //**********************************************************************************************************************
57 string ChimeraSlayerCommand::getHelpString(){   
58         try {
59                 string helpString = "";
60                 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
61                 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
62                 helpString += "The chimera.slayer command parameters are fasta, name, group, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
63                 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
64                 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
65                 helpString += "The group parameter allows you to provide a group file. The group file can be used with a namesfile and reference=self. When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
66         helpString += "The count parameter allows you to provide a count file. The count file reference=self. If your count file contains group information, when checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
67                 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
68                 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
69                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
70 #ifdef USE_MPI
71                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
72 #endif
73                 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
74                 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
75                 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
76                 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
77                 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
78                 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
79                 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
80                 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
81                 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
82                 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
83                 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
84                 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
85                 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
86                 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
87                 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
88                 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
89                 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true.  \n";
90                 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable.  \n";
91                 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
92                 helpString += "The chimera.slayer command should be in the following format: \n";
93                 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
94                 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
95                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
96                 return helpString;
97         }
98         catch(exception& e) {
99                 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
100                 exit(1);
101         }
102 }
103 //**********************************************************************************************************************
104 string ChimeraSlayerCommand::getOutputPattern(string type) {
105     try {
106         string pattern = "";
107         
108         if (type == "chimera") {  pattern = "[filename],slayer.chimeras"; } 
109         else if (type == "accnos") {  pattern = "[filename],slayer.accnos"; } 
110         else if (type == "fasta") {  pattern = "[filename],slayer.fasta"; } 
111         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
112         
113         return pattern;
114     }
115     catch(exception& e) {
116         m->errorOut(e, "ChimeraSlayerCommand", "getOutputPattern");
117         exit(1);
118     }
119 }
120 //**********************************************************************************************************************
121 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
122         try {
123                 abort = true; calledHelp = true;
124                 setParameters();
125                 vector<string> tempOutNames;
126                 outputTypes["chimera"] = tempOutNames;
127                 outputTypes["accnos"] = tempOutNames;
128                 outputTypes["fasta"] = tempOutNames;
129         }
130         catch(exception& e) {
131                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
132                 exit(1);
133         }
134 }
135 //***************************************************************************************************************
136 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
137         try {
138                 abort = false; calledHelp = false;   
139                 ReferenceDB* rdb = ReferenceDB::getInstance();
140         hasCount = false;
141         hasName = false;
142                 
143                 //allow user to run help
144                 if(option == "help") { help(); abort = true; calledHelp = true; }
145                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
146                 
147                 else {
148                         vector<string> myArray = setParameters();
149                         
150                         OptionParser parser(option);
151                         map<string,string> parameters = parser.getParameters();
152                         
153                         ValidParameters validParameter("chimera.slayer");
154                         map<string,string>::iterator it;
155                         
156                         //check to make sure all parameters are valid for command
157                         for (it = parameters.begin(); it != parameters.end(); it++) { 
158                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
159                         }
160                         
161                         vector<string> tempOutNames;
162                         outputTypes["chimera"] = tempOutNames;
163                         outputTypes["accnos"] = tempOutNames;
164                         outputTypes["fasta"] = tempOutNames;
165                 
166                         //if the user changes the input directory command factory will send this info to us in the output parameter 
167                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
168                         if (inputDir == "not found"){   inputDir = "";          }
169                                                 
170                         //check for required parameters
171                         fastafile = validParameter.validFile(parameters, "fasta", false);
172                         if (fastafile == "not found") {                                 
173                                 //if there is a current fasta file, use it
174                                 string filename = m->getFastaFile(); 
175                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
176                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
177                         }else { 
178                                 m->splitAtDash(fastafile, fastaFileNames);
179                                 
180                                 //go through files and make sure they are good, if not, then disregard them
181                                 for (int i = 0; i < fastaFileNames.size(); i++) {
182                                         
183                                         bool ignore = false;
184                                         if (fastaFileNames[i] == "current") { 
185                                                 fastaFileNames[i] = m->getFastaFile(); 
186                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
187                                                 else {  
188                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
189                                                         //erase from file list
190                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
191                                                         i--;
192                                                 }
193                                         }
194                                         
195                                         if (!ignore) {
196                                                 
197                                                 if (inputDir != "") {
198                                                         string path = m->hasPath(fastaFileNames[i]);
199                                                         //if the user has not given a path then, add inputdir. else leave path alone.
200                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
201                                                 }
202                 
203                                                 int ableToOpen;
204                                                 ifstream in;
205                                                 
206                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
207                                         
208                                                 //if you can't open it, try default location
209                                                 if (ableToOpen == 1) {
210                                                         if (m->getDefaultPath() != "") { //default path is set
211                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
212                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
213                                                                 ifstream in2;
214                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
215                                                                 in2.close();
216                                                                 fastaFileNames[i] = tryPath;
217                                                         }
218                                                 }
219                                                 
220                                                 if (ableToOpen == 1) {
221                                                         if (m->getOutputDir() != "") { //default path is set
222                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
223                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
224                                                                 ifstream in2;
225                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
226                                                                 in2.close();
227                                                                 fastaFileNames[i] = tryPath;
228                                                         }
229                                                 }
230                                                 
231                                                 in.close();
232                                                 
233                                                 if (ableToOpen == 1) { 
234                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
235                                                         //erase from file list
236                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
237                                                         i--;
238                                                 }else {
239                                                         m->setFastaFile(fastaFileNames[i]);
240                                                 }
241                                         }
242                                 }
243                                 
244                                 //make sure there is at least one valid file left
245                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
246                         }
247                         
248                         
249                         //check for required parameters
250                         namefile = validParameter.validFile(parameters, "name", false);
251                         if (namefile == "not found") { namefile = "";   }
252                         else { 
253                                 m->splitAtDash(namefile, nameFileNames);
254                                 
255                                 //go through files and make sure they are good, if not, then disregard them
256                                 for (int i = 0; i < nameFileNames.size(); i++) {
257                                         
258                                         bool ignore = false;
259                                         if (nameFileNames[i] == "current") { 
260                                                 nameFileNames[i] = m->getNameFile(); 
261                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
262                                                 else {  
263                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
264                                                         //erase from file list
265                                                         nameFileNames.erase(nameFileNames.begin()+i);
266                                                         i--;
267                                                 }
268                                         }
269                                         
270                                         if (!ignore) {
271                                                 
272                                                 if (inputDir != "") {
273                                                         string path = m->hasPath(nameFileNames[i]);
274                                                         //if the user has not given a path then, add inputdir. else leave path alone.
275                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
276                                                 }
277                                                 
278                                                 int ableToOpen;
279                                                 ifstream in;
280                                                 
281                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
282                                                 
283                                                 //if you can't open it, try default location
284                                                 if (ableToOpen == 1) {
285                                                         if (m->getDefaultPath() != "") { //default path is set
286                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
287                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
288                                                                 ifstream in2;
289                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
290                                                                 in2.close();
291                                                                 nameFileNames[i] = tryPath;
292                                                         }
293                                                 }
294                                                 
295                                                 if (ableToOpen == 1) {
296                                                         if (m->getOutputDir() != "") { //default path is set
297                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
298                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
299                                                                 ifstream in2;
300                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
301                                                                 in2.close();
302                                                                 nameFileNames[i] = tryPath;
303                                                         }
304                                                 }
305                                                 
306                                                 in.close();
307                                                 
308                                                 if (ableToOpen == 1) { 
309                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
310                                                         //erase from file list
311                                                         nameFileNames.erase(nameFileNames.begin()+i);
312                                                         i--;
313                                                 }else {
314                                                         m->setNameFile(nameFileNames[i]);
315                                                 }
316                                         }
317                                 }
318                         }
319             
320             if (nameFileNames.size() != 0) { hasName = true; }
321             
322             //check for required parameters
323             vector<string> countfileNames;
324                         countfile = validParameter.validFile(parameters, "count", false);
325                         if (countfile == "not found") { 
326                 countfile = "";  
327                         }else { 
328                                 m->splitAtDash(countfile, countfileNames);
329                                 
330                                 //go through files and make sure they are good, if not, then disregard them
331                                 for (int i = 0; i < countfileNames.size(); i++) {
332                                         
333                                         bool ignore = false;
334                                         if (countfileNames[i] == "current") { 
335                                                 countfileNames[i] = m->getCountTableFile(); 
336                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
337                                                 else {  
338                                                         m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true; 
339                                                         //erase from file list
340                                                         countfileNames.erase(countfileNames.begin()+i);
341                                                         i--;
342                                                 }
343                                         }
344                                         
345                                         if (!ignore) {
346                                                 
347                                                 if (inputDir != "") {
348                                                         string path = m->hasPath(countfileNames[i]);
349                                                         //if the user has not given a path then, add inputdir. else leave path alone.
350                                                         if (path == "") {       countfileNames[i] = inputDir + countfileNames[i];               }
351                                                 }
352                                                 
353                                                 int ableToOpen;
354                                                 ifstream in;
355                                                 
356                                                 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
357                                                 
358                                                 //if you can't open it, try default location
359                                                 if (ableToOpen == 1) {
360                                                         if (m->getDefaultPath() != "") { //default path is set
361                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
362                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
363                                                                 ifstream in2;
364                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
365                                                                 in2.close();
366                                                                 countfileNames[i] = tryPath;
367                                                         }
368                                                 }
369                                                 
370                                                 if (ableToOpen == 1) {
371                                                         if (m->getOutputDir() != "") { //default path is set
372                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
373                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
374                                                                 ifstream in2;
375                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
376                                                                 in2.close();
377                                                                 countfileNames[i] = tryPath;
378                                                         }
379                                                 }
380                                                 
381                                                 in.close();
382                                                 
383                                                 if (ableToOpen == 1) { 
384                                                         m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
385                                                         //erase from file list
386                                                         countfileNames.erase(countfileNames.begin()+i);
387                                                         i--;
388                                                 }else {
389                                                         m->setCountTableFile(countfileNames[i]);
390                                                 }
391                                         }
392                                 }
393                         }
394             
395             if (countfileNames.size() != 0) { hasCount = true; }
396             
397                         //make sure there is at least one valid file left
398             if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
399             
400             if (!hasName && hasCount) { nameFileNames = countfileNames; }
401             
402                         if ((hasCount || hasName) && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of name or count files does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
403                         
404                         bool hasGroup = true;
405                         groupfile = validParameter.validFile(parameters, "group", false);
406                         if (groupfile == "not found") { groupfile = "";  hasGroup = false; }
407                         else { 
408                                 m->splitAtDash(groupfile, groupFileNames);
409                                 
410                                 //go through files and make sure they are good, if not, then disregard them
411                                 for (int i = 0; i < groupFileNames.size(); i++) {
412                                         
413                                         bool ignore = false;
414                                         if (groupFileNames[i] == "current") { 
415                                                 groupFileNames[i] = m->getGroupFile(); 
416                                                 if (groupFileNames[i] != "") {  m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
417                                                 else {  
418                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
419                                                         //erase from file list
420                                                         groupFileNames.erase(groupFileNames.begin()+i);
421                                                         i--;
422                                                 }
423                                         }
424                                         
425                                         if (!ignore) {
426                                                 
427                                                 if (inputDir != "") {
428                                                         string path = m->hasPath(groupFileNames[i]);
429                                                         //if the user has not given a path then, add inputdir. else leave path alone.
430                                                         if (path == "") {       groupFileNames[i] = inputDir + groupFileNames[i];               }
431                                                 }
432                                                 
433                                                 int ableToOpen;
434                                                 ifstream in;
435                                                 
436                                                 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
437                                                 
438                                                 //if you can't open it, try default location
439                                                 if (ableToOpen == 1) {
440                                                         if (m->getDefaultPath() != "") { //default path is set
441                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
442                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
443                                                                 ifstream in2;
444                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
445                                                                 in2.close();
446                                                                 groupFileNames[i] = tryPath;
447                                                         }
448                                                 }
449                                                 
450                                                 if (ableToOpen == 1) {
451                                                         if (m->getOutputDir() != "") { //default path is set
452                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
453                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
454                                                                 ifstream in2;
455                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
456                                                                 in2.close();
457                                                                 groupFileNames[i] = tryPath;
458                                                         }
459                                                 }
460                                                 
461                                                 in.close();
462                                                 
463                                                 if (ableToOpen == 1) { 
464                                                         m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
465                                                         //erase from file list
466                                                         groupFileNames.erase(groupFileNames.begin()+i);
467                                                         i--;
468                                                 }else {
469                                                         m->setGroupFile(groupFileNames[i]);
470                                                 }
471                                         }
472                                 }
473                                 
474                                 //make sure there is at least one valid file left
475                                 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
476                         }
477                         
478                         if (hasGroup && (groupFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of groupfiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
479                         
480             if (hasGroup && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }                      
481                         //if the user changes the output directory command factory will send this info to us in the output parameter 
482                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
483                         
484                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
485                         m->setProcessors(temp);
486                         m->mothurConvert(temp, processors);
487                         
488                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
489                         save = m->isTrue(temp); 
490                         rdb->save = save; 
491                         if (save) { //clear out old references
492                                 rdb->clearMemory();     
493                         }
494                         
495                         string path;
496                         it = parameters.find("reference");
497                         //user has given a template file
498                         if(it != parameters.end()){ 
499                                 if (it->second == "self") { 
500                                         templatefile = "self"; 
501                                         if (save) {
502                                                 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
503                                                 m->mothurOutEndLine();
504                                                 save = false;
505                                         }
506                                 }
507                                 else {
508                                         path = m->hasPath(it->second);
509                                         //if the user has not given a path then, add inputdir. else leave path alone.
510                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
511                                         
512                                         templatefile = validParameter.validFile(parameters, "reference", true);
513                                         if (templatefile == "not open") { abort = true; }
514                                         else if (templatefile == "not found") { //check for saved reference sequences
515                                                 if (rdb->referenceSeqs.size() != 0) {
516                                                         templatefile = "saved";
517                                                 }else {
518                                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
519                                                         m->mothurOutEndLine();
520                                                         abort = true; 
521                                                 }
522                                         }else { if (save) {     rdb->setSavedReference(templatefile);   }       }       
523                                 }
524                         }else if (hasName) {  templatefile = "self"; 
525                                 if (save) {
526                                         m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
527                                         m->mothurOutEndLine();
528                                         save = false;
529                                 }
530                         }else if (hasCount) {  templatefile = "self"; 
531                                 if (save) {
532                                         m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
533                                         m->mothurOutEndLine();
534                                         save = false;
535                                 }
536                         }
537                         else { 
538                                 if (rdb->referenceSeqs.size() != 0) {
539                                         templatefile = "saved";
540                                 }else {
541                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
542                                         m->mothurOutEndLine();
543                                         templatefile = ""; abort = true; 
544                                 } 
545                         }
546                         
547                         
548                         
549                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
550                         m->mothurConvert(temp, ksize);
551                                                 
552                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
553                         m->mothurConvert(temp, window);
554                         
555                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
556                         m->mothurConvert(temp, match);
557                         
558                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
559                         m->mothurConvert(temp, mismatch);
560                         
561                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
562                         m->mothurConvert(temp, divR);
563                         
564                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
565                         m->mothurConvert(temp, minSimilarity);
566                         
567                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
568                         m->mothurConvert(temp, minCoverage);
569                         
570                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
571                         m->mothurConvert(temp, minBS);
572                         
573                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "10"; }
574                         m->mothurConvert(temp, minSNP);
575
576                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
577                         m->mothurConvert(temp, parents); 
578                         
579                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "t"; }
580                         realign = m->isTrue(temp); 
581                         
582                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
583                         trim = m->isTrue(temp); 
584                         
585                         temp = validParameter.validFile(parameters, "split", false);                    if (temp == "not found") { temp = "f"; }
586                         trimera = m->isTrue(temp); 
587                         
588                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "blast"; }
589                         
590                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "1000"; }             
591                         m->mothurConvert(temp, iters); 
592                          
593                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
594                         m->mothurConvert(temp, increment);
595                         
596                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
597                         m->mothurConvert(temp, numwanted);
598                         
599                         blastlocation = validParameter.validFile(parameters, "blastlocation", false);   
600                         if (blastlocation == "not found") { blastlocation = ""; }
601                         else {
602                                 //add / to name if needed
603                                 string lastChar = blastlocation.substr(blastlocation.length()-1);
604 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
605                                 if (lastChar != "/") { blastlocation += "/"; }
606 #else
607                                 if (lastChar != "\\") { blastlocation += "\\"; }        
608 #endif
609                                 blastlocation = m->getFullPathName(blastlocation);
610                                 string formatdbCommand = "";
611 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
612                                 formatdbCommand = blastlocation + "formatdb";   
613 #else
614                                 formatdbCommand = blastlocation + "formatdb.exe";
615 #endif
616                                 
617                                 //test to make sure formatdb exists
618                                 ifstream in;
619                                 formatdbCommand = m->getFullPathName(formatdbCommand);
620                                 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
621                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
622                                 
623                                 string blastCommand = "";
624 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
625                                 blastCommand = blastlocation + "megablast";     
626 #else
627                                 blastCommand = blastlocation + "megablast.exe";
628 #endif
629                                 //test to make sure formatdb exists
630                                 ifstream in2;
631                                 blastCommand = m->getFullPathName(blastCommand);
632                                 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
633                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
634                         }
635
636                         if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
637                         
638                         if ((hasName || hasCount) && (templatefile != "self")) { m->mothurOut("You have provided a namefile or countfile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
639                         if (hasGroup && (templatefile != "self")) { m->mothurOut("You have provided a group file and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
640
641                         //until we resolve the issue 10-18-11
642 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
643 #else
644                         //processors=1;
645 #endif
646                 }
647         }
648         catch(exception& e) {
649                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
650                 exit(1);
651         }
652 }
653 //***************************************************************************************************************
654
655 int ChimeraSlayerCommand::execute(){
656         try{
657                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
658
659                 for (int s = 0; s < fastaFileNames.size(); s++) {
660                                 
661                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
662                 
663                         int start = time(NULL); 
664                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it       
665                         map<string, string> variables; 
666             variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
667                         string outputFileName = getOutputFileName("chimera", variables);
668                         string accnosFileName = getOutputFileName("accnos", variables);
669                         string trimFastaFileName = getOutputFileName("fasta", variables);
670                         
671                         //clears files
672                         ofstream out, out1, out2;
673                         m->openOutputFile(outputFileName, out); out.close(); 
674                         m->openOutputFile(accnosFileName, out1); out1.close();
675                         if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
676                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
677                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
678                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }                     
679                         
680                         //maps a filename to priority map. 
681                         //if no groupfile this is fastafileNames[s] -> prioirity
682                         //if groupfile then this is each groups seqs -> priority
683                         map<string, map<string, int> > fileToPriority; 
684                         map<string, map<string, int> >::iterator itFile;
685                         map<string, string> fileGroup;
686                         fileToPriority[fastaFileNames[s]] = priority; //default
687                         fileGroup[fastaFileNames[s]] = "noGroup";
688             map<string, string> uniqueNames; 
689                         int totalChimeras = 0;
690                         lines.clear();
691                         
692                         if (templatefile == "self") { 
693                 if (hasCount) {
694                     SequenceCountParser* parser = NULL;
695                     setUpForSelfReference(parser, fileGroup, fileToPriority, s); 
696                     if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
697                 }else {
698                     SequenceParser* parser = NULL;
699                     setUpForSelfReference(parser, fileGroup, fileToPriority, s); 
700                     if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
701                 }
702             }
703                         
704                         if (m->control_pressed) {   for (int j = 0; j < outputNames.size(); j++) {      m->mothurRemove(outputNames[j]);        }  return 0;    }
705
706                         if (fileToPriority.size() == 1) { //you running without a groupfile
707                                 itFile = fileToPriority.begin();
708                                 string thisFastaName = itFile->first;
709                                 map<string, int> thisPriority = itFile->second;
710 #ifdef USE_MPI  
711                                 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
712 #else
713                                 //break up file
714                                 vector<unsigned long long> positions; 
715 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
716                                 positions = m->divideFile(thisFastaName, processors);
717                                 for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(linePair(positions[i], positions[(i+1)]));      }
718 #else
719                                 if (processors == 1) {  lines.push_back(linePair(0, 1000)); }
720                                 else {
721                                         positions = m->setFilePosFasta(thisFastaName, numSeqs); 
722                     if (positions.size() < processors) { processors = positions.size(); }
723                                         
724                                         //figure out how many sequences you have to process
725                                         int numSeqsPerProcessor = numSeqs / processors;
726                                         for (int i = 0; i < processors; i++) {
727                                                 int startIndex =  i * numSeqsPerProcessor;
728                                                 if(i == (processors - 1)){      numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor;        }
729                                                 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
730                                         }
731                                 }
732 #endif
733                                 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority);  }
734                                 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
735                                 
736                                 if (m->control_pressed) {  outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) {      m->mothurRemove(outputNames[j]);        }  return 0; }                          
737 #endif
738                         }else { //you have provided a groupfile
739 #ifdef USE_MPI  
740                                 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
741 #else
742                                 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);    }
743                                 else {  numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);          } //destroys fileToPriority
744 #endif
745
746 #ifdef USE_MPI  
747                                 int pid; 
748                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
749                                 
750                                 if (pid == 0) {
751 #endif
752                                 totalChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName, trimFastaFileName);
753                 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
754 #ifdef USE_MPI  
755                                 }
756                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
757 #endif
758                         }
759                         
760             m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");    m->mothurOutEndLine();
761                 }
762                 
763                 //set accnos file as new current accnosfile
764                 string current = "";
765                 itTypes = outputTypes.find("accnos");
766                 if (itTypes != outputTypes.end()) {
767                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
768                 }
769                 
770                 if (trim) {
771                         itTypes = outputTypes.find("fasta");
772                         if (itTypes != outputTypes.end()) {
773                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
774                         }
775                 }
776                 
777                 m->mothurOutEndLine();
778                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
779                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
780                 m->mothurOutEndLine();
781
782                 return 0;
783                 
784         }
785         catch(exception& e) {
786                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
787                 exit(1);
788         }
789 }
790 //**********************************************************************************************************************
791 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
792         try {
793 #ifdef USE_MPI  
794                 int pid; 
795                 int tag = 2001;
796                 
797                 MPI_Status status; 
798                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
799                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
800         
801                 //put filenames in a vector, then pass each process a starting and ending point in the vector
802                 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
803                 map<string, map<string, int> >::iterator itFile;
804                 vector<string> filenames;
805                 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
806                 
807                 int numGroupsPerProcessor = filenames.size() / processors;
808                 int startIndex =  pid * numGroupsPerProcessor;
809                 int endIndex = (pid+1) * numGroupsPerProcessor;
810                 if(pid == (processors - 1)){    endIndex = filenames.size();    }
811                 
812                 vector<unsigned long long> MPIPos;
813                 
814                 MPI_File outMPI;
815                 MPI_File outMPIAccnos;
816                 MPI_File outMPIFasta;
817                 
818                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
819                 int inMode=MPI_MODE_RDONLY; 
820                 
821                 char outFilename[1024];
822                 strcpy(outFilename, outputFileName.c_str());
823                 
824                 char outAccnosFilename[1024];
825                 strcpy(outAccnosFilename, accnosFileName.c_str());
826                 
827                 char outFastaFilename[1024];
828                 strcpy(outFastaFilename, trimFastaFileName.c_str());
829                 
830                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
831                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
832                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
833                 
834                 if (m->control_pressed) {   MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  return 0;  }
835                 
836                 //print headers
837                 if (pid == 0) { //you are the root process 
838                         m->mothurOutEndLine();
839                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
840                         m->mothurOutEndLine();
841                         
842                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
843                         
844                         //print header
845                         int length = outTemp.length();
846                         char* buf2 = new char[length];
847                         memcpy(buf2, outTemp.c_str(), length);
848                         
849                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
850                         delete buf2;
851                 }
852                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
853                 
854                 for (int i = startIndex; i < endIndex; i++) {
855                         
856                         int start = time(NULL);
857                         int num = 0;
858                         string thisFastaName = filenames[i];
859                         map<string, int> thisPriority = fileToPriority[thisFastaName];
860                         
861                         char inFileName[1024];
862                         strcpy(inFileName, thisFastaName.c_str());
863                         MPI_File inMPI;
864                         MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
865                         
866                         MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
867                         
868                         cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl; 
869                         
870                         driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
871                         numSeqs += num;
872                         
873                         MPI_File_close(&inMPI);
874                         m->mothurRemove(thisFastaName);
875                                                 
876                         cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
877                 }
878                 
879                 if (pid == 0) {
880                         for(int i = 1; i < processors; i++) { 
881                                 int temp = 0;
882                                 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
883                                 numSeqs += temp;
884                         }
885                 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
886                 
887                 MPI_File_close(&outMPI);
888                 MPI_File_close(&outMPIAccnos); 
889                 if (trim) { MPI_File_close(&outMPIFasta); }
890                 
891                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
892 #endif
893                 return 0;
894                 
895         }catch(exception& e) {
896                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
897                 exit(1);
898         }
899 }               
900 //**********************************************************************************************************************
901 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
902         try {
903                 
904 #ifdef USE_MPI  
905                 int pid, numSeqsPerProcessor; 
906                 int tag = 2001;
907                 vector<unsigned long long> MPIPos;
908                 
909                 MPI_Status status; 
910                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
911                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
912                 
913                 MPI_File inMPI;
914                 MPI_File outMPI;
915                 MPI_File outMPIAccnos;
916                 MPI_File outMPIFasta;
917                 
918                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
919                 int inMode=MPI_MODE_RDONLY; 
920                 
921                 char outFilename[1024];
922                 strcpy(outFilename, outputFileName.c_str());
923                 
924                 char outAccnosFilename[1024];
925                 strcpy(outAccnosFilename, accnosFileName.c_str());
926                 
927                 char outFastaFilename[1024];
928                 strcpy(outFastaFilename, trimFastaFileName.c_str());
929                 
930                 char inFileName[1024];
931                 strcpy(inFileName, inputFile.c_str());
932                 
933                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
934                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
935                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
936                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
937                 
938                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  return 0;  }
939                 
940                 if (pid == 0) { //you are the root process 
941                         m->mothurOutEndLine();
942                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
943                         m->mothurOutEndLine();
944                         
945                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
946                         
947                         //print header
948                         int length = outTemp.length();
949                         char* buf2 = new char[length];
950                         memcpy(buf2, outTemp.c_str(), length);
951                         
952                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
953                         delete buf2;
954                         
955                         MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
956                         
957                         if (templatefile != "self") { //if template=self we can only use 1 processor
958                                 //send file positions to all processes
959                                 for(int i = 1; i < processors; i++) { 
960                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
961                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
962                                 }
963                         }
964                         //figure out how many sequences you have to align
965                         numSeqsPerProcessor = numSeqs / processors;
966                         int startIndex =  pid * numSeqsPerProcessor;
967                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
968                         
969                         if (templatefile == "self") { //if template=self we can only use 1 processor
970                                 startIndex = 0;
971                                 numSeqsPerProcessor = numSeqs;
972                         }
973                         
974                         //do your part
975                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
976                                                 
977                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);   return 0;  }
978                         
979                 }else{ //you are a child process
980                         if (templatefile != "self") { //if template=self we can only use 1 processor
981                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
982                                 MPIPos.resize(numSeqs+1);
983                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
984                                 
985                                 //figure out how many sequences you have to align
986                                 numSeqsPerProcessor = numSeqs / processors;
987                                 int startIndex =  pid * numSeqsPerProcessor;
988                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
989                                 
990                                 //do your part
991                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
992                                 
993                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  return 0;  }
994                                 
995                         }
996                 }
997                 
998                 //close files 
999                 MPI_File_close(&inMPI);
1000                 MPI_File_close(&outMPI);
1001                 MPI_File_close(&outMPIAccnos); 
1002                 if (trim) { MPI_File_close(&outMPIFasta); }
1003                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1004                 
1005                 
1006 #endif          
1007                 return numSeqs;
1008         }
1009         catch(exception& e) {
1010                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1011                 exit(1);
1012         }
1013 }
1014 //**********************************************************************************************************************
1015 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1016         try {
1017                 map<string, string>::iterator itUnique;
1018                 int total = 0;
1019         
1020         if (trimera) { //add in more potential uniqueNames
1021             map<string, string> newUniqueNames = uniqueNames;
1022             for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1023                 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1024                 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1025             }
1026             uniqueNames = newUniqueNames;
1027             newUniqueNames.clear();
1028         }
1029                 
1030                 //edit accnos file
1031                 ifstream in2; 
1032                 m->openInputFile(accnosFileName, in2, "no error");
1033                 
1034                 ofstream out2;
1035                 m->openOutputFile(accnosFileName+".temp", out2);
1036                 
1037                 string name; name = "";
1038                 set<string> chimerasInFile;
1039                 set<string>::iterator itChimeras;
1040                 
1041                 while (!in2.eof()) {
1042                         if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1043                         
1044                         in2 >> name; m->gobble(in2);
1045                         
1046                         //find unique name
1047                         itUnique = uniqueNames.find(name);
1048                         
1049                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1050                         else {
1051                                 itChimeras = chimerasInFile.find((itUnique->second));
1052                                 
1053                                 if (itChimeras == chimerasInFile.end()) {
1054                                         out2 << itUnique->second << endl;
1055                                         chimerasInFile.insert((itUnique->second));
1056                                         total++;
1057                                 }
1058                         }
1059                 }
1060                 in2.close();
1061                 out2.close();
1062                 
1063                 m->mothurRemove(accnosFileName);
1064                 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1065                 
1066                 
1067                 //edit chimera file
1068                 ifstream in; 
1069                 m->openInputFile(outputFileName, in);
1070                 
1071                 ofstream out;
1072                 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1073
1074                 string rest, parent1, parent2, line;
1075                 set<string> namesInFile; //this is so if a sequence is found to be chimera in several samples we dont write it to the results file more than once
1076                 set<string>::iterator itNames;
1077                 
1078                 //assumptions - in file each read will always look like...
1079                 /*
1080                  F11Fcsw_92754  no
1081                  F11Fcsw_63104  F11Fcsw_33372   F11Fcsw_37007   0.89441 80.4469 0.2     1.03727 93.2961 52.2    no      0-241   243-369 
1082                  */
1083                 
1084                 //get header line
1085                 if (!in.eof()) {
1086                         line = m->getline(in); m->gobble(in);
1087                         out << line << endl;
1088                 }
1089                 
1090                 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do, 
1091                 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file, 
1092                 //then ignore this report and continue until we find the report that found it to be chimeric
1093                 
1094                 while (!in.eof()) {
1095                         
1096                         if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1097                         
1098                         in >> name;             m->gobble(in);
1099                         in >> parent1;  m->gobble(in);
1100                         
1101                         if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1102                                 line = m->getline(in); m->gobble(in);
1103                         }else {
1104                                 if (parent1 == "no") {
1105                                         //find unique name
1106                                         itUnique = uniqueNames.find(name);
1107                                         
1108                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1109                                         else {
1110                                                 //is this sequence really not chimeric??
1111                                                 itChimeras = chimerasInFile.find(itUnique->second);
1112                                                 
1113                                                 if (itChimeras == chimerasInFile.end()) {
1114                                                         //is this sequence not already in the file
1115                                                         itNames = namesInFile.find((itUnique->second));
1116                                                         
1117                                                         if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1118                                                 }
1119                                         }
1120                                 }else { //read the rest of the line
1121                                         double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1122                                         string flag, range1, range2;
1123                                         bool print = false;
1124                                         in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2;  m->gobble(in);
1125                                         
1126                                         //find unique name
1127                                         itUnique = uniqueNames.find(name);
1128                                         
1129                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1130                                         else {
1131                                                 name = itUnique->second;
1132                                                 //is this name already in the file
1133                                                 itNames = namesInFile.find((name));
1134                                                 
1135                                                 if (itNames == namesInFile.end()) { //no not in file
1136                                                         if (flag == "no") { //are you really a no??
1137                                                                 //is this sequence really not chimeric??
1138                                                                 itChimeras = chimerasInFile.find(name);
1139                                                                 
1140                                                                 //then you really are a no so print, otherwise skip
1141                                                                 if (itChimeras == chimerasInFile.end()) { print = true; }
1142                                                                 
1143                                                         }else{ print = true; }
1144                                                 }
1145                                         }
1146                                         
1147                                         if (print) {
1148                                                 out << name << '\t';
1149                                                 
1150                                                 namesInFile.insert(name);
1151
1152                                                 //output parent1's name
1153                                                 itUnique = uniqueNames.find(parent1);
1154                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1155                                                 else { out << itUnique->second << '\t'; }
1156                                                 
1157                                                 //output parent2's name
1158                                                 itUnique = uniqueNames.find(parent2);
1159                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1160                                                 else { out << itUnique->second << '\t'; }
1161                                                 
1162                                                 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1163                                         }
1164                                 }                               
1165                         }
1166                 }
1167                 in.close();
1168                 out.close();
1169                 
1170                 m->mothurRemove(outputFileName);
1171                 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1172                 
1173                 //edit fasta file
1174                 if (trim) {
1175                         ifstream in3; 
1176                         m->openInputFile(trimFileName, in3);
1177                         
1178                         ofstream out3;
1179                         m->openOutputFile(trimFileName+".temp", out3);
1180                         
1181                         namesInFile.clear();
1182                         
1183                         while (!in3.eof()) {
1184                                 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1185                                 
1186                                 Sequence seq(in3); m->gobble(in3);
1187                                 
1188                                 if (seq.getName() != "") {
1189                                         //find unique name
1190                                         itUnique = uniqueNames.find(seq.getName());
1191                                         
1192                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1193                                         else {
1194                                                 itNames = namesInFile.find((itUnique->second));
1195                                                 
1196                                                 if (itNames == namesInFile.end()) {
1197                                                         seq.printSequence(out3);
1198                                                 }
1199                                         }
1200                                 }
1201                         }
1202                         in3.close();
1203                         out3.close();
1204                         
1205                         m->mothurRemove(trimFileName);
1206                         rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1207                 }
1208                 
1209                 return total;
1210         }
1211         catch(exception& e) {
1212                 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1213                 exit(1);
1214         }
1215 }
1216 //**********************************************************************************************************************
1217 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1218         try {
1219                 fileGroup.clear();
1220                 fileToPriority.clear();
1221                 
1222                 string nameFile = "";
1223                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1224                         nameFile = nameFileNames[s];
1225                 }else {  nameFile = getNamesFile(fastaFileNames[s]); }
1226                 
1227                 //you provided a groupfile
1228                 string groupFile = "";
1229                 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1230                 
1231                 if (groupFile == "") { 
1232                         if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1233                                                 
1234                         //sort fastafile by abundance, returns new sorted fastafile name
1235                         m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
1236                         priority = sortFastaFile(fastaFileNames[s], nameFile);
1237                         m->mothurOut("Done."); m->mothurOutEndLine();
1238                         
1239                         fileToPriority[fastaFileNames[s]] = priority;
1240                         fileGroup[fastaFileNames[s]] = "noGroup";
1241                 }else {
1242                         //Parse sequences by group
1243                         parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1244                         vector<string> groups = parser->getNamesOfGroups();
1245                         
1246                         for (int i = 0; i < groups.size(); i++) {
1247                                 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1248                                 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1249                                 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1250                                 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
1251                                 fileToPriority[newFastaFile] = priority;
1252                                 fileGroup[newFastaFile] = groups[i];
1253                         }
1254                 }
1255                 
1256                 
1257                 return 0;
1258         }
1259         catch(exception& e) {
1260                 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1261                 exit(1);
1262         }
1263 }
1264 //**********************************************************************************************************************
1265 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1266         try {
1267                 fileGroup.clear();
1268                 fileToPriority.clear();
1269                 
1270                 string nameFile = "";
1271                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1272                         nameFile = nameFileNames[s];
1273                 }else {  m->control_pressed = true; return 0; }
1274          
1275                 CountTable ct;
1276                 if (!ct.testGroups(nameFile)) {  
1277                         if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1278             
1279                         //sort fastafile by abundance, returns new sorted fastafile name
1280                         m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
1281                         priority = sortFastaFile(fastaFileNames[s], nameFile);
1282                         m->mothurOut("Done."); m->mothurOutEndLine();
1283                         
1284                         fileToPriority[fastaFileNames[s]] = priority;
1285                         fileGroup[fastaFileNames[s]] = "noGroup";
1286                 }else {
1287                         //Parse sequences by group
1288                         parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1289                         vector<string> groups = parser->getNamesOfGroups();
1290                         
1291                         for (int i = 0; i < groups.size(); i++) {
1292                                 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1293                                 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1294                                 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1295                                 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
1296                                 fileToPriority[newFastaFile] = thisGroupsMap;
1297                                 fileGroup[newFastaFile] = groups[i];
1298                         }
1299                 }
1300                 
1301                 
1302                 return 0;
1303         }
1304         catch(exception& e) {
1305                 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1306                 exit(1);
1307         }
1308 }
1309 //**********************************************************************************************************************
1310 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1311         try {
1312                 string nameFile = "";
1313                 
1314                 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1315                 
1316                 //use unique.seqs to create new name and fastafile
1317                 string inputString = "fasta=" + inputFile;
1318                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1319                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
1320                 m->mothurCalling = true;
1321         
1322                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1323                 uniqueCommand->execute();
1324                 
1325                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1326                 
1327                 delete uniqueCommand;
1328                 m->mothurCalling = false;
1329                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1330                 
1331                 nameFile = filenames["name"][0];
1332                 inputFile = filenames["fasta"][0];
1333                 
1334                 return nameFile;
1335         }
1336         catch(exception& e) {
1337                 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1338                 exit(1);
1339         }
1340 }
1341 //**********************************************************************************************************************
1342
1343 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1344         try {
1345                 int totalSeqs = 0;
1346                 
1347                 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1348                         
1349                         if (m->control_pressed) {  return 0;  }
1350                         
1351                         int start = time(NULL);
1352                         string thisFastaName = itFile->first;
1353                         map<string, int> thisPriority = itFile->second;
1354                         string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1355                         string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1356                         string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1357                         
1358                         m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine(); 
1359                         
1360                         lines.clear();
1361 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1362                         int proc = 1;
1363                         vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1364                         lines.push_back(linePair(positions[0], positions[1]));  
1365 #else
1366                         lines.push_back(linePair(0, 1000)); 
1367 #endif                  
1368                         int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1369                         
1370                         //append files
1371                         m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName); 
1372                         m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1373                         if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1374                         m->mothurRemove(thisFastaName);
1375                         
1376                         totalSeqs += numSeqs;
1377                         
1378                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + ".");     m->mothurOutEndLine();
1379                 }
1380                 
1381                 return totalSeqs;
1382         }
1383         catch(exception& e) {
1384                 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1385                 exit(1);
1386         }
1387 }
1388 /**************************************************************************************************/
1389 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1390         try {
1391                 int process = 1;
1392                 int num = 0;
1393                 processIDS.clear();
1394                 
1395                 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1396                 
1397                 int groupsPerProcessor = fileToPriority.size() / processors;
1398                 int remainder = fileToPriority.size() % processors;
1399                 
1400                 vector< map<string, map<string, int> > > breakUp;
1401                 
1402                 for (int i = 0; i < processors; i++) {
1403                         map<string, map<string, int> > thisFileToPriority;
1404                         map<string, map<string, int> >::iterator itFile;
1405                         int count = 0;
1406                         int enough = groupsPerProcessor;
1407                         if (i == 0) { enough = groupsPerProcessor + remainder; }
1408                         
1409                         for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1410                                 thisFileToPriority[itFile->first] = itFile->second;
1411                                 fileToPriority.erase(itFile++);
1412                                 count++;
1413                                 if (count == enough) { break; }
1414                         }       
1415                         breakUp.push_back(thisFileToPriority);
1416                 }
1417                                 
1418 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1419                 //loop through and create all the processes you want
1420                 while (process != processors) {
1421                         int pid = fork();
1422                         
1423                         if (pid > 0) {
1424                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1425                                 process++;
1426                         }else if (pid == 0){
1427                                 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1428                                 
1429                                 //pass numSeqs to parent
1430                                 ofstream out;
1431                                 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1432                                 m->openOutputFile(tempFile, out);
1433                                 out << num << endl;
1434                                 out.close();
1435                                 exit(0);
1436                         }else { 
1437                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1438                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1439                                 exit(0);
1440                         }
1441                 }
1442                 
1443                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1444
1445                 //force parent to wait until all the processes are done
1446                 for (int i=0;i<processors;i++) { 
1447                         int temp = processIDS[i];
1448                         wait(&temp);
1449                 }
1450                 
1451                 for (int i = 0; i < processIDS.size(); i++) {
1452                         ifstream in;
1453                         string tempFile =  outputFName + toString(processIDS[i]) + ".num.temp";
1454                         m->openInputFile(tempFile, in);
1455                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
1456                         in.close(); m->mothurRemove(tempFile);
1457                 }
1458 #else
1459                 
1460                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1461                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1462                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1463                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1464                 
1465                 vector<slayerData*> pDataArray; 
1466                 DWORD   dwThreadIdArray[processors-1];
1467                 HANDLE  hThreadArray[processors-1]; 
1468                 
1469                 //Create processor worker threads.
1470                 for(int i=1; i<processors; i++ ){
1471                         string extension = toString(i) + ".temp";
1472                         slayerData* tempslayer = new slayerData((outputFName + extension), (fasta + extension), (accnos + extension), templatefile, search, blastlocation, trimera, trim, realign, m, breakUp[i], fileGroup, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
1473                         pDataArray.push_back(tempslayer);
1474                         processIDS.push_back(i);
1475                         
1476                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1477                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1478                         hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
1479                 }
1480                 
1481                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1482                 
1483                 //Wait until all threads have terminated.
1484                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1485                 
1486                 //Close all thread handles and free memory allocations.
1487                 for(int i=0; i < pDataArray.size(); i++){
1488                         num += pDataArray[i]->count;
1489                         CloseHandle(hThreadArray[i]);
1490                         delete pDataArray[i];
1491                 }
1492 #endif  
1493                 
1494                 //append output files
1495                 for(int i=0;i<processIDS.size();i++){
1496                         m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1497                         m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1498                         
1499                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1500                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1501                         
1502                         if (trim) {
1503                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1504                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1505                         }
1506                 }
1507                 
1508                 
1509                 return num;
1510         }
1511         catch(exception& e) {
1512                 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1513                 exit(1);
1514         }
1515 }
1516 //**********************************************************************************************************************
1517
1518 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1519         try {
1520                 
1521                 Chimera* chimera;
1522                 if (templatefile != "self") { //you want to run slayer with a reference template
1523                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1524                 }else {
1525                         chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());     
1526                 }
1527                 
1528                 if (m->control_pressed) { delete chimera; return 0; }
1529                 
1530                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1531                 templateSeqsLength = chimera->getLength();
1532                 
1533                 ofstream out;
1534                 m->openOutputFile(outputFName, out);
1535                 
1536                 ofstream out2;
1537                 m->openOutputFile(accnos, out2);
1538                 
1539                 ofstream out3;
1540                 if (trim) {  m->openOutputFile(fasta, out3); }
1541                 
1542                 ifstream inFASTA;
1543                 m->openInputFile(filename, inFASTA);
1544
1545                 inFASTA.seekg(filePos.start);
1546                 
1547                 if (filePos.start == 0) { chimera->printHeader(out); }
1548
1549                 bool done = false;
1550                 int count = 0;
1551         
1552                 while (!done) {
1553                 
1554                         if (m->control_pressed) {       delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
1555                 
1556                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
1557                         string candidateAligned = candidateSeq->getAligned();
1558                         
1559                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1560                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1561                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1562                                 }else{
1563                                         //find chimeras
1564                                         chimera->getChimeras(candidateSeq);
1565                                         
1566                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1567                                                 
1568                                         //if you are not chimeric, then check each half
1569                                         data_results wholeResults = chimera->getResults();
1570                                         
1571                                         //determine if we need to split
1572                                         bool isChimeric = false;
1573                                         
1574                                         if (wholeResults.flag == "yes") {
1575                                                 string chimeraFlag = "no";
1576                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1577                                                    ||
1578                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1579                                                 
1580                                                 
1581                                                 if (chimeraFlag == "yes") {     
1582                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1583                                                 }
1584                                         }
1585                                         
1586                                         if ((!isChimeric) && trimera) {
1587                                                 
1588                                                 //split sequence in half by bases
1589                                                 string leftQuery, rightQuery;
1590                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1591                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1592                                                 
1593                                                 //run chimeraSlayer on each piece
1594                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1595                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1596                                                 
1597                                                 //find chimeras
1598                                                 chimera->getChimeras(left);
1599                                                 data_results leftResults = chimera->getResults();
1600                                                 
1601                                                 chimera->getChimeras(right);
1602                                                 data_results rightResults = chimera->getResults();
1603                                                 
1604                                                 //if either piece is chimeric then report
1605                                                 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1606                                                 if (trim) { trimmed.printSequence(out3);  }
1607                                                 
1608                                                 delete left; delete right;
1609                                                 
1610                                         }else { //already chimeric
1611                                                 //print results
1612                                                 Sequence trimmed = chimera->print(out, out2);
1613                                                 if (trim) { trimmed.printSequence(out3);  }
1614                                         }
1615                                         
1616                                         
1617                                 }
1618                                 count++;
1619                         }
1620                         
1621                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1622                                 unsigned long long pos = inFASTA.tellg();
1623                                 if ((pos == -1) || (pos >= filePos.end)) { break; }
1624                         #else
1625                                 if (inFASTA.eof()) { break; }
1626                         #endif
1627                         
1628                         delete candidateSeq;
1629                         //report progress
1630                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1631                 }
1632                 //report progress
1633                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1634                 
1635                 int numNoParents = chimera->getNumNoParents();
1636                 if (numNoParents == count) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); } 
1637                 
1638                 out.close();
1639                 out2.close();
1640                 if (trim) { out3.close(); }
1641                 inFASTA.close();
1642                 delete chimera;
1643                                 
1644                 return count;
1645                 
1646                 
1647         }
1648         catch(exception& e) {
1649                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1650                 exit(1);
1651         }
1652 }
1653 //**********************************************************************************************************************
1654 #ifdef USE_MPI
1655 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long long>& MPIPos, string filename, map<string, int>& priority, bool byGroup){
1656         try {
1657                 MPI_Status status; 
1658                 int pid;
1659                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1660                 
1661                 Chimera* chimera;
1662                 if (templatefile != "self") { //you want to run slayer with a reference template
1663                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1664                 }else {
1665                         chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand(), byGroup);    
1666                 }
1667                 
1668                 if (m->control_pressed) { delete chimera; return 0; }
1669                 
1670                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1671                 templateSeqsLength = chimera->getLength();
1672                 
1673                 for(int i=0;i<num;i++){
1674                         
1675                         if (m->control_pressed) {       delete chimera; return 1;       }
1676                         
1677                         //read next sequence
1678                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1679
1680                         char* buf4 = new char[length];
1681                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1682         
1683                         string tempBuf = buf4;
1684                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1685                         istringstream iss (tempBuf,istringstream::in);
1686
1687                         delete buf4;
1688
1689                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
1690                         string candidateAligned = candidateSeq->getAligned();
1691                 
1692                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1693                                 
1694                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1695                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1696                                 }else{
1697                 
1698                                         //find chimeras
1699                                         chimera->getChimeras(candidateSeq);
1700                         
1701                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1702                                         
1703                                         //if you are not chimeric, then check each half
1704                                         data_results wholeResults = chimera->getResults();
1705                                         
1706                                         //determine if we need to split
1707                                         bool isChimeric = false;
1708                                         
1709                                         if (wholeResults.flag == "yes") {
1710                                                 string chimeraFlag = "no";
1711                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1712                                                    ||
1713                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1714                                                 
1715                                                 
1716                                                 if (chimeraFlag == "yes") {     
1717                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1718                                                 }
1719                                         }
1720                                         
1721                                         if ((!isChimeric) && trimera) {                                                 
1722                                                 //split sequence in half by bases
1723                                                 string leftQuery, rightQuery;
1724                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1725                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1726                                                 
1727                                                 //run chimeraSlayer on each piece
1728                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1729                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1730                                                 
1731                                                 //find chimeras
1732                                                 chimera->getChimeras(left);
1733                                                 data_results leftResults = chimera->getResults();
1734                                                 
1735                                                 chimera->getChimeras(right);
1736                                                 data_results rightResults = chimera->getResults();
1737                                                 
1738                                                 //if either piece is chimeric then report
1739                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1740                                                 if (trim) {  
1741                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1742                                                         
1743                                                         //write to accnos file
1744                                                         int length = outputString.length();
1745                                                         char* buf2 = new char[length];
1746                                                         memcpy(buf2, outputString.c_str(), length);
1747                                                         
1748                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1749                                                         delete buf2;
1750                                                 }
1751                                                 
1752                                                 delete left; delete right;
1753                                                 
1754                                         }else { 
1755                                                 //print results
1756                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1757                                                 
1758                                                 if (trim) {  
1759                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1760                                                         
1761                                                         //write to accnos file
1762                                                         int length = outputString.length();
1763                                                         char* buf2 = new char[length];
1764                                                         memcpy(buf2, outputString.c_str(), length);
1765                                                         
1766                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1767                                                         delete buf2;
1768                                                 }
1769                                         }
1770                                         
1771                                 }
1772                         }
1773                         delete candidateSeq;
1774                         
1775                         //report progress
1776                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
1777                 }
1778                 //report progress
1779                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
1780                 
1781                 int numNoParents = chimera->getNumNoParents();
1782                 if (numNoParents == num) { cout << "[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors." << endl; }
1783                 
1784                 delete chimera;         
1785                 return 0;
1786         }
1787         catch(exception& e) {
1788                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1789                 exit(1);
1790         }
1791 }
1792 #endif
1793
1794 /**************************************************************************************************/
1795
1796 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1797         try {
1798                 int process = 0;
1799                 int num = 0;
1800                 processIDS.clear();
1801                 
1802 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1803                 //loop through and create all the processes you want
1804                 while (process != processors) {
1805                         int pid = fork();
1806                         
1807                         if (pid > 0) {
1808                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1809                                 process++;
1810                         }else if (pid == 0){
1811                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1812                                 
1813                                 //pass numSeqs to parent
1814                                 ofstream out;
1815                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1816                                 m->openOutputFile(tempFile, out);
1817                                 out << num << endl;
1818                                 out.close();
1819                                 exit(0);
1820                         }else { 
1821                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1822                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1823                                 exit(0);
1824                         }
1825                 }
1826                 
1827                 //force parent to wait until all the processes are done
1828                 for (int i=0;i<processors;i++) { 
1829                         int temp = processIDS[i];
1830                         wait(&temp);
1831                 }
1832                 
1833                 for (int i = 0; i < processIDS.size(); i++) {
1834                         ifstream in;
1835                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
1836                         m->openInputFile(tempFile, in);
1837                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
1838                         in.close(); m->mothurRemove(tempFile);
1839                 }
1840 #else
1841                 
1842                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1843                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1844                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1845                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1846                 
1847                 vector<slayerData*> pDataArray; 
1848                 DWORD   dwThreadIdArray[processors];
1849                 HANDLE  hThreadArray[processors]; 
1850                 
1851                 //Create processor worker threads.
1852                 for( int i=0; i<processors; i++ ){
1853                         string extension = toString(i) + ".temp";
1854                         slayerData* tempslayer = new slayerData((outputFileName + extension), (fasta + extension), (accnos + extension), filename, templatefile, search, blastlocation, trimera, trim, realign, m, lines[i].start, lines[i].end, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
1855                         pDataArray.push_back(tempslayer);
1856                         processIDS.push_back(i);
1857                         
1858                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1859                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1860                         hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
1861                 }
1862                                 
1863                 //Wait until all threads have terminated.
1864                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1865                 
1866                 //Close all thread handles and free memory allocations.
1867                 for(int i=0; i < pDataArray.size(); i++){
1868                         num += pDataArray[i]->count;
1869                         CloseHandle(hThreadArray[i]);
1870                         delete pDataArray[i];
1871                 }
1872 #endif  
1873                 
1874                 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1875                 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1876                 if (trim) {  rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1877                 
1878                 //append output files
1879                 for(int i=1;i<processIDS.size();i++){
1880                         m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1881                         m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1882                         
1883                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1884                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1885                         
1886                         if (trim) {
1887                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1888                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1889                         }
1890                 }
1891                 
1892                 
1893                 return num;
1894         }
1895         catch(exception& e) {
1896                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1897                 exit(1);
1898         }
1899 }
1900
1901 /**************************************************************************************************/
1902
1903 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1904         try {
1905                 
1906                 string queryUnAligned = querySeq.getUnaligned();
1907                 int numBases = int(queryUnAligned.length() * 0.5);
1908                 
1909                 string queryAligned = querySeq.getAligned();
1910                 leftQuery = querySeq.getAligned();
1911                 rightQuery = querySeq.getAligned();
1912                 
1913                 int baseCount = 0;
1914                 int leftSpot = 0;
1915                 for (int i = 0; i < queryAligned.length(); i++) {
1916                         //if you are a base
1917                         if (isalpha(queryAligned[i])) {         
1918                                 baseCount++; 
1919                         }
1920                         
1921                         //if you have half
1922                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
1923                 }
1924                 
1925                 //blank out right side
1926                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1927                 
1928                 //blank out left side
1929                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1930                 
1931                 return 0;
1932                 
1933         }
1934         catch(exception& e) {
1935                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1936                 exit(1);
1937         }
1938 }
1939 /**************************************************************************************************/
1940 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1941         try {
1942                 map<string, int> nameAbund;
1943                 
1944                 //read through fastafile and store info
1945                 map<string, string> seqs;
1946                 ifstream in;
1947                 m->openInputFile(fastaFile, in);
1948                 
1949                 while (!in.eof()) {
1950                         
1951                         if (m->control_pressed) { in.close(); return nameAbund; }
1952                         
1953                         Sequence seq(in); m->gobble(in);
1954                         seqs[seq.getName()] = seq.getAligned();
1955                 }
1956                 
1957                 in.close();
1958                 
1959                 //read namefile or countfile
1960                 vector<seqPriorityNode> nameMapCount;
1961         int error;
1962         if (hasCount) { 
1963             CountTable ct;
1964             ct.readTable(nameFile);
1965             
1966             for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
1967                 int num = ct.getNumSeqs(it->first);
1968                 if (num == 0) { error = 1; }
1969                 else {
1970                     seqPriorityNode temp(num, it->second, it->first);
1971                     nameMapCount.push_back(temp);
1972                 }
1973             }
1974         }else { error = m->readNames(nameFile, nameMapCount, seqs); }
1975                 
1976                 if (m->control_pressed) { return nameAbund; }
1977                 
1978                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1979                 if (seqs.size() != nameMapCount.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
1980
1981                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1982                 
1983                 string newFasta = fastaFile + ".temp";
1984                 ofstream out;
1985                 m->openOutputFile(newFasta, out);
1986                 
1987                 //print new file in order of
1988                 for (int i = 0; i < nameMapCount.size(); i++) {
1989                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1990                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1991                 }
1992                 out.close();
1993                 
1994                 rename(newFasta.c_str(), fastaFile.c_str());
1995                                 
1996                 return nameAbund;
1997                 
1998         }
1999         catch(exception& e) {
2000                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2001                 exit(1);
2002         }
2003 }
2004 /**************************************************************************************************/
2005 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2006         try {
2007                 map<string, int> nameAbund;
2008                 vector<seqPriorityNode> nameVector;
2009                 
2010                 //read through fastafile and store info
2011                 map<string, string> seqs;
2012                                 
2013                 for (int i = 0; i < thisseqs.size(); i++) {
2014                         
2015                         if (m->control_pressed) { return nameAbund; }
2016                         
2017                         map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2018                         
2019                         if (itNameMap == nameMap.end()){
2020                                 m->control_pressed = true;
2021                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2022                         }else {
2023                                 int num = m->getNumNames(itNameMap->second);
2024                                 
2025                                 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2026                                 nameVector.push_back(temp);
2027                         }
2028                 }
2029         
2030                 //sort by num represented
2031                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2032         
2033                 if (m->control_pressed) { return nameAbund; }
2034                 
2035                 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
2036                                 
2037                 ofstream out;
2038                 m->openOutputFile(newFile, out);
2039                 
2040                 //print new file in order of
2041                 for (int i = 0; i < nameVector.size(); i++) {
2042                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2043                         nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2044                 }
2045                 out.close();
2046                 
2047                 return nameAbund;
2048                 
2049         }
2050         catch(exception& e) {
2051                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2052                 exit(1);
2053         }
2054 }
2055 /**************************************************************************************************/
2056 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2057         try {
2058                 vector<seqPriorityNode> nameVector;
2059                 
2060                 //read through fastafile and store info
2061                 map<string, string> seqs;
2062         
2063                 for (int i = 0; i < thisseqs.size(); i++) {
2064                         
2065                         if (m->control_pressed) { return 0; }
2066                         
2067                         map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2068                         
2069                         if (itCountMap == countMap.end()){
2070                                 m->control_pressed = true;
2071                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2072                         }else {
2073                 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2074                                 nameVector.push_back(temp);
2075                         }
2076                 }
2077         
2078                 //sort by num represented
2079                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2080         
2081                 if (m->control_pressed) { return 0; }
2082                 
2083                 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your count file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
2084         
2085                 ofstream out;
2086                 m->openOutputFile(newFile, out);
2087                 
2088                 //print new file in order of
2089                 for (int i = 0; i < nameVector.size(); i++) {
2090                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2091                 }
2092                 out.close();
2093                 
2094                 return 0;
2095                 
2096         }
2097         catch(exception& e) {
2098                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2099                 exit(1);
2100         }
2101 }
2102 /**************************************************************************************************/
2103