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