]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
cf219951f08e314f57ebb2e6c27985d3f5409167
[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 "chimeraslayer.h"
12 #include "deconvolutecommand.h"
13
14 //**********************************************************************************************************************
15 vector<string> ChimeraSlayerCommand::setParameters(){   
16         try {
17                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
18                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
19                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
20                 CommandParameter pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
21                 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
22                 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
23                 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
24                 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
25                 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
26                 CommandParameter pminsnp("minsnp", "Number", "", "100", "", "", "",false,false); parameters.push_back(pminsnp);
27                 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
28                 CommandParameter psearch("search", "Multiple", "kmer-blast-distance", "distance", "", "", "",false,false); parameters.push_back(psearch);
29                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
30                 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(prealign);
31                 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
32                 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
33                 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
34                 CommandParameter piters("iters", "Number", "", "100", "", "", "",false,false); parameters.push_back(piters);
35                 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
36                 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
37                 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
38                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
39                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
40                 
41                 vector<string> myArray;
42                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 string ChimeraSlayerCommand::getHelpString(){   
52         try {
53                 string helpString = "";
54                 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
55                 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
56                 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, and realign.\n";
57                 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";
58                 helpString += "The name parameter allows you to provide a name file, if you are using template=self. \n";
59                 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
60                 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";
61                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
62 #ifdef USE_MPI
63                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
64 #endif
65                 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";
66                 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";
67                 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
68                 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
69                 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
70                 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
71                 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
72                 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";
73                 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
74                 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
75                 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=100.\n";
76                 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
77                 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
78                 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
79                 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 100) \n";
80                 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are distance, blast, and kmer, default distance. \n";
81                 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true.  \n";
82                 helpString += "The chimera.slayer command should be in the following format: \n";
83                 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
84                 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
85                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
86                 return helpString;
87         }
88         catch(exception& e) {
89                 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
90                 exit(1);
91         }
92 }
93 //**********************************************************************************************************************
94 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
95         try {
96                 abort = true; calledHelp = true;
97                 setParameters();
98                 vector<string> tempOutNames;
99                 outputTypes["chimera"] = tempOutNames;
100                 outputTypes["accnos"] = tempOutNames;
101                 outputTypes["fasta"] = tempOutNames;
102         }
103         catch(exception& e) {
104                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
105                 exit(1);
106         }
107 }
108 //***************************************************************************************************************
109 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
110         try {
111                 abort = false; calledHelp = false;   
112                 
113                 //allow user to run help
114                 if(option == "help") { help(); abort = true; calledHelp = true; }
115                 
116                 else {
117                         vector<string> myArray = setParameters();
118                         
119                         OptionParser parser(option);
120                         map<string,string> parameters = parser.getParameters();
121                         
122                         ValidParameters validParameter("chimera.slayer");
123                         map<string,string>::iterator it;
124                         
125                         //check to make sure all parameters are valid for command
126                         for (it = parameters.begin(); it != parameters.end(); it++) { 
127                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
128                         }
129                         
130                         vector<string> tempOutNames;
131                         outputTypes["chimera"] = tempOutNames;
132                         outputTypes["accnos"] = tempOutNames;
133                         outputTypes["fasta"] = tempOutNames;
134                 
135                         //if the user changes the input directory command factory will send this info to us in the output parameter 
136                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
137                         if (inputDir == "not found"){   inputDir = "";          }
138                                                 
139                         //check for required parameters
140                         fastafile = validParameter.validFile(parameters, "fasta", false);
141                         if (fastafile == "not found") {                                 
142                                 //if there is a current fasta file, use it
143                                 string filename = m->getFastaFile(); 
144                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
145                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
146                         }else { 
147                                 m->splitAtDash(fastafile, fastaFileNames);
148                                 
149                                 //go through files and make sure they are good, if not, then disregard them
150                                 for (int i = 0; i < fastaFileNames.size(); i++) {
151                                         
152                                         bool ignore = false;
153                                         if (fastaFileNames[i] == "current") { 
154                                                 fastaFileNames[i] = m->getFastaFile(); 
155                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
156                                                 else {  
157                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
158                                                         //erase from file list
159                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
160                                                         i--;
161                                                 }
162                                         }
163                                         
164                                         if (!ignore) {
165                                                 
166                                                 if (inputDir != "") {
167                                                         string path = m->hasPath(fastaFileNames[i]);
168                                                         //if the user has not given a path then, add inputdir. else leave path alone.
169                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
170                                                 }
171                 
172                                                 int ableToOpen;
173                                                 ifstream in;
174                                                 
175                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
176                                         
177                                                 //if you can't open it, try default location
178                                                 if (ableToOpen == 1) {
179                                                         if (m->getDefaultPath() != "") { //default path is set
180                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
181                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
182                                                                 ifstream in2;
183                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
184                                                                 in2.close();
185                                                                 fastaFileNames[i] = tryPath;
186                                                         }
187                                                 }
188                                                 
189                                                 if (ableToOpen == 1) {
190                                                         if (m->getOutputDir() != "") { //default path is set
191                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
192                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
193                                                                 ifstream in2;
194                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
195                                                                 in2.close();
196                                                                 fastaFileNames[i] = tryPath;
197                                                         }
198                                                 }
199                                                 
200                                                 in.close();
201                                                 
202                                                 if (ableToOpen == 1) { 
203                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
204                                                         //erase from file list
205                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
206                                                         i--;
207                                                 }
208                                         }
209                                 }
210                                 
211                                 //make sure there is at least one valid file left
212                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
213                         }
214                         
215                         
216                         //check for required parameters
217                         bool hasName = true;
218                         namefile = validParameter.validFile(parameters, "name", false);
219                         if (namefile == "not found") { namefile = "";  hasName = false; }
220                         else { 
221                                 m->splitAtDash(namefile, nameFileNames);
222                                 
223                                 //go through files and make sure they are good, if not, then disregard them
224                                 for (int i = 0; i < nameFileNames.size(); i++) {
225                                         
226                                         bool ignore = false;
227                                         if (nameFileNames[i] == "current") { 
228                                                 nameFileNames[i] = m->getNameFile(); 
229                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
230                                                 else {  
231                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
232                                                         //erase from file list
233                                                         nameFileNames.erase(nameFileNames.begin()+i);
234                                                         i--;
235                                                 }
236                                         }
237                                         
238                                         if (!ignore) {
239                                                 
240                                                 if (inputDir != "") {
241                                                         string path = m->hasPath(nameFileNames[i]);
242                                                         //if the user has not given a path then, add inputdir. else leave path alone.
243                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
244                                                 }
245                                                 
246                                                 int ableToOpen;
247                                                 ifstream in;
248                                                 
249                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
250                                                 
251                                                 //if you can't open it, try default location
252                                                 if (ableToOpen == 1) {
253                                                         if (m->getDefaultPath() != "") { //default path is set
254                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
255                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
256                                                                 ifstream in2;
257                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
258                                                                 in2.close();
259                                                                 nameFileNames[i] = tryPath;
260                                                         }
261                                                 }
262                                                 
263                                                 if (ableToOpen == 1) {
264                                                         if (m->getOutputDir() != "") { //default path is set
265                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
266                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
267                                                                 ifstream in2;
268                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
269                                                                 in2.close();
270                                                                 nameFileNames[i] = tryPath;
271                                                         }
272                                                 }
273                                                 
274                                                 in.close();
275                                                 
276                                                 if (ableToOpen == 1) { 
277                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
278                                                         //erase from file list
279                                                         nameFileNames.erase(nameFileNames.begin()+i);
280                                                         i--;
281                                                 }
282                                         }
283                                 }
284                                 
285                                 //make sure there is at least one valid file left
286                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
287                         }
288                         
289                         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; }
290                         
291                         //if the user changes the output directory command factory will send this info to us in the output parameter 
292                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
293                         
294                         
295                         string path;
296                         it = parameters.find("reference");
297                         //user has given a template file
298                         if(it != parameters.end()){ 
299                                 if (it->second == "self") { templatefile = "self"; }
300                                 else {
301                                         path = m->hasPath(it->second);
302                                         //if the user has not given a path then, add inputdir. else leave path alone.
303                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
304                                         
305                                         templatefile = validParameter.validFile(parameters, "reference", true);
306                                         if (templatefile == "not open") { abort = true; }
307                                         else if (templatefile == "not found") { templatefile = "";  m->mothurOut("reference is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true;  }  
308                                 }
309                         }
310                         
311                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
312                         m->setProcessors(temp);
313                         convert(temp, processors);
314                         
315                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
316                         convert(temp, ksize);
317                                                 
318                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
319                         convert(temp, window);
320                         
321                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
322                         convert(temp, match);
323                         
324                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
325                         convert(temp, mismatch);
326                         
327                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
328                         convert(temp, divR);
329                         
330                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
331                         convert(temp, minSimilarity);
332                         
333                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
334                         convert(temp, minCoverage);
335                         
336                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
337                         convert(temp, minBS);
338                         
339                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "100"; }
340                         convert(temp, minSNP);
341
342                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
343                         convert(temp, parents); 
344                         
345                         temp = validParameter.validFile(parameters, "realign", true);                   if (temp == "not found") { temp = "t"; }
346                         realign = m->isTrue(temp); 
347                         
348                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
349                         trim = m->isTrue(temp); 
350                         
351                         temp = validParameter.validFile(parameters, "split", false);                    if (temp == "not found") { temp = "f"; }
352                         trimera = m->isTrue(temp); 
353                         
354                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "distance"; }
355                         
356                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "100"; }              
357                         convert(temp, iters); 
358                          
359                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
360                         convert(temp, increment);
361                         
362                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
363                         convert(temp, numwanted);
364
365                         if ((search != "distance") && (search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
366                 }
367         }
368         catch(exception& e) {
369                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
370                 exit(1);
371         }
372 }
373 //***************************************************************************************************************
374
375 int ChimeraSlayerCommand::execute(){
376         try{
377                 
378                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
379                 
380                 for (int s = 0; s < fastaFileNames.size(); s++) {
381                                 
382                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
383                 
384                         int start = time(NULL); 
385                         
386                         if (templatefile != "self") { //you want to run slayer with a refernce template
387                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);     
388                         }else {
389                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
390                                 string nameFile = "";
391                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
392                                         nameFile = nameFileNames[s];
393                                 }else {
394                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
395                                         
396                                         //use unique.seqs to create new name and fastafile
397                                         string inputString = "fasta=" + fastaFileNames[s];
398                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
399                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
400                                                                  
401                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
402                                         uniqueCommand->execute();
403                                         
404                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
405                                         
406                                         delete uniqueCommand;
407                                         
408                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
409                                         
410                                         nameFile = filenames["name"][0];
411                                         fastaFileNames[s] = filenames["fasta"][0];
412                                 }
413                                 
414                                 //sort fastafile by abundance, returns new sorted fastafile name
415                                 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
416                                 map<string, int> priority = sortFastaFile(fastaFileNames[s], nameFile);
417                                 m->mothurOut("Done."); m->mothurOutEndLine();
418                                 
419                                 if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       remove(outputNames[j].c_str()); }  return 0;    }
420
421                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);   
422                         }
423                                 
424                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
425                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
426                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
427                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";
428                         
429                         if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0;    }
430                         
431                         if (chimera->getUnaligned()) { 
432                                 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); 
433                                 delete chimera;
434                                 return 0; 
435                         }
436                         templateSeqsLength = chimera->getLength();
437                         
438                 #ifdef USE_MPI  
439                         int pid, numSeqsPerProcessor; 
440                                 int tag = 2001;
441                                 vector<unsigned long int> MPIPos;
442                                 
443                                 MPI_Status status; 
444                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
445                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
446
447                                 MPI_File inMPI;
448                                 MPI_File outMPI;
449                                 MPI_File outMPIAccnos;
450                                 MPI_File outMPIFasta;
451                                 
452                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
453                                 int inMode=MPI_MODE_RDONLY; 
454                                 
455                                 char outFilename[1024];
456                                 strcpy(outFilename, outputFileName.c_str());
457                                 
458                                 char outAccnosFilename[1024];
459                                 strcpy(outAccnosFilename, accnosFileName.c_str());
460                         
461                                 char outFastaFilename[1024];
462                                 strcpy(outFastaFilename, trimFastaFileName.c_str());
463                                 
464                                 char inFileName[1024];
465                                 strcpy(inFileName, fastaFileNames[s].c_str());
466
467                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
468                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
469                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
470                                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
471
472                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) {   remove(outputNames[j].c_str()); }   delete chimera; return 0;  }
473                         
474                                 if (pid == 0) { //you are the root process 
475                                         m->mothurOutEndLine();
476                                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
477                                         m->mothurOutEndLine();
478                 
479                                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
480                                         
481                                         //print header
482                                         int length = outTemp.length();
483                                         char* buf2 = new char[length];
484                                         memcpy(buf2, outTemp.c_str(), length);
485
486                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
487                                         delete buf2;
488
489                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
490                                         
491                                         if (templatefile != "self") { //if template=self we can only use 1 processor
492                                                 //send file positions to all processes
493                                                 for(int i = 1; i < processors; i++) { 
494                                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
495                                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
496                                                 }
497                                         }
498                                         //figure out how many sequences you have to align
499                                         numSeqsPerProcessor = numSeqs / processors;
500                                         int startIndex =  pid * numSeqsPerProcessor;
501                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
502                                         
503                                         if (templatefile == "self") { //if template=self we can only use 1 processor
504                                                 startIndex = 0;
505                                                 numSeqsPerProcessor = numSeqs;
506                                         }
507                                         
508                                         //do your part
509                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
510                                         
511                                         if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  for (int j = 0; j < outputNames.size(); j++) {   remove(outputNames[j].c_str()); }  remove(outputFileName.c_str());  remove(accnosFileName.c_str());  delete chimera; return 0;  }
512
513                                 }else{ //you are a child process
514                                         if (templatefile != "self") { //if template=self we can only use 1 processor
515                                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
516                                                 MPIPos.resize(numSeqs+1);
517                                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
518                                         
519                                                 //figure out how many sequences you have to align
520                                                 numSeqsPerProcessor = numSeqs / processors;
521                                                 int startIndex =  pid * numSeqsPerProcessor;
522                                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
523                                         
524                                                 //do your part
525                                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
526                                         
527                                                 if (m->control_pressed) { outputTypes.clear();  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  for (int j = 0; j < outputNames.size(); j++) {   remove(outputNames[j].c_str()); }  delete chimera; return 0;  }
528                                 
529                                         }
530                                 }
531                                 
532                                 //close files 
533                                 MPI_File_close(&inMPI);
534                                 MPI_File_close(&outMPI);
535                                 MPI_File_close(&outMPIAccnos); 
536                                 if (trim) { MPI_File_close(&outMPIFasta); }
537                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
538                                 
539                 #else
540                         ofstream outHeader;
541                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
542                         m->openOutputFile(tempHeader, outHeader);
543                         
544                         chimera->printHeader(outHeader);
545                         outHeader.close();
546                         
547                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
548                                 
549                         for (int i = 0; i < (positions.size()-1); i++) {
550                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
551                         }       
552
553                         //break up file
554                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
555                                 if(processors == 1){
556                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
557                                         
558                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {      remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
559                                         
560                                 }else{
561                                         processIDS.resize(0);
562                                         
563                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName); 
564                                 
565                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
566                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
567                                         if (trim) {  rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
568                                                 
569                                         //append output files
570                                         for(int i=1;i<processors;i++){
571                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
572                                                 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
573                                         }
574                                         
575                                         //append output files
576                                         for(int i=1;i<processors;i++){
577                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
578                                                 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
579                                         }
580                                         
581                                         if (trim) {
582                                                 for(int i=1;i<processors;i++){
583                                                         m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
584                                                         remove((trimFastaFileName + toString(processIDS[i]) + ".temp").c_str());
585                                                 }
586                                         }
587                                         
588                                         if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {  remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
589                                 }
590
591                         #else
592                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
593                                 
594                                 if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) {      remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear(); delete chimera; return 0; }
595                                 
596                         #endif
597                         
598                         m->appendFiles(outputFileName, tempHeader);
599                 
600                         remove(outputFileName.c_str());
601                         rename(tempHeader.c_str(), outputFileName.c_str());
602                         
603                 #endif
604                         delete chimera;
605                         
606                         
607                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
608                         
609                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
610                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
611                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
612                         
613                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
614                 }
615                 
616                 //set accnos file as new current accnosfile
617                 string current = "";
618                 itTypes = outputTypes.find("accnos");
619                 if (itTypes != outputTypes.end()) {
620                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
621                 }
622                 
623                 if (trim) {
624                         itTypes = outputTypes.find("fasta");
625                         if (itTypes != outputTypes.end()) {
626                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
627                         }
628                 }
629                 
630                 m->mothurOutEndLine();
631                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
632                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
633                 m->mothurOutEndLine();
634
635                 return 0;
636                 
637         }
638         catch(exception& e) {
639                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
640                 exit(1);
641         }
642 }
643 //**********************************************************************************************************************
644
645 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
646         try {
647                 ofstream out;
648                 m->openOutputFile(outputFName, out);
649                 
650                 ofstream out2;
651                 m->openOutputFile(accnos, out2);
652                 
653                 ofstream out3;
654                 if (trim) {  m->openOutputFile(fasta, out3); }
655                 
656                 ifstream inFASTA;
657                 m->openInputFile(filename, inFASTA);
658
659                 inFASTA.seekg(filePos->start);
660
661                 bool done = false;
662                 int count = 0;
663         
664                 while (!done) {
665                 
666                         if (m->control_pressed) {       out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
667                 
668                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
669                         string candidateAligned = candidateSeq->getAligned();
670                         
671                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
672                                 
673                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
674                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
675                                 }else{
676                                         //find chimeras
677                                         chimera->getChimeras(candidateSeq);
678                                         
679                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
680                                                 
681                                         //if you are not chimeric, then check each half
682                                         data_results wholeResults = chimera->getResults();
683                                         
684                                         //determine if we need to split
685                                         bool isChimeric = false;
686                                         
687                                         if (wholeResults.flag == "yes") {
688                                                 string chimeraFlag = "no";
689                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
690                                                    ||
691                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
692                                                 
693                                                 
694                                                 if (chimeraFlag == "yes") {     
695                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
696                                                 }
697                                         }
698                                         
699                                         if ((!isChimeric) && trimera) {
700                                                 
701                                                 //split sequence in half by bases
702                                                 string leftQuery, rightQuery;
703                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
704                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
705                                                 
706                                                 //run chimeraSlayer on each piece
707                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
708                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
709                                                 
710                                                 //find chimeras
711                                                 chimera->getChimeras(left);
712                                                 data_results leftResults = chimera->getResults();
713                                                 
714                                                 chimera->getChimeras(right);
715                                                 data_results rightResults = chimera->getResults();
716                                                 
717                                                 //if either piece is chimeric then report
718                                                 Sequence* trimmed = chimera->print(out, out2, leftResults, rightResults);
719                                                 if (trim) { trimmed->printSequence(out3); delete trimmed; }
720                                                 
721                                                 delete left; delete right;
722                                                 
723                                         }else { //already chimeric
724                                                 //print results
725                                                 Sequence* trimmed = chimera->print(out, out2);
726                                                 if (trim) { trimmed->printSequence(out3); delete trimmed; }
727                                         }
728                                         
729                                         
730                                 }
731                                 count++;
732                         }
733                         
734                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
735                                 unsigned long int pos = inFASTA.tellg();
736                         //cout << candidateSeq->getName() << '\t' << pos << endl;
737                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
738                         #else
739                                 if (inFASTA.eof()) { break; }
740                         #endif
741                         
742                         delete candidateSeq;
743                         //report progress
744                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
745                 }
746                 //report progress
747                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
748                 
749                 out.close();
750                 out2.close();
751                 if (trim) { out3.close(); }
752                 inFASTA.close();
753                                 
754                 return count;
755         }
756         catch(exception& e) {
757                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
758                 exit(1);
759         }
760 }
761 //**********************************************************************************************************************
762 #ifdef USE_MPI
763 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
764         try {                           
765                 MPI_Status status; 
766                 int pid;
767                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
768                 
769                 for(int i=0;i<num;i++){
770                         
771                         if (m->control_pressed) {       return 1;       }
772                         
773                         //read next sequence
774                         int length = MPIPos[start+i+1] - MPIPos[start+i];
775
776                         char* buf4 = new char[length];
777                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
778         
779                         string tempBuf = buf4;
780                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
781                         istringstream iss (tempBuf,istringstream::in);
782
783                         delete buf4;
784
785                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
786                         string candidateAligned = candidateSeq->getAligned();
787                 
788                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
789                                 
790                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
791                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
792                                 }else{
793                 
794                                         //find chimeras
795                                         chimera->getChimeras(candidateSeq);
796                         
797                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
798                                         
799                                         //if you are not chimeric, then check each half
800                                         data_results wholeResults = chimera->getResults();
801                                         
802                                         //determine if we need to split
803                                         bool isChimeric = false;
804                                         
805                                         if (wholeResults.flag == "yes") {
806                                                 string chimeraFlag = "no";
807                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
808                                                    ||
809                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
810                                                 
811                                                 
812                                                 if (chimeraFlag == "yes") {     
813                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
814                                                 }
815                                         }
816                                         
817                                         if ((!isChimeric) && trimera) {                                                 
818                                                 //split sequence in half by bases
819                                                 string leftQuery, rightQuery;
820                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
821                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
822                                                 
823                                                 //run chimeraSlayer on each piece
824                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
825                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
826                                                 
827                                                 //find chimeras
828                                                 chimera->getChimeras(left);
829                                                 data_results leftResults = chimera->getResults();
830                                                 
831                                                 chimera->getChimeras(right);
832                                                 data_results rightResults = chimera->getResults();
833                                                 
834                                                 //if either piece is chimeric then report
835                                                 Sequence* trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
836                                                 if (trim) {  
837                                                         string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
838                                                         delete trimmed;
839                                                         
840                                                         //write to accnos file
841                                                         int length = outputString.length();
842                                                         char* buf2 = new char[length];
843                                                         memcpy(buf2, outputString.c_str(), length);
844                                                         
845                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
846                                                         delete buf2;
847                                                 }
848                                                 
849                                                 delete left; delete right;
850                                                 
851                                         }else { 
852                                                 //print results
853                                                 Sequence* trimmed = chimera->print(outMPI, outAccMPI);
854                                                 
855                                                 if (trim) {  
856                                                         string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
857                                                         delete trimmed;
858                                                         
859                                                         //write to accnos file
860                                                         int length = outputString.length();
861                                                         char* buf2 = new char[length];
862                                                         memcpy(buf2, outputString.c_str(), length);
863                                                         
864                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
865                                                         delete buf2;
866                                                 }
867                                         }
868                                         
869                                 }
870                         }
871                         delete candidateSeq;
872                         
873                         //report progress
874                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
875                 }
876                 //report progress
877                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
878                 
879                                 
880                 return 0;
881         }
882         catch(exception& e) {
883                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
884                 exit(1);
885         }
886 }
887 #endif
888
889 /**************************************************************************************************/
890
891 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
892         try {
893 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
894                 int process = 0;
895                 int num = 0;
896                 
897                 //loop through and create all the processes you want
898                 while (process != processors) {
899                         int pid = fork();
900                         
901                         if (pid > 0) {
902                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
903                                 process++;
904                         }else if (pid == 0){
905                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
906                                 
907                                 //pass numSeqs to parent
908                                 ofstream out;
909                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
910                                 m->openOutputFile(tempFile, out);
911                                 out << num << endl;
912                                 out.close();
913                                 
914                                 exit(0);
915                         }else { 
916                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
917                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
918                                 exit(0);
919                         }
920                 }
921                 
922                 //force parent to wait until all the processes are done
923                 for (int i=0;i<processors;i++) { 
924                         int temp = processIDS[i];
925                         wait(&temp);
926                 }
927                 
928                 for (int i = 0; i < processIDS.size(); i++) {
929                         ifstream in;
930                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
931                         m->openInputFile(tempFile, in);
932                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
933                         in.close(); remove(tempFile.c_str());
934                 }
935                 
936                 return num;
937 #endif          
938         }
939         catch(exception& e) {
940                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
941                 exit(1);
942         }
943 }
944
945 /**************************************************************************************************/
946
947 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
948         try {
949                 
950                 string queryUnAligned = querySeq.getUnaligned();
951                 int numBases = int(queryUnAligned.length() * 0.5);
952                 
953                 string queryAligned = querySeq.getAligned();
954                 leftQuery = querySeq.getAligned();
955                 rightQuery = querySeq.getAligned();
956                 
957                 int baseCount = 0;
958                 int leftSpot = 0;
959                 for (int i = 0; i < queryAligned.length(); i++) {
960                         //if you are a base
961                         if (isalpha(queryAligned[i])) {         
962                                 baseCount++; 
963                         }
964                         
965                         //if you have half
966                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
967                 }
968                 
969                 //blank out right side
970                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
971                 
972                 //blank out left side
973                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
974                 
975                 return 0;
976                 
977         }
978         catch(exception& e) {
979                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
980                 exit(1);
981         }
982 }
983 /**************************************************************************************************/
984 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
985         try {
986                 map<string, int> nameAbund;
987                 
988                 //read through fastafile and store info
989                 map<string, string> seqs;
990                 ifstream in;
991                 m->openInputFile(fastaFile, in);
992                 
993                 while (!in.eof()) {
994                         
995                         if (m->control_pressed) { in.close(); return nameAbund; }
996                         
997                         Sequence seq(in); m->gobble(in);
998                         seqs[seq.getName()] = seq.getAligned();
999                 }
1000                 
1001                 in.close();
1002                 
1003                 //read namefile
1004                 vector<seqPriorityNode> nameMapCount;
1005                 int error = m->readNames(nameFile, nameMapCount, seqs);
1006                 
1007                 if (m->control_pressed) { return nameAbund; }
1008                 
1009                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1010                 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; }
1011
1012                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1013                 
1014                 string newFasta = fastaFile + ".temp";
1015                 ofstream out;
1016                 m->openOutputFile(newFasta, out);
1017                 
1018                 //print new file in order of
1019                 for (int i = 0; i < nameMapCount.size(); i++) {
1020                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1021                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1022                 }
1023                 out.close();
1024                 
1025                 rename(newFasta.c_str(), fastaFile.c_str());
1026                                 
1027                 return nameAbund;
1028                 
1029         }
1030         catch(exception& e) {
1031                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1032                 exit(1);
1033         }
1034 }
1035
1036 /**************************************************************************************************/
1037