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