]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
f15581f271382f671505dc708a9ffa2545e32eeb
[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 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
102         try {
103                 abort = true; calledHelp = true;
104                 setParameters();
105                 vector<string> tempOutNames;
106                 outputTypes["chimera"] = tempOutNames;
107                 outputTypes["accnos"] = tempOutNames;
108                 outputTypes["fasta"] = tempOutNames;
109         }
110         catch(exception& e) {
111                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
112                 exit(1);
113         }
114 }
115 //***************************************************************************************************************
116 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
117         try {
118                 abort = false; calledHelp = false;   
119                 ReferenceDB* rdb = ReferenceDB::getInstance();
120                 
121                 //allow user to run help
122                 if(option == "help") { help(); abort = true; calledHelp = true; }
123                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
124                 
125                 else {
126                         vector<string> myArray = setParameters();
127                         
128                         OptionParser parser(option);
129                         map<string,string> parameters = parser.getParameters();
130                         
131                         ValidParameters validParameter("chimera.slayer");
132                         map<string,string>::iterator it;
133                         
134                         //check to make sure all parameters are valid for command
135                         for (it = parameters.begin(); it != parameters.end(); it++) { 
136                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
137                         }
138                         
139                         vector<string> tempOutNames;
140                         outputTypes["chimera"] = tempOutNames;
141                         outputTypes["accnos"] = tempOutNames;
142                         outputTypes["fasta"] = tempOutNames;
143                 
144                         //if the user changes the input directory command factory will send this info to us in the output parameter 
145                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
146                         if (inputDir == "not found"){   inputDir = "";          }
147                                                 
148                         //check for required parameters
149                         fastafile = validParameter.validFile(parameters, "fasta", false);
150                         if (fastafile == "not found") {                                 
151                                 //if there is a current fasta file, use it
152                                 string filename = m->getFastaFile(); 
153                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
154                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
155                         }else { 
156                                 m->splitAtDash(fastafile, fastaFileNames);
157                                 
158                                 //go through files and make sure they are good, if not, then disregard them
159                                 for (int i = 0; i < fastaFileNames.size(); i++) {
160                                         
161                                         bool ignore = false;
162                                         if (fastaFileNames[i] == "current") { 
163                                                 fastaFileNames[i] = m->getFastaFile(); 
164                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
165                                                 else {  
166                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
167                                                         //erase from file list
168                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
169                                                         i--;
170                                                 }
171                                         }
172                                         
173                                         if (!ignore) {
174                                                 
175                                                 if (inputDir != "") {
176                                                         string path = m->hasPath(fastaFileNames[i]);
177                                                         //if the user has not given a path then, add inputdir. else leave path alone.
178                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
179                                                 }
180                 
181                                                 int ableToOpen;
182                                                 ifstream in;
183                                                 
184                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
185                                         
186                                                 //if you can't open it, try default location
187                                                 if (ableToOpen == 1) {
188                                                         if (m->getDefaultPath() != "") { //default path is set
189                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
190                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
191                                                                 ifstream in2;
192                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
193                                                                 in2.close();
194                                                                 fastaFileNames[i] = tryPath;
195                                                         }
196                                                 }
197                                                 
198                                                 if (ableToOpen == 1) {
199                                                         if (m->getOutputDir() != "") { //default path is set
200                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
201                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
202                                                                 ifstream in2;
203                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
204                                                                 in2.close();
205                                                                 fastaFileNames[i] = tryPath;
206                                                         }
207                                                 }
208                                                 
209                                                 in.close();
210                                                 
211                                                 if (ableToOpen == 1) { 
212                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
213                                                         //erase from file list
214                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
215                                                         i--;
216                                                 }else {
217                                                         m->setFastaFile(fastaFileNames[i]);
218                                                 }
219                                         }
220                                 }
221                                 
222                                 //make sure there is at least one valid file left
223                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
224                         }
225                         
226                         
227                         //check for required parameters
228                         bool hasName = true;
229                         namefile = validParameter.validFile(parameters, "name", false);
230                         if (namefile == "not found") { namefile = "";  hasName = false; }
231                         else { 
232                                 m->splitAtDash(namefile, nameFileNames);
233                                 
234                                 //go through files and make sure they are good, if not, then disregard them
235                                 for (int i = 0; i < nameFileNames.size(); i++) {
236                                         
237                                         bool ignore = false;
238                                         if (nameFileNames[i] == "current") { 
239                                                 nameFileNames[i] = m->getNameFile(); 
240                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
241                                                 else {  
242                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
243                                                         //erase from file list
244                                                         nameFileNames.erase(nameFileNames.begin()+i);
245                                                         i--;
246                                                 }
247                                         }
248                                         
249                                         if (!ignore) {
250                                                 
251                                                 if (inputDir != "") {
252                                                         string path = m->hasPath(nameFileNames[i]);
253                                                         //if the user has not given a path then, add inputdir. else leave path alone.
254                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
255                                                 }
256                                                 
257                                                 int ableToOpen;
258                                                 ifstream in;
259                                                 
260                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
261                                                 
262                                                 //if you can't open it, try default location
263                                                 if (ableToOpen == 1) {
264                                                         if (m->getDefaultPath() != "") { //default path is set
265                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
266                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
267                                                                 ifstream in2;
268                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
269                                                                 in2.close();
270                                                                 nameFileNames[i] = tryPath;
271                                                         }
272                                                 }
273                                                 
274                                                 if (ableToOpen == 1) {
275                                                         if (m->getOutputDir() != "") { //default path is set
276                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
277                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
278                                                                 ifstream in2;
279                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
280                                                                 in2.close();
281                                                                 nameFileNames[i] = tryPath;
282                                                         }
283                                                 }
284                                                 
285                                                 in.close();
286                                                 
287                                                 if (ableToOpen == 1) { 
288                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
289                                                         //erase from file list
290                                                         nameFileNames.erase(nameFileNames.begin()+i);
291                                                         i--;
292                                                 }else {
293                                                         m->setNameFile(nameFileNames[i]);
294                                                 }
295                                         }
296                                 }
297                                 
298                                 //make sure there is at least one valid file left
299                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
300                         }
301                         
302                         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; }
303                         
304                         bool hasGroup = true;
305                         groupfile = validParameter.validFile(parameters, "group", false);
306                         if (groupfile == "not found") { groupfile = "";  hasGroup = false; }
307                         else { 
308                                 m->splitAtDash(groupfile, groupFileNames);
309                                 
310                                 //go through files and make sure they are good, if not, then disregard them
311                                 for (int i = 0; i < groupFileNames.size(); i++) {
312                                         
313                                         bool ignore = false;
314                                         if (groupFileNames[i] == "current") { 
315                                                 groupFileNames[i] = m->getGroupFile(); 
316                                                 if (groupFileNames[i] != "") {  m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
317                                                 else {  
318                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
319                                                         //erase from file list
320                                                         groupFileNames.erase(groupFileNames.begin()+i);
321                                                         i--;
322                                                 }
323                                         }
324                                         
325                                         if (!ignore) {
326                                                 
327                                                 if (inputDir != "") {
328                                                         string path = m->hasPath(groupFileNames[i]);
329                                                         //if the user has not given a path then, add inputdir. else leave path alone.
330                                                         if (path == "") {       groupFileNames[i] = inputDir + groupFileNames[i];               }
331                                                 }
332                                                 
333                                                 int ableToOpen;
334                                                 ifstream in;
335                                                 
336                                                 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
337                                                 
338                                                 //if you can't open it, try default location
339                                                 if (ableToOpen == 1) {
340                                                         if (m->getDefaultPath() != "") { //default path is set
341                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
342                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
343                                                                 ifstream in2;
344                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
345                                                                 in2.close();
346                                                                 groupFileNames[i] = tryPath;
347                                                         }
348                                                 }
349                                                 
350                                                 if (ableToOpen == 1) {
351                                                         if (m->getOutputDir() != "") { //default path is set
352                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
353                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
354                                                                 ifstream in2;
355                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
356                                                                 in2.close();
357                                                                 groupFileNames[i] = tryPath;
358                                                         }
359                                                 }
360                                                 
361                                                 in.close();
362                                                 
363                                                 if (ableToOpen == 1) { 
364                                                         m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
365                                                         //erase from file list
366                                                         groupFileNames.erase(groupFileNames.begin()+i);
367                                                         i--;
368                                                 }else {
369                                                         m->setGroupFile(groupFileNames[i]);
370                                                 }
371                                         }
372                                 }
373                                 
374                                 //make sure there is at least one valid file left
375                                 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
376                         }
377                         
378                         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; }
379                         
380                         
381                         //if the user changes the output directory command factory will send this info to us in the output parameter 
382                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
383                         
384                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
385                         m->setProcessors(temp);
386                         convert(temp, processors);
387                         
388                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
389                         save = m->isTrue(temp); 
390                         rdb->save = save; 
391                         if (save) { //clear out old references
392                                 rdb->clearMemory();     
393                         }
394                         
395                         string path;
396                         it = parameters.find("reference");
397                         //user has given a template file
398                         if(it != parameters.end()){ 
399                                 if (it->second == "self") { 
400                                         templatefile = "self"; 
401                                         if (save) {
402                                                 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
403                                                 m->mothurOutEndLine();
404                                                 save = false;
405                                         }
406                                 }
407                                 else {
408                                         path = m->hasPath(it->second);
409                                         //if the user has not given a path then, add inputdir. else leave path alone.
410                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
411                                         
412                                         templatefile = validParameter.validFile(parameters, "reference", true);
413                                         if (templatefile == "not open") { abort = true; }
414                                         else if (templatefile == "not found") { //check for saved reference sequences
415                                                 if (rdb->referenceSeqs.size() != 0) {
416                                                         templatefile = "saved";
417                                                 }else {
418                                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
419                                                         m->mothurOutEndLine();
420                                                         abort = true; 
421                                                 }
422                                         }else { if (save) {     rdb->setSavedReference(templatefile);   }       }       
423                                 }
424                         }else if (hasName) {  templatefile = "self"; 
425                                 if (save) {
426                                         m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
427                                         m->mothurOutEndLine();
428                                         save = false;
429                                 }
430                         }
431                         else { 
432                                 if (rdb->referenceSeqs.size() != 0) {
433                                         templatefile = "saved";
434                                 }else {
435                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
436                                         m->mothurOutEndLine();
437                                         templatefile = ""; abort = true; 
438                                 } 
439                         }
440                         
441                         
442                         
443                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
444                         convert(temp, ksize);
445                                                 
446                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
447                         convert(temp, window);
448                         
449                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
450                         convert(temp, match);
451                         
452                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
453                         convert(temp, mismatch);
454                         
455                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
456                         convert(temp, divR);
457                         
458                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
459                         convert(temp, minSimilarity);
460                         
461                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
462                         convert(temp, minCoverage);
463                         
464                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
465                         convert(temp, minBS);
466                         
467                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "10"; }
468                         convert(temp, minSNP);
469
470                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
471                         convert(temp, parents); 
472                         
473                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "t"; }
474                         realign = m->isTrue(temp); 
475                         
476                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
477                         trim = m->isTrue(temp); 
478                         
479                         temp = validParameter.validFile(parameters, "split", false);                    if (temp == "not found") { temp = "f"; }
480                         trimera = m->isTrue(temp); 
481                         
482                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "blast"; }
483                         
484                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "1000"; }             
485                         convert(temp, iters); 
486                          
487                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
488                         convert(temp, increment);
489                         
490                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
491                         convert(temp, numwanted);
492                         
493                         blastlocation = validParameter.validFile(parameters, "blastlocation", false);   
494                         if (blastlocation == "not found") { blastlocation = ""; }
495                         else {
496                                 //add / to name if needed
497                                 string lastChar = blastlocation.substr(blastlocation.length()-1);
498 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
499                                 if (lastChar != "/") { blastlocation += "/"; }
500 #else
501                                 if (lastChar != "\\") { blastlocation += "\\"; }        
502 #endif
503                                 blastlocation = m->getFullPathName(blastlocation);
504                                 string formatdbCommand = "";
505 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
506                                 formatdbCommand = blastlocation + "formatdb";   
507 #else
508                                 formatdbCommand = blastlocation + "formatdb.exe";
509 #endif
510                                 
511                                 //test to make sure formatdb exists
512                                 ifstream in;
513                                 formatdbCommand = m->getFullPathName(formatdbCommand);
514                                 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
515                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
516                                 
517                                 string blastCommand = "";
518 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
519                                 blastCommand = blastlocation + "megablast";     
520 #else
521                                 blastCommand = blastlocation + "megablast.exe";
522 #endif
523                                 //test to make sure formatdb exists
524                                 ifstream in2;
525                                 blastCommand = m->getFullPathName(blastCommand);
526                                 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
527                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
528                         }
529
530                         if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
531                         
532                         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; }
533                         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; }
534
535                         //until we resolve the issue 10-18-11
536 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
537 #else
538                         processors=1;
539 #endif
540                 }
541         }
542         catch(exception& e) {
543                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
544                 exit(1);
545         }
546 }
547 //***************************************************************************************************************
548
549 int ChimeraSlayerCommand::execute(){
550         try{
551                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
552                         
553                 for (int s = 0; s < fastaFileNames.size(); s++) {
554                                 
555                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
556                 
557                         int start = time(NULL); 
558                         
559                         //you provided a groupfile
560                         string groupFile = "";
561                         if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
562                         
563                         //maps a filename to priority map. 
564                         //if no groupfile this is fastafileNames[s] -> prioirity
565                         //if groupfile then this is each groups seqs -> priority
566                         map<string, map<string, int> > fileToPriority; 
567                         map<string, map<string, int> >::iterator itFile;
568                         map<string, string> fileGroup;
569                         fileToPriority[fastaFileNames[s]] = priority; //default
570                         fileGroup[fastaFileNames[s]] = "noGroup";
571                         SequenceParser* parser = NULL;
572                         int totalSeqs = 0;
573                         int totalChimeras = 0;
574                         
575                         if ((templatefile == "self") && (groupFile == "")) { 
576                                 fileGroup.clear();
577                                 fileToPriority.clear();
578                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
579                                 string nameFile = "";
580                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
581                                         nameFile = nameFileNames[s];
582                                 }else {  nameFile = getNamesFile(fastaFileNames[s]); }
583                                 
584                                 //sort fastafile by abundance, returns new sorted fastafile name
585                                 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
586                                 priority = sortFastaFile(fastaFileNames[s], nameFile);
587                                 m->mothurOut("Done."); m->mothurOutEndLine();
588                                 
589                                 fileToPriority.clear();
590                                 fileGroup.clear();
591                                 fileToPriority[fastaFileNames[s]] = priority;
592                                 fileGroup[fastaFileNames[s]] = "noGroup";
593                                 if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       m->mothurRemove(outputNames[j]);        }  return 0;    }
594                         }else if ((templatefile == "self") && (groupFile != "")) {
595                                 fileGroup.clear();
596                                 fileToPriority.clear();
597                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
598                                 string nameFile = "";
599                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
600                                         nameFile = nameFileNames[s];
601                                 }else { nameFile = getNamesFile(fastaFileNames[s]); }
602                                 
603                                 //Parse sequences by group
604                                 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
605                                 vector<string> groups = parser->getNamesOfGroups();
606                                 
607                                 for (int i = 0; i < groups.size(); i++) {
608                                         vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
609                                         map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
610                                         string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
611                                         priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
612                                         fileToPriority[newFastaFile] = priority;
613                                         fileGroup[newFastaFile] = groups[i];
614                                 }
615                         }
616                         
617                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
618                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
619                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
620                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";
621                         
622                         //clears files
623                         ofstream out, out1, out2;
624                         m->openOutputFile(outputFileName, out); out.close(); 
625                         m->openOutputFile(accnosFileName, out1); out1.close();
626                         if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
627                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
628                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
629                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
630                         
631                         
632                         for (itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
633                                 
634                                 string thisFastaName = itFile->first;
635                                 map<string, int> thisPriority = itFile->second;
636                                 
637                                 //this is true when you have parsed by groups
638                                 if (fileToPriority.size() > 1) { m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();  }
639                                 
640                                 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
641                                 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
642                                 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
643                                 
644                                 //create chimera here if you are mac or linux because fork will copy for you. Create in create processes instead if you are windows.
645                                 if (processors == 1) { templateSeqsLength = setupChimera(thisFastaName, thisPriority); }
646                                 else {
647                                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || USE_MPI
648                                                 templateSeqsLength = setupChimera(thisFastaName, thisPriority);
649                                         #endif
650                                 }
651                                 
652                                 if (m->control_pressed) {  if (parser != NULL) { delete parser; } for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        }  return 0;    }
653                                 
654                         #ifdef USE_MPI  
655                                 MPIExecute(thisFastaName, thisoutputFileName, thisaccnosFileName, thistrimFastaFileName);
656                                 if (m->control_pressed) { outputTypes.clear();  for (int j = 0; j < outputNames.size(); j++) {  m->mothurRemove(outputNames[j]);        }  return 0;  }
657                         #else
658                                         //break up file
659                                         vector<unsigned long long> positions; 
660                                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
661                                         positions = m->divideFile(thisFastaName, processors);
662                                         for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(new linePair(positions[i], positions[(i+1)]));  }
663                                 #else
664                                         if (processors == 1) {  lines.push_back(new linePair(0, 1000)); }
665                                         else {
666                                                 positions = m->setFilePosFasta(thisFastaName, numSeqs); 
667                                         
668                                                 //figure out how many sequences you have to process
669                                                 int numSeqsPerProcessor = numSeqs / processors;
670                                                 for (int i = 0; i < processors; i++) {
671                                                         int startIndex =  i * numSeqsPerProcessor;
672                                                         if(i == (processors - 1)){      numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor;        }
673                                                         lines.push_back(new linePair(positions[startIndex], numSeqsPerProcessor));
674                                                 }
675                                         }
676                                 #endif
677                                 
678                                 if(processors == 1){
679                                         numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName);
680                                         
681                                         int numNoParents = chimera->getNumNoParents();
682                                         if (numNoParents == numSeqs) { 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(); }
683                                         
684                                 }else{ numSeqs = createProcesses(thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName); }
685                                 
686                                 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]);        } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
687                                 
688                         #endif
689                                 
690                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || USE_MPI
691                                 delete chimera;
692                         #endif
693                                 
694                                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
695                                 
696                                 //append files
697                                 m->appendFiles(thisoutputFileName, outputFileName); m->mothurRemove(thisoutputFileName); 
698                                 totalChimeras = m->appendFiles(thisaccnosFileName, accnosFileName); m->mothurRemove(thisaccnosFileName);
699                                 if (trim) { m->appendFiles(thistrimFastaFileName, trimFastaFileName); m->mothurRemove(thistrimFastaFileName); }
700                                 
701                                 totalSeqs += numSeqs;
702                         }
703                         
704                         if (fileToPriority.size() > 1) { totalChimeras = deconvoluteResults(parser, outputFileName, accnosFileName, trimFastaFileName); }
705                         
706                         if (parser != NULL) { delete parser; } 
707                         
708                         m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(totalSeqs) + " sequences.");     m->mothurOutEndLine();
709                 }
710                 
711                 //set accnos file as new current accnosfile
712                 string current = "";
713                 itTypes = outputTypes.find("accnos");
714                 if (itTypes != outputTypes.end()) {
715                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
716                 }
717                 
718                 if (trim) {
719                         itTypes = outputTypes.find("fasta");
720                         if (itTypes != outputTypes.end()) {
721                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
722                         }
723                 }
724                 
725                 m->mothurOutEndLine();
726                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
727                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
728                 m->mothurOutEndLine();
729
730                 return 0;
731                 
732         }
733         catch(exception& e) {
734                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
735                 exit(1);
736         }
737 }
738 //**********************************************************************************************************************
739 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName){
740         try {
741                 
742 #ifdef USE_MPI  
743                 int pid, numSeqsPerProcessor; 
744                 int tag = 2001;
745                 vector<unsigned long long> MPIPos;
746                 
747                 MPI_Status status; 
748                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
749                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
750                 
751                 MPI_File inMPI;
752                 MPI_File outMPI;
753                 MPI_File outMPIAccnos;
754                 MPI_File outMPIFasta;
755                 
756                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
757                 int inMode=MPI_MODE_RDONLY; 
758                 
759                 char outFilename[1024];
760                 strcpy(outFilename, outputFileName.c_str());
761                 
762                 char outAccnosFilename[1024];
763                 strcpy(outAccnosFilename, accnosFileName.c_str());
764                 
765                 char outFastaFilename[1024];
766                 strcpy(outFastaFilename, trimFastaFileName.c_str());
767                 
768                 char inFileName[1024];
769                 strcpy(inFileName, inputFile.c_str());
770                 
771                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
772                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
773                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
774                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
775                 
776                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  delete chimera; return 0;  }
777                 
778                 if (pid == 0) { //you are the root process 
779                         m->mothurOutEndLine();
780                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
781                         m->mothurOutEndLine();
782                         
783                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
784                         
785                         //print header
786                         int length = outTemp.length();
787                         char* buf2 = new char[length];
788                         memcpy(buf2, outTemp.c_str(), length);
789                         
790                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
791                         delete buf2;
792                         
793                         MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
794                         
795                         if (templatefile != "self") { //if template=self we can only use 1 processor
796                                 //send file positions to all processes
797                                 for(int i = 1; i < processors; i++) { 
798                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
799                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
800                                 }
801                         }
802                         //figure out how many sequences you have to align
803                         numSeqsPerProcessor = numSeqs / processors;
804                         int startIndex =  pid * numSeqsPerProcessor;
805                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
806                         
807                         if (templatefile == "self") { //if template=self we can only use 1 processor
808                                 startIndex = 0;
809                                 numSeqsPerProcessor = numSeqs;
810                         }
811                         
812                         //do your part
813                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
814                         
815                         int numNoParents = chimera->getNumNoParents();
816                         int temp;
817                         for(int i = 1; i < processors; i++) { 
818                                 MPI_Recv(&temp, 1, MPI_INT, 1, tag, MPI_COMM_WORLD, &status);
819                                 numNoParents += temp;
820                         }
821                         
822                         
823                         if (numSeqs == numNoParents) {  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(); }
824                         
825                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  delete chimera; return 0;  }
826                         
827                 }else{ //you are a child process
828                         if (templatefile != "self") { //if template=self we can only use 1 processor
829                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
830                                 MPIPos.resize(numSeqs+1);
831                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
832                                 
833                                 //figure out how many sequences you have to align
834                                 numSeqsPerProcessor = numSeqs / processors;
835                                 int startIndex =  pid * numSeqsPerProcessor;
836                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
837                                 
838                                 //do your part
839                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
840                                 
841                                 int numNoParents = chimera->getNumNoParents();
842                                 MPI_Send(&numNoParents, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
843                                 
844                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  delete chimera; return 0;  }
845                                 
846                         }
847                 }
848                 
849                 //close files 
850                 MPI_File_close(&inMPI);
851                 MPI_File_close(&outMPI);
852                 MPI_File_close(&outMPIAccnos); 
853                 if (trim) { MPI_File_close(&outMPIFasta); }
854                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
855                 
856                 
857 #endif          
858                 return 0;
859         }
860         catch(exception& e) {
861                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
862                 exit(1);
863         }
864 }
865 //**********************************************************************************************************************
866 int ChimeraSlayerCommand::deconvoluteResults(SequenceParser* parser, string outputFileName, string accnosFileName, string trimFileName){
867         try {
868                 map<string, string> uniqueNames = parser->getAllSeqsMap();
869                 map<string, string>::iterator itUnique;
870                 int total = 0;
871                 
872                 //edit accnos file
873                 ifstream in2; 
874                 m->openInputFile(accnosFileName, in2, "no error");
875                 
876                 ofstream out2;
877                 m->openOutputFile(accnosFileName+".temp", out2);
878                 
879                 string name; name = "";
880                 set<string> chimerasInFile;
881                 set<string>::iterator itChimeras;
882                 
883                 while (!in2.eof()) {
884                         if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
885                         
886                         in2 >> name; m->gobble(in2);
887                         
888                         //find unique name
889                         itUnique = uniqueNames.find(name);
890                         
891                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
892                         else {
893                                 itChimeras = chimerasInFile.find((itUnique->second));
894                                 
895                                 if (itChimeras == chimerasInFile.end()) {
896                                         out2 << itUnique->second << endl;
897                                         chimerasInFile.insert((itUnique->second));
898                                         total++;
899                                 }
900                         }
901                 }
902                 in2.close();
903                 out2.close();
904                 
905                 m->mothurRemove(accnosFileName);
906                 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
907                 
908                 
909                 //edit chimera file
910                 ifstream in; 
911                 m->openInputFile(outputFileName, in);
912                 
913                 ofstream out;
914                 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
915
916                 string rest, parent1, parent2, line;
917                 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
918                 set<string>::iterator itNames;
919                 
920                 //assumptions - in file each read will always look like...
921                 /*
922                  F11Fcsw_92754  no
923                  F11Fcsw_63104  F11Fcsw_33372   F11Fcsw_37007   0.89441 80.4469 0.2     1.03727 93.2961 52.2    no      0-241   243-369 
924                  */
925                 
926                 //get header line
927                 if (!in.eof()) {
928                         line = m->getline(in); m->gobble(in);
929                         out << line << endl;
930                 }
931                 
932                 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do, 
933                 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file, 
934                 //then ignore this report and continue until we find the report that found it to be chimeric
935                 
936                 while (!in.eof()) {
937                         
938                         if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
939                         
940                         in >> name;             m->gobble(in);
941                         in >> parent1;  m->gobble(in);
942                         
943                         if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
944                                 line = m->getline(in); m->gobble(in);
945                         }else {
946                                 if (parent1 == "no") {
947                                         //find unique name
948                                         itUnique = uniqueNames.find(name);
949                                         
950                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
951                                         else {
952                                                 //is this sequence really not chimeric??
953                                                 itChimeras = chimerasInFile.find(itUnique->second);
954                                                 
955                                                 if (itChimeras == chimerasInFile.end()) {
956                                                         itNames = namesInFile.find((itUnique->second));
957                                                         
958                                                         if (itNames == namesInFile.end()) {cout << itUnique->second << endl; out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
959                                                 }
960                                         }
961                                 }else { //read the rest of the line
962                                         double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
963                                         string flag, range1, range2;
964                                         bool print = false;
965                                         in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2;  m->gobble(in);
966                                         
967                                         //find unique name
968                                         itUnique = uniqueNames.find(name);
969                                         
970                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
971                                         else {
972                                                 name = itUnique->second;
973                                                 //is this name already in the file
974                                                 itNames = namesInFile.find((name));
975                                                 
976                                                 if (itNames == namesInFile.end()) { //no not in file
977                                                         if (flag == "no") { //are you really a no??
978                                                                 //is this sequence really not chimeric??
979                                                                 itChimeras = chimerasInFile.find(name);
980                                                                 
981                                                                 //then you really are a no so print, otherwise skip
982                                                                 if (itChimeras == chimerasInFile.end()) { print = true; }
983                                                         }else{ print = true; }
984                                                 }
985                                         }
986                                         
987                                         if (print) {
988                                                 out << name << '\t';
989                                                 
990                                                 namesInFile.insert(name);
991
992                                                 //output parent1's name
993                                                 itUnique = uniqueNames.find(parent1);
994                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
995                                                 else { out << itUnique->second << '\t'; }
996                                                 
997                                                 //output parent2's name
998                                                 itUnique = uniqueNames.find(parent2);
999                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1000                                                 else { out << itUnique->second << '\t'; }
1001                                                 
1002                                                 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1003                                         }
1004                                 }                               
1005                         }
1006                 }
1007                 in.close();
1008                 out.close();
1009                 
1010                 m->mothurRemove(outputFileName);
1011                 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1012                 
1013                 //edit fasta file
1014                 if (trim) {
1015                         ifstream in3; 
1016                         m->openInputFile(trimFileName, in3);
1017                         
1018                         ofstream out3;
1019                         m->openOutputFile(trimFileName+".temp", out3);
1020                         
1021                         namesInFile.clear();
1022                         
1023                         while (!in3.eof()) {
1024                                 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1025                                 
1026                                 Sequence seq(in3); m->gobble(in3);
1027                                 
1028                                 if (seq.getName() != "") {
1029                                         //find unique name
1030                                         itUnique = uniqueNames.find(seq.getName());
1031                                         
1032                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1033                                         else {
1034                                                 itNames = namesInFile.find((itUnique->second));
1035                                                 
1036                                                 if (itNames == namesInFile.end()) {
1037                                                         seq.printSequence(out3);
1038                                                 }
1039                                         }
1040                                 }
1041                         }
1042                         in3.close();
1043                         out3.close();
1044                         
1045                         m->mothurRemove(trimFileName);
1046                         rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1047                 }
1048                 
1049                 return total;
1050         }
1051         catch(exception& e) {
1052                 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1053                 exit(1);
1054         }
1055 }       
1056 //**********************************************************************************************************************
1057 int ChimeraSlayerCommand::setupChimera(string inputFile, map<string, int>& priority){
1058         try {
1059                 if (templatefile != "self") { //you want to run slayer with a reference template
1060                         chimera = new ChimeraSlayer(inputFile, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());      
1061                 }else {
1062                         chimera = new ChimeraSlayer(inputFile, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());    
1063                 }
1064                 
1065                 if (m->control_pressed) { delete chimera; return 0; }
1066                 
1067                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1068                 
1069                 return (chimera->getLength());
1070         }
1071         catch(exception& e) {
1072                 m->errorOut(e, "ChimeraSlayerCommand", "setupChimera");
1073                 exit(1);
1074         }
1075 }
1076 //**********************************************************************************************************************
1077
1078 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1079         try {
1080                 string nameFile = "";
1081                 
1082                 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1083                 
1084                 //use unique.seqs to create new name and fastafile
1085                 string inputString = "fasta=" + inputFile;
1086                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1087                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
1088                 
1089                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1090                 uniqueCommand->execute();
1091                 
1092                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1093                 
1094                 delete uniqueCommand;
1095                 
1096                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1097                 
1098                 nameFile = filenames["name"][0];
1099                 inputFile = filenames["fasta"][0];
1100                 
1101                 return nameFile;
1102         }
1103         catch(exception& e) {
1104                 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1105                 exit(1);
1106         }
1107 }
1108 //**********************************************************************************************************************
1109
1110 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
1111         try {
1112                 ofstream out;
1113                 m->openOutputFile(outputFName, out);
1114                 
1115                 ofstream out2;
1116                 m->openOutputFile(accnos, out2);
1117                 
1118                 ofstream out3;
1119                 if (trim) {  m->openOutputFile(fasta, out3); }
1120                 
1121                 ifstream inFASTA;
1122                 m->openInputFile(filename, inFASTA);
1123
1124                 inFASTA.seekg(filePos->start);
1125                 
1126                 if (filePos->start == 0) { chimera->printHeader(out); }
1127
1128                 bool done = false;
1129                 int count = 0;
1130         
1131                 while (!done) {
1132                 
1133                         if (m->control_pressed) {       out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
1134                 
1135                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
1136                         string candidateAligned = candidateSeq->getAligned();
1137                         
1138                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1139                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1140                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1141                                 }else{
1142                                         //find chimeras
1143                                         chimera->getChimeras(candidateSeq);
1144                                         
1145                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
1146                                                 
1147                                         //if you are not chimeric, then check each half
1148                                         data_results wholeResults = chimera->getResults();
1149                                         
1150                                         //determine if we need to split
1151                                         bool isChimeric = false;
1152                                         
1153                                         if (wholeResults.flag == "yes") {
1154                                                 string chimeraFlag = "no";
1155                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1156                                                    ||
1157                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1158                                                 
1159                                                 
1160                                                 if (chimeraFlag == "yes") {     
1161                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1162                                                 }
1163                                         }
1164                                         
1165                                         if ((!isChimeric) && trimera) {
1166                                                 
1167                                                 //split sequence in half by bases
1168                                                 string leftQuery, rightQuery;
1169                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1170                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1171                                                 
1172                                                 //run chimeraSlayer on each piece
1173                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1174                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1175                                                 
1176                                                 //find chimeras
1177                                                 chimera->getChimeras(left);
1178                                                 data_results leftResults = chimera->getResults();
1179                                                 
1180                                                 chimera->getChimeras(right);
1181                                                 data_results rightResults = chimera->getResults();
1182                                                 
1183                                                 //if either piece is chimeric then report
1184                                                 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1185                                                 if (trim) { trimmed.printSequence(out3);  }
1186                                                 
1187                                                 delete left; delete right;
1188                                                 
1189                                         }else { //already chimeric
1190                                                 //print results
1191                                                 Sequence trimmed = chimera->print(out, out2);
1192                                                 if (trim) { trimmed.printSequence(out3);  }
1193                                         }
1194                                         
1195                                         
1196                                 }
1197                                 count++;
1198                         }
1199                         
1200                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1201                                 unsigned long long pos = inFASTA.tellg();
1202                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
1203                         #else
1204                                 if (inFASTA.eof()) { break; }
1205                         #endif
1206                         
1207                         delete candidateSeq;
1208                         //report progress
1209                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1210                 }
1211                 //report progress
1212                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1213                 
1214                 out.close();
1215                 out2.close();
1216                 if (trim) { out3.close(); }
1217                 inFASTA.close();
1218                                 
1219                 return count;
1220         }
1221         catch(exception& e) {
1222                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1223                 exit(1);
1224         }
1225 }
1226 //**********************************************************************************************************************
1227 #ifdef USE_MPI
1228 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long long>& MPIPos){
1229         try {                           
1230                 MPI_Status status; 
1231                 int pid;
1232                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1233                 
1234                 for(int i=0;i<num;i++){
1235                         
1236                         if (m->control_pressed) {       return 1;       }
1237                         
1238                         //read next sequence
1239                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1240
1241                         char* buf4 = new char[length];
1242                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1243         
1244                         string tempBuf = buf4;
1245                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1246                         istringstream iss (tempBuf,istringstream::in);
1247
1248                         delete buf4;
1249
1250                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
1251                         string candidateAligned = candidateSeq->getAligned();
1252                 
1253                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1254                                 
1255                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1256                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1257                                 }else{
1258                 
1259                                         //find chimeras
1260                                         chimera->getChimeras(candidateSeq);
1261                         
1262                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
1263                                         
1264                                         //if you are not chimeric, then check each half
1265                                         data_results wholeResults = chimera->getResults();
1266                                         
1267                                         //determine if we need to split
1268                                         bool isChimeric = false;
1269                                         
1270                                         if (wholeResults.flag == "yes") {
1271                                                 string chimeraFlag = "no";
1272                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1273                                                    ||
1274                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1275                                                 
1276                                                 
1277                                                 if (chimeraFlag == "yes") {     
1278                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1279                                                 }
1280                                         }
1281                                         
1282                                         if ((!isChimeric) && trimera) {                                                 
1283                                                 //split sequence in half by bases
1284                                                 string leftQuery, rightQuery;
1285                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1286                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1287                                                 
1288                                                 //run chimeraSlayer on each piece
1289                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1290                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1291                                                 
1292                                                 //find chimeras
1293                                                 chimera->getChimeras(left);
1294                                                 data_results leftResults = chimera->getResults();
1295                                                 
1296                                                 chimera->getChimeras(right);
1297                                                 data_results rightResults = chimera->getResults();
1298                                                 
1299                                                 //if either piece is chimeric then report
1300                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1301                                                 if (trim) {  
1302                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1303                                                         
1304                                                         //write to accnos file
1305                                                         int length = outputString.length();
1306                                                         char* buf2 = new char[length];
1307                                                         memcpy(buf2, outputString.c_str(), length);
1308                                                         
1309                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1310                                                         delete buf2;
1311                                                 }
1312                                                 
1313                                                 delete left; delete right;
1314                                                 
1315                                         }else { 
1316                                                 //print results
1317                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1318                                                 
1319                                                 if (trim) {  
1320                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1321                                                         
1322                                                         //write to accnos file
1323                                                         int length = outputString.length();
1324                                                         char* buf2 = new char[length];
1325                                                         memcpy(buf2, outputString.c_str(), length);
1326                                                         
1327                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1328                                                         delete buf2;
1329                                                 }
1330                                         }
1331                                         
1332                                 }
1333                         }
1334                         delete candidateSeq;
1335                         
1336                         //report progress
1337                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
1338                 }
1339                 //report progress
1340                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
1341                 
1342                                 
1343                 return 0;
1344         }
1345         catch(exception& e) {
1346                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1347                 exit(1);
1348         }
1349 }
1350 #endif
1351
1352 /**************************************************************************************************/
1353
1354 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
1355         try {
1356                 int process = 0;
1357                 int num = 0;
1358                 int numNoParents = 0;
1359                 processIDS.clear();
1360                 
1361 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1362                 //loop through and create all the processes you want
1363                 while (process != processors) {
1364                         int pid = fork();
1365                         
1366                         if (pid > 0) {
1367                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1368                                 process++;
1369                         }else if (pid == 0){
1370                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
1371                                 
1372                                 //pass numSeqs to parent
1373                                 ofstream out;
1374                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1375                                 m->openOutputFile(tempFile, out);
1376                                 out << num << '\t' << chimera->getNumNoParents() << endl;
1377                                 out.close();
1378                                 exit(0);
1379                         }else { 
1380                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1381                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1382                                 exit(0);
1383                         }
1384                 }
1385                 
1386                 //force parent to wait until all the processes are done
1387                 for (int i=0;i<processors;i++) { 
1388                         int temp = processIDS[i];
1389                         wait(&temp);
1390                 }
1391                 
1392                 for (int i = 0; i < processIDS.size(); i++) {
1393                         ifstream in;
1394                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
1395                         m->openInputFile(tempFile, in);
1396                         if (!in.eof()) { int tempNum = 0; int tempNumParents = 0; in >> tempNum >> tempNumParents; num += tempNum; numNoParents += tempNumParents; }
1397                         in.close(); m->mothurRemove(tempFile);
1398                 }
1399 #else
1400                 
1401                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1402                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1403                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1404                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1405                 
1406                 vector<slayerData*> pDataArray; 
1407                 DWORD   dwThreadIdArray[processors];
1408                 HANDLE  hThreadArray[processors]; 
1409                 
1410                 //Create processor worker threads.
1411                 for( int i=0; i<processors; i++ ){
1412                         string extension = toString(i) + ".temp";
1413                         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);
1414                         pDataArray.push_back(tempslayer);
1415                         processIDS.push_back(i);
1416                         
1417                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1418                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1419                         hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
1420                 }
1421                                 
1422                 //Wait until all threads have terminated.
1423                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1424                 
1425                 //Close all thread handles and free memory allocations.
1426                 for(int i=0; i < pDataArray.size(); i++){
1427                         num += pDataArray[i]->count;
1428                         numNoParents += pDataArray[i]->numNoParents;
1429                         CloseHandle(hThreadArray[i]);
1430                         delete pDataArray[i];
1431                 }
1432 #endif  
1433                 if (num == numNoParents) {  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(); }
1434                 
1435                 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1436                 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1437                 if (trim) {  rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1438                 
1439                 //append output files
1440                 for(int i=1;i<processIDS.size();i++){
1441                         m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1442                         m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1443                         
1444                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1445                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1446                         
1447                         if (trim) {
1448                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1449                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1450                         }
1451                 }
1452                 
1453                 
1454                 return num;
1455         }
1456         catch(exception& e) {
1457                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1458                 exit(1);
1459         }
1460 }
1461
1462 /**************************************************************************************************/
1463
1464 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1465         try {
1466                 
1467                 string queryUnAligned = querySeq.getUnaligned();
1468                 int numBases = int(queryUnAligned.length() * 0.5);
1469                 
1470                 string queryAligned = querySeq.getAligned();
1471                 leftQuery = querySeq.getAligned();
1472                 rightQuery = querySeq.getAligned();
1473                 
1474                 int baseCount = 0;
1475                 int leftSpot = 0;
1476                 for (int i = 0; i < queryAligned.length(); i++) {
1477                         //if you are a base
1478                         if (isalpha(queryAligned[i])) {         
1479                                 baseCount++; 
1480                         }
1481                         
1482                         //if you have half
1483                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
1484                 }
1485                 
1486                 //blank out right side
1487                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1488                 
1489                 //blank out left side
1490                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1491                 
1492                 return 0;
1493                 
1494         }
1495         catch(exception& e) {
1496                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1497                 exit(1);
1498         }
1499 }
1500 /**************************************************************************************************/
1501 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1502         try {
1503                 map<string, int> nameAbund;
1504                 
1505                 //read through fastafile and store info
1506                 map<string, string> seqs;
1507                 ifstream in;
1508                 m->openInputFile(fastaFile, in);
1509                 
1510                 while (!in.eof()) {
1511                         
1512                         if (m->control_pressed) { in.close(); return nameAbund; }
1513                         
1514                         Sequence seq(in); m->gobble(in);
1515                         seqs[seq.getName()] = seq.getAligned();
1516                 }
1517                 
1518                 in.close();
1519                 
1520                 //read namefile
1521                 vector<seqPriorityNode> nameMapCount;
1522                 int error = m->readNames(nameFile, nameMapCount, seqs);
1523                 
1524                 if (m->control_pressed) { return nameAbund; }
1525                 
1526                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1527                 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; }
1528
1529                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1530                 
1531                 string newFasta = fastaFile + ".temp";
1532                 ofstream out;
1533                 m->openOutputFile(newFasta, out);
1534                 
1535                 //print new file in order of
1536                 for (int i = 0; i < nameMapCount.size(); i++) {
1537                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1538                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1539                 }
1540                 out.close();
1541                 
1542                 rename(newFasta.c_str(), fastaFile.c_str());
1543                                 
1544                 return nameAbund;
1545                 
1546         }
1547         catch(exception& e) {
1548                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1549                 exit(1);
1550         }
1551 }
1552 /**************************************************************************************************/
1553 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
1554         try {
1555                 map<string, int> nameAbund;
1556                 vector<seqPriorityNode> nameVector;
1557                 
1558                 //read through fastafile and store info
1559                 map<string, string> seqs;
1560                                 
1561                 for (int i = 0; i < thisseqs.size(); i++) {
1562                         
1563                         if (m->control_pressed) { return nameAbund; }
1564                         
1565                         map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
1566                         
1567                         if (itNameMap == nameMap.end()){
1568                                 m->control_pressed = true;
1569                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
1570                         }else {
1571                                 int num = m->getNumNames(itNameMap->second);
1572                                 
1573                                 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
1574                                 nameVector.push_back(temp);
1575                         }
1576                 }
1577         
1578                 //sort by num represented
1579                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
1580         
1581                 if (m->control_pressed) { return nameAbund; }
1582                 
1583                 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; }
1584                                 
1585                 ofstream out;
1586                 m->openOutputFile(newFile, out);
1587                 
1588                 //print new file in order of
1589                 for (int i = 0; i < nameVector.size(); i++) {
1590                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
1591                         nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
1592                 }
1593                 out.close();
1594                 
1595                 return nameAbund;
1596                 
1597         }
1598         catch(exception& e) {
1599                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1600                 exit(1);
1601         }
1602 }
1603 /**************************************************************************************************/
1604