]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
1.19.0
[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", "", "10", "", "", "",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", "blast", "", "", "",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", "", "1000", "", "", "",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=1000.\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: 10) \n";
80                 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \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 = "10"; }
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", false);                  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 = "blast"; }
355                         
356                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "1000"; }             
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 != "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                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
378                 
379                 for (int s = 0; s < fastaFileNames.size(); s++) {
380                                 
381                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
382                 
383                         int start = time(NULL); 
384                         
385                         if (templatefile != "self") { //you want to run slayer with a refernce template
386                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);     
387                         }else {
388                                 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
389                                 string nameFile = "";
390                                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
391                                         nameFile = nameFileNames[s];
392                                 }else {
393                                         m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
394                                         
395                                         //use unique.seqs to create new name and fastafile
396                                         string inputString = "fasta=" + fastaFileNames[s];
397                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
398                                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
399                                                                  
400                                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
401                                         uniqueCommand->execute();
402                                         
403                                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
404                                         
405                                         delete uniqueCommand;
406                                         
407                                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
408                                         
409                                         nameFile = filenames["name"][0];
410                                         fastaFileNames[s] = filenames["fasta"][0];
411                                 }
412                                 
413                                 //sort fastafile by abundance, returns new sorted fastafile name
414                                 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
415                                 map<string, int> priority = sortFastaFile(fastaFileNames[s], nameFile);
416                                 m->mothurOut("Done."); m->mothurOutEndLine();
417                                 
418                                 if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       remove(outputNames[j].c_str()); }  return 0;    }
419
420                                 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);   
421                         }
422                                 
423                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
424                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
425                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
426                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";
427                         
428                         if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) {        remove(outputNames[j].c_str()); }  return 0;    }
429                         
430                         if (chimera->getUnaligned()) { 
431                                 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); 
432                                 delete chimera;
433                                 return 0; 
434                         }
435                         templateSeqsLength = chimera->getLength();
436                         
437                 #ifdef USE_MPI  
438                         int pid, numSeqsPerProcessor; 
439                                 int tag = 2001;
440                                 vector<unsigned long int> MPIPos;
441                                 
442                                 MPI_Status status; 
443                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
444                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
445
446                                 MPI_File inMPI;
447                                 MPI_File outMPI;
448                                 MPI_File outMPIAccnos;
449                                 MPI_File outMPIFasta;
450                                 
451                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
452                                 int inMode=MPI_MODE_RDONLY; 
453                                 
454                                 char outFilename[1024];
455                                 strcpy(outFilename, outputFileName.c_str());
456                                 
457                                 char outAccnosFilename[1024];
458                                 strcpy(outAccnosFilename, accnosFileName.c_str());
459                         
460                                 char outFastaFilename[1024];
461                                 strcpy(outFastaFilename, trimFastaFileName.c_str());
462                                 
463                                 char inFileName[1024];
464                                 strcpy(inFileName, fastaFileNames[s].c_str());
465
466                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
467                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
468                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
469                                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
470
471                         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;  }
472                         
473                                 if (pid == 0) { //you are the root process 
474                                         m->mothurOutEndLine();
475                                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
476                                         m->mothurOutEndLine();
477                 
478                                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
479                                         
480                                         //print header
481                                         int length = outTemp.length();
482                                         char* buf2 = new char[length];
483                                         memcpy(buf2, outTemp.c_str(), length);
484
485                                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
486                                         delete buf2;
487
488                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
489                                         
490                                         if (templatefile != "self") { //if template=self we can only use 1 processor
491                                                 //send file positions to all processes
492                                                 for(int i = 1; i < processors; i++) { 
493                                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
494                                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
495                                                 }
496                                         }
497                                         //figure out how many sequences you have to align
498                                         numSeqsPerProcessor = numSeqs / processors;
499                                         int startIndex =  pid * numSeqsPerProcessor;
500                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
501                                         
502                                         if (templatefile == "self") { //if template=self we can only use 1 processor
503                                                 startIndex = 0;
504                                                 numSeqsPerProcessor = numSeqs;
505                                         }
506                                         
507                                         //do your part
508                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
509                                         
510                                         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;  }
511
512                                 }else{ //you are a child process
513                                         if (templatefile != "self") { //if template=self we can only use 1 processor
514                                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
515                                                 MPIPos.resize(numSeqs+1);
516                                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
517                                         
518                                                 //figure out how many sequences you have to align
519                                                 numSeqsPerProcessor = numSeqs / processors;
520                                                 int startIndex =  pid * numSeqsPerProcessor;
521                                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
522                                         
523                                                 //do your part
524                                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
525                                         
526                                                 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;  }
527                                 
528                                         }
529                                 }
530                                 
531                                 //close files 
532                                 MPI_File_close(&inMPI);
533                                 MPI_File_close(&outMPI);
534                                 MPI_File_close(&outMPIAccnos); 
535                                 if (trim) { MPI_File_close(&outMPIFasta); }
536                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
537                                 
538                 #else
539                         ofstream outHeader;
540                         string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
541                         m->openOutputFile(tempHeader, outHeader);
542                         
543                         chimera->printHeader(outHeader);
544                         outHeader.close();
545                         
546                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
547                                 
548                         for (int i = 0; i < (positions.size()-1); i++) {
549                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
550                         }       
551
552                         //break up file
553                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
554                                 if(processors == 1){
555                                         numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
556                                         
557                                         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; }
558                                         
559                                 }else{
560                                         processIDS.resize(0);
561                                         
562                                         numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName); 
563                                 
564                                         rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
565                                         rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
566                                         if (trim) {  rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
567                                                 
568                                         //append output files
569                                         for(int i=1;i<processors;i++){
570                                                 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
571                                                 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
572                                         }
573                                         
574                                         //append output files
575                                         for(int i=1;i<processors;i++){
576                                                 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
577                                                 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
578                                         }
579                                         
580                                         if (trim) {
581                                                 for(int i=1;i<processors;i++){
582                                                         m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
583                                                         remove((trimFastaFileName + toString(processIDS[i]) + ".temp").c_str());
584                                                 }
585                                         }
586                                         
587                                         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; }
588                                 }
589
590                         #else
591                                 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
592                                 
593                                 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; }
594                                 
595                         #endif
596                         
597                         m->appendFiles(outputFileName, tempHeader);
598                 
599                         remove(outputFileName.c_str());
600                         rename(tempHeader.c_str(), outputFileName.c_str());
601                         
602                 #endif
603                         delete chimera;
604                         
605                         
606                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
607                         
608                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
609                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
610                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
611                         
612                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
613                 }
614                 
615                 //set accnos file as new current accnosfile
616                 string current = "";
617                 itTypes = outputTypes.find("accnos");
618                 if (itTypes != outputTypes.end()) {
619                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
620                 }
621                 
622                 if (trim) {
623                         itTypes = outputTypes.find("fasta");
624                         if (itTypes != outputTypes.end()) {
625                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
626                         }
627                 }
628                 
629                 m->mothurOutEndLine();
630                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
631                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
632                 m->mothurOutEndLine();
633
634                 return 0;
635                 
636         }
637         catch(exception& e) {
638                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
639                 exit(1);
640         }
641 }
642 //**********************************************************************************************************************
643
644 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
645         try {
646                 ofstream out;
647                 m->openOutputFile(outputFName, out);
648                 
649                 ofstream out2;
650                 m->openOutputFile(accnos, out2);
651                 
652                 ofstream out3;
653                 if (trim) {  m->openOutputFile(fasta, out3); }
654                 
655                 ifstream inFASTA;
656                 m->openInputFile(filename, inFASTA);
657
658                 inFASTA.seekg(filePos->start);
659
660                 bool done = false;
661                 int count = 0;
662         
663                 while (!done) {
664                 
665                         if (m->control_pressed) {       out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
666                 
667                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
668                         string candidateAligned = candidateSeq->getAligned();
669                         
670                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
671                                 
672                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
673                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
674                                 }else{
675                                         //find chimeras
676                                         chimera->getChimeras(candidateSeq);
677                                         
678                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
679                                                 
680                                         //if you are not chimeric, then check each half
681                                         data_results wholeResults = chimera->getResults();
682                                         
683                                         //determine if we need to split
684                                         bool isChimeric = false;
685                                         
686                                         if (wholeResults.flag == "yes") {
687                                                 string chimeraFlag = "no";
688                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
689                                                    ||
690                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
691                                                 
692                                                 
693                                                 if (chimeraFlag == "yes") {     
694                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
695                                                 }
696                                         }
697                                         
698                                         if ((!isChimeric) && trimera) {
699                                                 
700                                                 //split sequence in half by bases
701                                                 string leftQuery, rightQuery;
702                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
703                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
704                                                 
705                                                 //run chimeraSlayer on each piece
706                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
707                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
708                                                 
709                                                 //find chimeras
710                                                 chimera->getChimeras(left);
711                                                 data_results leftResults = chimera->getResults();
712                                                 
713                                                 chimera->getChimeras(right);
714                                                 data_results rightResults = chimera->getResults();
715                                                 
716                                                 //if either piece is chimeric then report
717                                                 Sequence* trimmed = chimera->print(out, out2, leftResults, rightResults);
718                                                 if (trim) { trimmed->printSequence(out3); delete trimmed; }
719                                                 
720                                                 delete left; delete right;
721                                                 
722                                         }else { //already chimeric
723                                                 //print results
724                                                 Sequence* trimmed = chimera->print(out, out2);
725                                                 if (trim) { trimmed->printSequence(out3); delete trimmed; }
726                                         }
727                                         
728                                         
729                                 }
730                                 count++;
731                         }
732                         
733                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
734                                 unsigned long int pos = inFASTA.tellg();
735                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
736                         #else
737                                 if (inFASTA.eof()) { break; }
738                         #endif
739                         
740                         delete candidateSeq;
741                         //report progress
742                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
743                 }
744                 //report progress
745                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
746                 
747                 out.close();
748                 out2.close();
749                 if (trim) { out3.close(); }
750                 inFASTA.close();
751                                 
752                 return count;
753         }
754         catch(exception& e) {
755                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
756                 exit(1);
757         }
758 }
759 //**********************************************************************************************************************
760 #ifdef USE_MPI
761 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
762         try {                           
763                 MPI_Status status; 
764                 int pid;
765                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
766                 
767                 for(int i=0;i<num;i++){
768                         
769                         if (m->control_pressed) {       return 1;       }
770                         
771                         //read next sequence
772                         int length = MPIPos[start+i+1] - MPIPos[start+i];
773
774                         char* buf4 = new char[length];
775                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
776         
777                         string tempBuf = buf4;
778                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
779                         istringstream iss (tempBuf,istringstream::in);
780
781                         delete buf4;
782
783                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
784                         string candidateAligned = candidateSeq->getAligned();
785                 
786                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
787                                 
788                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
789                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
790                                 }else{
791                 
792                                         //find chimeras
793                                         chimera->getChimeras(candidateSeq);
794                         
795                                         if (m->control_pressed) {       delete candidateSeq; return 1;  }
796                                         
797                                         //if you are not chimeric, then check each half
798                                         data_results wholeResults = chimera->getResults();
799                                         
800                                         //determine if we need to split
801                                         bool isChimeric = false;
802                                         
803                                         if (wholeResults.flag == "yes") {
804                                                 string chimeraFlag = "no";
805                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
806                                                    ||
807                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
808                                                 
809                                                 
810                                                 if (chimeraFlag == "yes") {     
811                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
812                                                 }
813                                         }
814                                         
815                                         if ((!isChimeric) && trimera) {                                                 
816                                                 //split sequence in half by bases
817                                                 string leftQuery, rightQuery;
818                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
819                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
820                                                 
821                                                 //run chimeraSlayer on each piece
822                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
823                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
824                                                 
825                                                 //find chimeras
826                                                 chimera->getChimeras(left);
827                                                 data_results leftResults = chimera->getResults();
828                                                 
829                                                 chimera->getChimeras(right);
830                                                 data_results rightResults = chimera->getResults();
831                                                 
832                                                 //if either piece is chimeric then report
833                                                 Sequence* trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
834                                                 if (trim) {  
835                                                         string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
836                                                         delete trimmed;
837                                                         
838                                                         //write to accnos file
839                                                         int length = outputString.length();
840                                                         char* buf2 = new char[length];
841                                                         memcpy(buf2, outputString.c_str(), length);
842                                                         
843                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
844                                                         delete buf2;
845                                                 }
846                                                 
847                                                 delete left; delete right;
848                                                 
849                                         }else { 
850                                                 //print results
851                                                 Sequence* trimmed = chimera->print(outMPI, outAccMPI);
852                                                 
853                                                 if (trim) {  
854                                                         string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
855                                                         delete trimmed;
856                                                         
857                                                         //write to accnos file
858                                                         int length = outputString.length();
859                                                         char* buf2 = new char[length];
860                                                         memcpy(buf2, outputString.c_str(), length);
861                                                         
862                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
863                                                         delete buf2;
864                                                 }
865                                         }
866                                         
867                                 }
868                         }
869                         delete candidateSeq;
870                         
871                         //report progress
872                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
873                 }
874                 //report progress
875                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
876                 
877                                 
878                 return 0;
879         }
880         catch(exception& e) {
881                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
882                 exit(1);
883         }
884 }
885 #endif
886
887 /**************************************************************************************************/
888
889 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
890         try {
891 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
892                 int process = 0;
893                 int num = 0;
894                 
895                 //loop through and create all the processes you want
896                 while (process != processors) {
897                         int pid = fork();
898                         
899                         if (pid > 0) {
900                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
901                                 process++;
902                         }else if (pid == 0){
903                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
904                                 
905                                 //pass numSeqs to parent
906                                 ofstream out;
907                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
908                                 m->openOutputFile(tempFile, out);
909                                 out << num << endl;
910                                 out.close();
911                                 
912                                 exit(0);
913                         }else { 
914                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
915                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
916                                 exit(0);
917                         }
918                 }
919                 
920                 //force parent to wait until all the processes are done
921                 for (int i=0;i<processors;i++) { 
922                         int temp = processIDS[i];
923                         wait(&temp);
924                 }
925                 
926                 for (int i = 0; i < processIDS.size(); i++) {
927                         ifstream in;
928                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
929                         m->openInputFile(tempFile, in);
930                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
931                         in.close(); remove(tempFile.c_str());
932                 }
933                 
934                 return num;
935 #endif          
936         }
937         catch(exception& e) {
938                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
939                 exit(1);
940         }
941 }
942
943 /**************************************************************************************************/
944
945 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
946         try {
947                 
948                 string queryUnAligned = querySeq.getUnaligned();
949                 int numBases = int(queryUnAligned.length() * 0.5);
950                 
951                 string queryAligned = querySeq.getAligned();
952                 leftQuery = querySeq.getAligned();
953                 rightQuery = querySeq.getAligned();
954                 
955                 int baseCount = 0;
956                 int leftSpot = 0;
957                 for (int i = 0; i < queryAligned.length(); i++) {
958                         //if you are a base
959                         if (isalpha(queryAligned[i])) {         
960                                 baseCount++; 
961                         }
962                         
963                         //if you have half
964                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
965                 }
966                 
967                 //blank out right side
968                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
969                 
970                 //blank out left side
971                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
972                 
973                 return 0;
974                 
975         }
976         catch(exception& e) {
977                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
978                 exit(1);
979         }
980 }
981 /**************************************************************************************************/
982 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
983         try {
984                 map<string, int> nameAbund;
985                 
986                 //read through fastafile and store info
987                 map<string, string> seqs;
988                 ifstream in;
989                 m->openInputFile(fastaFile, in);
990                 
991                 while (!in.eof()) {
992                         
993                         if (m->control_pressed) { in.close(); return nameAbund; }
994                         
995                         Sequence seq(in); m->gobble(in);
996                         seqs[seq.getName()] = seq.getAligned();
997                 }
998                 
999                 in.close();
1000                 
1001                 //read namefile
1002                 vector<seqPriorityNode> nameMapCount;
1003                 int error = m->readNames(nameFile, nameMapCount, seqs);
1004                 
1005                 if (m->control_pressed) { return nameAbund; }
1006                 
1007                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1008                 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; }
1009
1010                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1011                 
1012                 string newFasta = fastaFile + ".temp";
1013                 ofstream out;
1014                 m->openOutputFile(newFasta, out);
1015                 
1016                 //print new file in order of
1017                 for (int i = 0; i < nameMapCount.size(); i++) {
1018                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1019                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1020                 }
1021                 out.close();
1022                 
1023                 rename(newFasta.c_str(), fastaFile.c_str());
1024                                 
1025                 return nameAbund;
1026                 
1027         }
1028         catch(exception& e) {
1029                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1030                 exit(1);
1031         }
1032 }
1033
1034 /**************************************************************************************************/
1035