]> git.donarmstrong.com Git - mothur.git/blob - aligncommand.cpp
update .gitignore
[mothur.git] / aligncommand.cpp
1 /*
2  *  aligncommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 5/15/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  *      This version of nast does everything I think that the greengenes nast server does and then some.  I have added the 
9  *      feature of allowing users to define their database, kmer size for searching, alignment penalty values and alignment 
10  *      method.  This latter feature is perhaps most significant.  nastPlus enables a user to use either a Needleman-Wunsch 
11  *      (non-affine gap penalty) or Gotoh (affine gap penalty) pairwise alignment algorithm.  This is significant because it
12  *      allows for a global alignment and not the local alignment provided by bLAst.  Furthermore, it has the potential to
13  *      provide a better alignment because of the banding method employed by blast (I'm not sure about this).
14  *
15  */
16
17 #include "aligncommand.h"
18 #include "referencedb.h"
19
20 //**********************************************************************************************************************
21 vector<string> AlignCommand::setParameters(){   
22         try {
23                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptemplate);
24                 CommandParameter pcandidate("fasta", "InputTypes", "", "", "none", "none", "none","fasta-alignreport-accnos",false,true,true); parameters.push_back(pcandidate);
25                 CommandParameter psearch("search", "Multiple", "kmer-blast-suffix", "kmer", "", "", "","",false,false,true); parameters.push_back(psearch);
26                 CommandParameter pksize("ksize", "Number", "", "8", "", "", "","",false,false); parameters.push_back(pksize);
27                 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "","",false,false); parameters.push_back(pmatch);
28                 CommandParameter palign("align", "Multiple", "needleman-gotoh-blast-noalign", "needleman", "", "", "","",false,false,true); parameters.push_back(palign);
29                 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "","",false,false); parameters.push_back(pmismatch);
30                 CommandParameter pgapopen("gapopen", "Number", "", "-5.0", "", "", "","",false,false); parameters.push_back(pgapopen);
31                 CommandParameter pgapextend("gapextend", "Number", "", "-2.0", "", "", "","",false,false); parameters.push_back(pgapextend);
32                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
33                 CommandParameter pflip("flip", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pflip);
34                 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
35                 CommandParameter pthreshold("threshold", "Number", "", "0.50", "", "", "","",false,false); parameters.push_back(pthreshold);
36                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
37                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
38
39                 vector<string> myArray;
40                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
41                 return myArray;
42         }
43         catch(exception& e) {
44                 m->errorOut(e, "AlignCommand", "setParameters");
45                 exit(1);
46         }
47 }
48 //**********************************************************************************************************************
49 string AlignCommand::getHelpString(){   
50         try {
51                 string helpString = "";
52                 helpString += "The align.seqs command reads a file containing sequences and creates an alignment file and a report file.";
53                 helpString += "The align.seqs command parameters are reference, fasta, search, ksize, align, match, mismatch, gapopen, gapextend and processors.";
54                 helpString += "The reference and fasta parameters are required. You may leave fasta blank if you have a valid fasta file. You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta.";
55                 helpString += "The search parameter allows you to specify the method to find most similar template.  Your options are: suffix, kmer and blast. The default is kmer.";
56                 helpString += "The align parameter allows you to specify the alignment method to use.  Your options are: gotoh, needleman, blast and noalign. The default is needleman.";
57                 helpString += "The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.";
58                 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.";
59                 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.";
60                 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -5.0.";
61                 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -2.0.";
62                 helpString += "The flip parameter is used to specify whether or not you want mothur to try the reverse complement if a sequence falls below the threshold.  The default is false.";
63                 helpString += "The threshold is used to specify a cutoff at which an alignment is deemed 'bad' and the reverse complement may be tried. The default threshold is 0.50, meaning 50% of the bases are removed in the alignment.";
64                 helpString += "If the flip parameter is set to true the reverse complement of the sequence is aligned and the better alignment is reported.";
65                 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.";
66                 helpString += "The default for the threshold parameter is 0.50, meaning at least 50% of the bases must remain or the sequence is reported as potentially reversed.";
67                 helpString += "The align.seqs command should be in the following format:";
68                 helpString += "align.seqs(reference=yourTemplateFile, fasta=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty)";
69                 helpString += "Example align.seqs(candidate=candidate.fasta, template=core.filtered, align=kmer, search=gotoh, ksize=8, match=2.0, mismatch=3.0, gapopen=-2.0, gapextend=-1.0)";
70                 helpString += "Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).";
71                 return helpString;
72         }
73         catch(exception& e) {
74                 m->errorOut(e, "AlignCommand", "getHelpString");
75                 exit(1);
76         }
77 }
78 //**********************************************************************************************************************
79 string AlignCommand::getOutputPattern(string type) {
80     try {
81         string pattern = "";
82         
83         if (type == "fasta") {  pattern = "[filename],align"; } //makes file like: amazon.align
84         else if (type == "alignreport") {  pattern = "[filename],align.report"; }
85         else if (type == "accnos") {  pattern = "[filename],flip.accnos"; }
86         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
87         
88         return pattern;
89     }
90     catch(exception& e) {
91         m->errorOut(e, "AlignCommand", "getOutputPattern");
92         exit(1);
93     }
94 }
95 //**********************************************************************************************************************
96 AlignCommand::AlignCommand(){   
97         try {
98                 abort = true; calledHelp = true; 
99                 setParameters();
100                 vector<string> tempOutNames;
101                 outputTypes["fasta"] = tempOutNames;
102                 outputTypes["alignreport"] = tempOutNames;
103                 outputTypes["accnos"] = tempOutNames;
104         }
105         catch(exception& e) {
106                 m->errorOut(e, "AlignCommand", "AlignCommand");
107                 exit(1);
108         }
109 }
110 //**********************************************************************************************************************
111 AlignCommand::AlignCommand(string option)  {
112         try {
113                 abort = false; calledHelp = false;
114                 ReferenceDB* rdb = ReferenceDB::getInstance();
115                 
116                 //allow user to run help
117                 if(option == "help") { help(); abort = true; calledHelp = true;}
118                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
119                 
120                 else {
121                         vector<string> myArray = setParameters();
122                         
123                         OptionParser parser(option);
124                         map<string, string> parameters = parser.getParameters(); 
125                         
126                         ValidParameters validParameter("align.seqs");
127                         map<string, string>::iterator it;
128                         
129                         //check to make sure all parameters are valid for command
130                         for (it = parameters.begin(); it != parameters.end(); it++) { 
131                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
132                         }
133                         
134                         //initialize outputTypes
135                         vector<string> tempOutNames;
136                         outputTypes["fasta"] = tempOutNames;
137                         outputTypes["alignreport"] = tempOutNames;
138                         outputTypes["accnos"] = tempOutNames;
139                         
140                         //if the user changes the output directory command factory will send this info to us in the output parameter 
141                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
142                         
143
144                         //if the user changes the input directory command factory will send this info to us in the output parameter 
145                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
146                         
147                         if (inputDir == "not found"){   inputDir = "";          }
148                         else {
149                                 string path;
150
151                                 it = parameters.find("reference");
152
153                                 //user has given a template file
154                                 if(it != parameters.end()){ 
155                                         path = m->hasPath(it->second);
156                                         //if the user has not given a path then, add inputdir. else leave path alone.
157                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
158                                 }
159                         }
160
161                         candidateFileName = validParameter.validFile(parameters, "fasta", false);
162                         if (candidateFileName == "not found") { 
163                                 //if there is a current fasta file, use it
164                                 string filename = m->getFastaFile(); 
165                                 if (filename != "") { candidateFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
166                                 else {  m->mothurOut("You have no current fastafile and the candidate parameter is required."); m->mothurOutEndLine(); abort = true; }
167                         }else { 
168                                 m->splitAtDash(candidateFileName, candidateFileNames);
169                                 
170                                 //go through files and make sure they are good, if not, then disregard them
171                                 for (int i = 0; i < candidateFileNames.size(); i++) {
172                                         //candidateFileNames[i] = m->getFullPathName(candidateFileNames[i]);
173                                         
174                                         bool ignore = false;
175                                         if (candidateFileNames[i] == "current") { 
176                                                 candidateFileNames[i] = m->getFastaFile(); 
177                                                 if (candidateFileNames[i] != "") {  m->mothurOut("Using " + candidateFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
178                                                 else {  
179                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
180                                                         //erase from file list
181                                                         candidateFileNames.erase(candidateFileNames.begin()+i);
182                                                         i--;
183                                                 }
184                                         }
185                                         
186                                         if (!ignore) {
187                                         
188                                                 if (inputDir != "") {
189                                                         string path = m->hasPath(candidateFileNames[i]);
190                                                         //if the user has not given a path then, add inputdir. else leave path alone.
191                                                         if (path == "") {       candidateFileNames[i] = inputDir + candidateFileNames[i];               }
192                                                 }
193                 
194                                                 int ableToOpen;
195                                                 ifstream in;
196                                                 ableToOpen = m->openInputFile(candidateFileNames[i], in, "noerror");
197                                                 in.close();     
198                                                 
199                                                 //if you can't open it, try default location
200                                                 if (ableToOpen == 1) {
201                                                         if (m->getDefaultPath() != "") { //default path is set
202                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(candidateFileNames[i]);
203                                                                 m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
204                                                                 ifstream in2;
205                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
206                                                                 in2.close();
207                                                                 candidateFileNames[i] = tryPath;
208                                                         }
209                                                 }
210                                                 
211                                                 //if you can't open it, try output location
212                                                 if (ableToOpen == 1) {
213                                                         if (m->getOutputDir() != "") { //default path is set
214                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(candidateFileNames[i]);
215                                                                 m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
216                                                                 ifstream in2;
217                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
218                                                                 in2.close();
219                                                                 candidateFileNames[i] = tryPath;
220                                                         }
221                                                 }
222                                                 
223                                                                                 
224
225                                                 if (ableToOpen == 1) { 
226                                                         m->mothurOut("Unable to open " + candidateFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
227                                                         //erase from file list
228                                                         candidateFileNames.erase(candidateFileNames.begin()+i);
229                                                         i--;
230                                                 }else {
231                                                         m->setFastaFile(candidateFileNames[i]);
232                                                 }
233                                         }
234                                 }
235                                 
236                                 //make sure there is at least one valid file left
237                                 if (candidateFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
238                         }
239                 
240                         //check for optional parameter and set defaults
241                         // ...at some point should added some additional type checking...
242                         string temp;
243                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
244                         m->mothurConvert(temp, kmerSize); 
245                         
246                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
247                         m->mothurConvert(temp, match);  
248                         
249                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
250                         m->mothurConvert(temp, misMatch);  
251                         
252                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-5.0";                  }
253                         m->mothurConvert(temp, gapOpen);  
254                         
255                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-2.0";                  }
256                         m->mothurConvert(temp, gapExtend); 
257                         
258                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
259                         m->setProcessors(temp);
260                         m->mothurConvert(temp, processors); 
261                         
262                         temp = validParameter.validFile(parameters, "flip", false);                     if (temp == "not found"){       temp = "f";                             }
263                         flip = m->isTrue(temp); 
264                         
265                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
266                         save = m->isTrue(temp); 
267                         rdb->save = save; 
268                         if (save) { //clear out old references
269                                 rdb->clearMemory();
270                         }
271                         
272                         //this has to go after save so that if the user sets save=t and provides no reference we abort
273                         templateFileName = validParameter.validFile(parameters, "reference", true);
274                         if (templateFileName == "not found") { 
275                                 //check for saved reference sequences
276                                 if (rdb->referenceSeqs.size() != 0) {
277                                         templateFileName = "saved";
278                                 }else {
279                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required for the align.seqs command."); 
280                                         m->mothurOutEndLine();
281                                         abort = true; 
282                                 }
283                         }else if (templateFileName == "not open") { abort = true; }     
284                         else {  if (save) {     rdb->setSavedReference(templateFileName);       }       }
285                         
286                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found"){       temp = "0.50";                  }
287                         m->mothurConvert(temp, threshold); 
288                         
289                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
290                         if ((search != "suffix") && (search != "kmer") && (search != "blast")) { m->mothurOut("invalid search option: choices are kmer, suffix or blast."); m->mothurOutEndLine(); abort=true; }
291                         
292                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }
293                         if ((align != "needleman") && (align != "gotoh") && (align != "blast") && (align != "noalign")) { m->mothurOut("invalid align option: choices are needleman, gotoh, blast or noalign."); m->mothurOutEndLine(); abort=true; }
294
295                 }
296                 
297         }
298         catch(exception& e) {
299                 m->errorOut(e, "AlignCommand", "AlignCommand");
300                 exit(1);
301         }
302 }
303 //**********************************************************************************************************************
304 AlignCommand::~AlignCommand(){  
305
306         if (abort == false) {
307                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
308                 delete templateDB;
309         }
310 }
311 //**********************************************************************************************************************
312
313 int AlignCommand::execute(){
314         try {
315                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
316
317                 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, rand());
318                 
319                 for (int s = 0; s < candidateFileNames.size(); s++) {
320                         if (m->control_pressed) { outputTypes.clear(); return 0; }
321                         
322                         m->mothurOut("Aligning sequences from " + candidateFileNames[s] + " ..." ); m->mothurOutEndLine();
323                         
324                         if (outputDir == "") {  outputDir += m->hasPath(candidateFileNames[s]); }
325             map<string, string> variables; variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(candidateFileNames[s]));
326                         string alignFileName = getOutputFileName("fasta", variables);  
327                         string reportFileName = getOutputFileName("alignreport", variables);
328                         string accnosFileName = getOutputFileName("accnos", variables);
329             
330                         bool hasAccnos = true;
331                         
332                         int numFastaSeqs = 0;
333                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
334                         int start = time(NULL);
335                 
336 #ifdef USE_MPI  
337                                 int pid, numSeqsPerProcessor; 
338                                 int tag = 2001;
339                                 vector<unsigned long long> MPIPos;
340                                 MPIWroteAccnos = false;
341                         
342                                 MPI_Status status; 
343                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
344                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
345
346                                 MPI_File inMPI;
347                                 MPI_File outMPIAlign;
348                                 MPI_File outMPIReport;
349                                 MPI_File outMPIAccnos;
350                                 
351                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
352                                 int inMode=MPI_MODE_RDONLY; 
353                                 
354                                 char outAlignFilename[1024];
355                                 strcpy(outAlignFilename, alignFileName.c_str());
356                                 
357                                 char outReportFilename[1024];
358                                 strcpy(outReportFilename, reportFileName.c_str());
359                                 
360                                 char outAccnosFilename[1024];
361                                 strcpy(outAccnosFilename, accnosFileName.c_str());
362                                 
363                                 char inFileName[1024];
364                                 strcpy(inFileName, candidateFileNames[s].c_str());
365                                 
366                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
367                                 MPI_File_open(MPI_COMM_WORLD, outAlignFilename, outMode, MPI_INFO_NULL, &outMPIAlign);
368                                 MPI_File_open(MPI_COMM_WORLD, outReportFilename, outMode, MPI_INFO_NULL, &outMPIReport);
369                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
370                                 
371                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
372                                 
373                                 if (pid == 0) { //you are the root process 
374                                         
375                                         MPIPos = m->setFilePosFasta(candidateFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
376                                         
377                                         //send file positions to all processes
378                                         for(int i = 1; i < processors; i++) { 
379                                                 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
380                                                 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
381                                         }
382                                         
383                                         //figure out how many sequences you have to align
384                                         numSeqsPerProcessor = numFastaSeqs / processors;
385                                         int startIndex =  pid * numSeqsPerProcessor;
386                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
387                                         
388                                         //align your part
389                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
390                                         
391                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
392
393                                         for (int i = 1; i < processors; i++) {
394                                                 bool tempResult;
395                                                 MPI_Recv(&tempResult, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
396                                                 if (tempResult != 0) { MPIWroteAccnos = true; }
397                                         }
398                                 }else{ //you are a child process
399                                         MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
400                                         MPIPos.resize(numFastaSeqs+1);
401                                         MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
402
403                                         
404                                         //figure out how many sequences you have to align
405                                         numSeqsPerProcessor = numFastaSeqs / processors;
406                                         int startIndex =  pid * numSeqsPerProcessor;
407                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
408                                         
409                                         
410                                         //align your part
411                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
412                                         
413                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
414
415                                         MPI_Send(&MPIWroteAccnos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); 
416                                 }
417                                 
418                                 //close files 
419                                 MPI_File_close(&inMPI);
420                                 MPI_File_close(&outMPIAlign);
421                                 MPI_File_close(&outMPIReport);
422                                 MPI_File_close(&outMPIAccnos);
423                                 
424                                 //delete accnos file if blank
425                                 if (pid == 0) {
426                                         //delete accnos file if its blank else report to user
427                                         if (MPIWroteAccnos) { 
428                                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
429                                                 if (!flip) {
430                                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); 
431                                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }
432                                                 m->mothurOutEndLine();
433                                         }else { 
434                                                 //MPI_Info info;
435                                                 //MPI_File_delete(outAccnosFilename, info);
436                                                 hasAccnos = false;      
437                                                 m->mothurRemove(accnosFileName); 
438                                         }
439                                 }
440                                 
441 #else
442
443                         vector<unsigned long long> positions; 
444                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
445                         positions = m->divideFile(candidateFileNames[s], processors);
446                         for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(new linePair(positions[i], positions[(i+1)]));  }
447                 #else
448                         if (processors == 1) {
449                                 lines.push_back(new linePair(0, 1000));
450                         }else {
451                                 positions = m->setFilePosFasta(candidateFileNames[s], numFastaSeqs); 
452                                 if (positions.size() < processors) { processors = positions.size(); }
453                 
454                                 //figure out how many sequences you have to process
455                                 int numSeqsPerProcessor = numFastaSeqs / processors;
456                                 for (int i = 0; i < processors; i++) {
457                                         int startIndex =  i * numSeqsPerProcessor;
458                                         if(i == (processors - 1)){      numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;   }
459                                         lines.push_back(new linePair(positions[startIndex], numSeqsPerProcessor));
460                                 }
461                         }
462                 #endif
463                         
464                         if(processors == 1){
465                                 numFastaSeqs = driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
466                         }else{
467                                 numFastaSeqs = createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]); 
468                         }
469                                 
470                         if (m->control_pressed) { m->mothurRemove(accnosFileName); m->mothurRemove(alignFileName); m->mothurRemove(reportFileName); outputTypes.clear();  return 0; }
471                         
472                         //delete accnos file if its blank else report to user
473                         if (m->isBlank(accnosFileName)) {  m->mothurRemove(accnosFileName);  hasAccnos = false; }
474                         else { 
475                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
476                                 if (!flip) {
477                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); 
478                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }
479                                 m->mothurOutEndLine();
480                         }
481
482 #endif          
483
484
485                 #ifdef USE_MPI
486                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
487                                         
488                         if (pid == 0) { //only one process should output to screen
489                 #endif
490
491                         outputNames.push_back(alignFileName); outputTypes["fasta"].push_back(alignFileName);
492                         outputNames.push_back(reportFileName); outputTypes["alignreport"].push_back(reportFileName);
493                         if (hasAccnos)  {       outputNames.push_back(accnosFileName);  outputTypes["accnos"].push_back(accnosFileName);  }
494                         
495                 #ifdef USE_MPI
496                         }
497                 #endif
498
499                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");
500                         m->mothurOutEndLine();
501                         m->mothurOutEndLine();
502                 }
503                 
504                 //set align file as new current fastafile
505                 string currentFasta = "";
506                 itTypes = outputTypes.find("fasta");
507                 if (itTypes != outputTypes.end()) {
508                         if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
509                 }
510                 
511                 m->mothurOutEndLine();
512                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
513                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
514                 m->mothurOutEndLine();
515
516                 return 0;
517         }
518         catch(exception& e) {
519                 m->errorOut(e, "AlignCommand", "execute");
520                 exit(1);
521         }
522 }
523
524 //**********************************************************************************************************************
525 int AlignCommand::driver(linePair* filePos, string alignFName, string reportFName, string accnosFName, string filename){
526         try {
527                 ofstream alignmentFile;
528                 m->openOutputFile(alignFName, alignmentFile);
529                 
530                 ofstream accnosFile;
531                 m->openOutputFile(accnosFName, accnosFile);
532                 
533                 NastReport report(reportFName);
534                 
535                 ifstream inFASTA;
536                 m->openInputFile(filename, inFASTA);
537
538                 inFASTA.seekg(filePos->start);
539
540                 bool done = false;
541                 int count = 0;
542                 
543                 //moved this into driver to avoid deep copies in windows paralellized version
544                 Alignment* alignment;
545                 int longestBase = templateDB->getLongestBase();
546         if (m->debug) { m->mothurOut("[DEBUG]: template longest base = "  + toString(templateDB->getLongestBase()) + " \n"); }
547                 if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }
548                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }
549                 else if(align == "blast")               {       alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch);            }
550                 else if(align == "noalign")             {       alignment = new NoAlign();                                                                                                      }
551                 else {
552                         m->mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
553                         m->mothurOutEndLine();
554                         alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
555                 }
556         
557                 while (!done) {
558                         
559                         if (m->control_pressed) {  break; }
560                         
561                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
562                         report.setCandidate(candidateSeq);
563
564                         int origNumBases = candidateSeq->getNumBases();
565                         string originalUnaligned = candidateSeq->getUnaligned();
566                         int numBasesNeeded = origNumBases * threshold;
567         
568                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
569                                 if (candidateSeq->getUnaligned().length()+1 > alignment->getnRows()) {
570                     if (m->debug) { m->mothurOut("[DEBUG]: " + candidateSeq->getName() + " " + toString(candidateSeq->getUnaligned().length()) + " " + toString(alignment->getnRows()) + " \n"); }
571                                         alignment->resize(candidateSeq->getUnaligned().length()+2);
572                                 }
573                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);
574                                 Sequence* templateSeq = new Sequence(temp.getName(), temp.getAligned());
575                                 
576                                 float searchScore = templateDB->getSearchScore();
577                                                                 
578                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
579                 
580                                 Sequence* copy;
581                                 
582                                 Nast* nast2;
583                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below
584                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
585                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
586                                                                                                 //so this bool tells you if you need to delete it
587                                                                                                 
588                                 //if there is a possibility that this sequence should be reversed
589                                 if (candidateSeq->getNumBases() < numBasesNeeded) {
590                                         
591                                         string wasBetter =  "";
592                                         //if the user wants you to try the reverse
593                                         if (flip) {
594                                 
595                                                 //get reverse compliment
596                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
597                                                 copy->reverseComplement();
598                         
599                         if (m->debug) { m->mothurOut("[DEBUG]: flipping "  + candidateSeq->getName() + " \n"); }
600                                                 
601                                                 //rerun alignment
602                                                 Sequence temp2 = templateDB->findClosestSequence(copy);
603                                                 Sequence* templateSeq2 = new Sequence(temp2.getName(), temp2.getAligned());
604                         
605                         if (m->debug) { m->mothurOut("[DEBUG]: closest template "  + temp2.getName() + " \n"); }
606                                                 
607                                                 searchScore = templateDB->getSearchScore();
608                                                 
609                                                 nast2 = new Nast(alignment, copy, templateSeq2);
610                         
611                         if (m->debug) { m->mothurOut("[DEBUG]: completed Nast2 "  + candidateSeq->getName() + " flipped numBases = " + toString(copy->getNumBases()) + " old numbases = " + toString(candidateSeq->getNumBases()) +" \n"); }
612                         
613                                                 //check if any better
614                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {
615                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better
616                             delete templateSeq;
617                                                         templateSeq = templateSeq2;
618                                                         delete nast;
619                                                         nast = nast2;
620                                                         needToDeleteCopy = true;
621                                                         wasBetter = "\treverse complement produced a better alignment, so mothur used the reverse complement.";
622                                                 }else{  
623                                                         wasBetter = "\treverse complement did NOT produce a better alignment so it was not used, please check sequence.";
624                                                         delete nast2;
625                             delete templateSeq2;
626                                                         delete copy;    
627                                                 }
628                         if (m->debug) { m->mothurOut("[DEBUG]: done.\n"); }
629                                         }
630                                         
631                                         //create accnos file with names
632                                         accnosFile << candidateSeq->getName() << wasBetter << endl;
633                                 }
634                                 
635                                 report.setTemplate(templateSeq);
636                                 report.setSearchParameters(search, searchScore);
637                                 report.setAlignmentParameters(align, alignment);
638                                 report.setNastParameters(*nast);
639         
640                                 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;
641                                 
642                                 report.print();
643                                 delete nast;
644                 delete templateSeq;
645                                 if (needToDeleteCopy) {   delete copy;   }
646                                 
647                                 count++;
648                         }
649                         delete candidateSeq;
650                         
651                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
652                                 unsigned long long pos = inFASTA.tellg();
653                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
654                         #else
655                                 if (inFASTA.eof()) { break; }
656                         #endif
657                         
658                         //report progress
659                         if((count) % 100 == 0){ m->mothurOutJustToScreen(toString(count) + "\n");               }
660                         
661                 }
662                 //report progress
663                 if((count) % 100 != 0){ m->mothurOutJustToScreen(toString(count) + "\n");               }
664                 
665                 delete alignment;
666                 alignmentFile.close();
667                 inFASTA.close();
668                 accnosFile.close();
669                 
670                 return count;
671         }
672         catch(exception& e) {
673                 m->errorOut(e, "AlignCommand", "driver");
674                 exit(1);
675         }
676 }
677 //**********************************************************************************************************************
678 #ifdef USE_MPI
679 int AlignCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& alignFile, MPI_File& reportFile, MPI_File& accnosFile, vector<unsigned long long>& MPIPos){
680         try {
681                 string outputString = "";
682                 MPI_Status statusReport; 
683                 MPI_Status statusAlign; 
684                 MPI_Status statusAccnos; 
685                 MPI_Status status; 
686                 int pid;
687                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
688         
689                 NastReport report;
690                 
691                 if (pid == 0) {
692                         outputString = report.getHeaders();
693                         int length = outputString.length();
694             
695                         char* buf = new char[length];
696                         memcpy(buf, outputString.c_str(), length);
697                 
698                         MPI_File_write_shared(reportFile, buf, length, MPI_CHAR, &statusReport);
699
700             delete buf;
701                 }
702                 
703                 Alignment* alignment;
704                 int longestBase = templateDB->getLongestBase();
705                 if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }
706                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }
707                 else if(align == "blast")               {       alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch);            }
708                 else if(align == "noalign")             {       alignment = new NoAlign();                                                                                                      }
709                 else {
710                         m->mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
711                         m->mothurOutEndLine();
712                         alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
713                 }
714                 
715                 
716                 for(int i=0;i<num;i++){
717                 
718                         if (m->control_pressed) { delete alignment; return 0; }
719
720                         //read next sequence
721                         int length = MPIPos[start+i+1] - MPIPos[start+i];
722
723                         char* buf4 = new char[length];
724                         //memcpy(buf4, outputString.c_str(), length);
725
726                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
727                         
728                         string tempBuf = buf4;
729
730                         delete buf4;
731
732                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
733         
734                         istringstream iss (tempBuf,istringstream::in);
735
736                         Sequence* candidateSeq = new Sequence(iss);  
737                         report.setCandidate(candidateSeq);
738
739                         int origNumBases = candidateSeq->getNumBases();
740                         string originalUnaligned = candidateSeq->getUnaligned();
741                         int numBasesNeeded = origNumBases * threshold;
742         
743                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
744                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
745                                         alignment->resize(candidateSeq->getUnaligned().length()+1);
746                                 }
747                                                                 
748                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);
749                                 Sequence* templateSeq = new Sequence(temp.getName(), temp.getAligned());
750                                 
751                                 float searchScore = templateDB->getSearchScore();
752                                                                 
753                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
754                                 Sequence* copy;
755                                 
756                                 Nast* nast2;
757                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below
758                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
759                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
760                                                                                                 //so this bool tells you if you need to delete it
761                                                                                                 
762                                 //if there is a possibility that this sequence should be reversed
763                                 if (candidateSeq->getNumBases() < numBasesNeeded) {
764                                         
765                                         string wasBetter = "";
766                                         //if the user wants you to try the reverse
767                                         if (flip) {
768                                                 //get reverse compliment
769                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
770                                                 copy->reverseComplement();
771                                                 
772                                                 //rerun alignment
773                                                 Sequence temp2 = templateDB->findClosestSequence(copy);
774                                                 Sequence* templateSeq2 = new Sequence(temp2.getName(), temp2.getAligned());
775                                                 
776                                                 searchScore = templateDB->getSearchScore();
777                                                 
778                                                 nast2 = new Nast(alignment, copy, templateSeq2);
779                         
780                                                 //check if any better
781                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {
782                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better
783                                                         delete templateSeq;
784                                                         templateSeq = templateSeq2;
785                                                         delete nast;
786                                                         nast = nast2;
787                                                         needToDeleteCopy = true;
788                                                         wasBetter = "\treverse complement produced a better alignment, so mothur used the reverse complement.";
789                                                 }else{  
790                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";
791                                                         delete nast2;
792                             delete templateSeq2;
793                                                         delete copy;    
794                                                 }
795                                         }
796                                         
797                                         //create accnos file with names
798                                         outputString = candidateSeq->getName() + wasBetter + "\n";
799                                         
800                                         //send results to parent
801                                         int length = outputString.length();
802
803                                         char* buf = new char[length];
804                                         memcpy(buf, outputString.c_str(), length);
805                                 
806                                         MPI_File_write_shared(accnosFile, buf, length, MPI_CHAR, &statusAccnos);
807                                         delete buf;
808                                         MPIWroteAccnos = true;
809                                 }
810                                 
811                                 report.setTemplate(templateSeq);
812                                 report.setSearchParameters(search, searchScore);
813                                 report.setAlignmentParameters(align, alignment);
814                                 report.setNastParameters(*nast);
815         
816                                 outputString =  ">" + candidateSeq->getName() + "\n" + candidateSeq->getAligned() + "\n";
817                                 
818                                 //send results to parent
819                                 int length = outputString.length();
820                                 char* buf2 = new char[length];
821                                 memcpy(buf2, outputString.c_str(), length);
822                                 
823                                 MPI_File_write_shared(alignFile, buf2, length, MPI_CHAR, &statusAlign);
824                                 
825                                 delete buf2;
826
827                                 outputString = report.getReport();
828                                 
829                                 //send results to parent
830                                 length = outputString.length();
831                                 char* buf3 = new char[length];
832                                 memcpy(buf3, outputString.c_str(), length);
833                                 
834                                 MPI_File_write_shared(reportFile, buf3, length, MPI_CHAR, &statusReport);
835                                 
836                                 delete buf3;
837                                 delete nast;
838                 delete templateSeq;
839                                 if (needToDeleteCopy) {   delete copy;   }
840                         }
841                         delete candidateSeq;
842                         
843                         //report progress
844                         if((i+1) % 100 == 0){   cout << (toString(i+1)) << endl;                }
845                 }
846                 //report progress
847                 if((num) % 100 != 0){   cout << (toString(num)) << endl;                }
848                 
849                 return 1;
850         }
851         catch(exception& e) {
852                 m->errorOut(e, "AlignCommand", "driverMPI");
853                 exit(1);
854         }
855 }
856 #endif
857 /**************************************************************************************************/
858
859 int AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {
860         try {
861                 int num = 0;
862                 processIDS.resize(0);
863         bool recalc = false;
864         
865 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
866                 int process = 1;
867                 
868                 //loop through and create all the processes you want
869                 while (process != processors) {
870                         pid_t pid = fork();
871                         
872                         if (pid > 0) {
873                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
874                                 process++;
875                         }else if (pid == 0){
876                                 num = driver(lines[process], alignFileName + toString(m->mothurGetpid(process)) + ".temp", reportFileName + toString(m->mothurGetpid(process)) + ".temp", accnosFName + m->mothurGetpid(process) + ".temp", filename);
877                                 
878                                 //pass numSeqs to parent
879                                 ofstream out;
880                                 string tempFile = alignFileName + toString(m->mothurGetpid(process)) + ".num.temp";
881                                 m->openOutputFile(tempFile, out);
882                                 out << num << endl;
883                                 out.close();
884                                 
885                                 exit(0);
886                         }else { 
887                                 m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process;
888                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
889                 recalc = true;
890                                 break;
891                         }
892                 }
893                 
894         if (recalc) {
895             for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
896             vector<unsigned long long> positions;
897                         positions = m->divideFile(filename, processors);
898                         for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(new linePair(positions[i], positions[(i+1)]));  }
899             
900             num = 0;
901             processIDS.resize(0);
902             process = 1;
903             
904             while (process != processors) {
905                 pid_t pid = fork();
906                 
907                 if (pid > 0) {
908                     processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
909                     process++;
910                 }else if (pid == 0){
911                     num = driver(lines[process], alignFileName + toString(m->mothurGetpid(process)) + ".temp", reportFileName + toString(m->mothurGetpid(process)) + ".temp", accnosFName + m->mothurGetpid(process) + ".temp", filename);
912                     
913                     //pass numSeqs to parent
914                     ofstream out;
915                     string tempFile = alignFileName + toString(m->mothurGetpid(process)) + ".num.temp";
916                     m->openOutputFile(tempFile, out);
917                     out << num << endl;
918                     out.close();
919                     
920                     exit(0);
921                 }else {
922                     m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
923                     for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
924                     exit(0);
925                 }
926             }
927         }
928         
929                 //do my part
930                 num = driver(lines[0], alignFileName, reportFileName, accnosFName, filename);
931                 
932                 //force parent to wait until all the processes are done
933                 for (int i=0;i<processIDS.size();i++) { 
934                         int temp = processIDS[i];
935                         wait(&temp);
936                 }
937                 
938                 vector<string> nonBlankAccnosFiles;
939                 if (!(m->isBlank(accnosFName))) { nonBlankAccnosFiles.push_back(accnosFName); }
940                 else { m->mothurRemove(accnosFName); } //remove so other files can be renamed to it
941                         
942                 for (int i = 0; i < processIDS.size(); i++) {
943                         ifstream in;
944                         string tempFile =  alignFileName + toString(processIDS[i]) + ".num.temp";
945                         m->openInputFile(tempFile, in);
946                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
947                         in.close(); m->mothurRemove(tempFile);
948                         
949                         m->appendFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);
950                         m->mothurRemove((alignFileName + toString(processIDS[i]) + ".temp"));
951                         
952                         appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);
953                         m->mothurRemove((reportFileName + toString(processIDS[i]) + ".temp"));
954                         
955                         if (!(m->isBlank(accnosFName + toString(processIDS[i]) + ".temp"))) {
956                                 nonBlankAccnosFiles.push_back(accnosFName + toString(processIDS[i]) + ".temp");
957                         }else { m->mothurRemove((accnosFName + toString(processIDS[i]) + ".temp"));  }
958                         
959                 }
960                 
961                 //append accnos files
962                 if (nonBlankAccnosFiles.size() != 0) { 
963                         rename(nonBlankAccnosFiles[0].c_str(), accnosFName.c_str());
964                         
965                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
966                                 m->appendFiles(nonBlankAccnosFiles[h], accnosFName);
967                                 m->mothurRemove(nonBlankAccnosFiles[h]);
968                         }
969                 }else { //recreate the accnosfile if needed
970                         ofstream out;
971                         m->openOutputFile(accnosFName, out);
972                         out.close();
973                 }
974 #else
975                 //////////////////////////////////////////////////////////////////////////////////////////////////////
976                 //Windows version shared memory, so be careful when passing variables through the alignData struct. 
977                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
978                 //////////////////////////////////////////////////////////////////////////////////////////////////////
979                 
980                 vector<alignData*> pDataArray; 
981                 DWORD   dwThreadIdArray[processors-1];
982                 HANDLE  hThreadArray[processors-1]; 
983                 
984                 //Create processor worker threads.
985                 for( int i=0; i<processors-1; i++ ){
986                         //copy templateDb
987                         //AlignmentDB* tempDB = new AlignmentDB(*templateDB);
988                         
989                         // Allocate memory for thread data.
990                         string extension = "";
991                         if (i != 0) { extension = toString(i) + ".temp"; }
992                         
993                         alignData* tempalign = new alignData(templateFileName, (alignFileName + extension), (reportFileName + extension), (accnosFName + extension), filename, align, search, kmerSize, m, lines[i]->start, lines[i]->end, flip, match, misMatch, gapOpen, gapExtend, threshold, i);
994                         pDataArray.push_back(tempalign);
995                         processIDS.push_back(i);
996                                 
997                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
998                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
999                         hThreadArray[i] = CreateThread(NULL, 0, MyAlignThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
1000                 }
1001                 
1002                 //need to check for line ending error
1003                 ifstream inFASTA;
1004                 m->openInputFile(filename, inFASTA);
1005                 inFASTA.seekg(lines[processors-1]->start-1);
1006                 char c = inFASTA.peek();
1007                 
1008                 if (c != '>') { //we need to move back
1009                         lines[processors-1]->start--; 
1010                 }
1011                 
1012                 //using the main process as a worker saves time and memory
1013                 //do my part - do last piece because windows is looking for eof
1014                 num = driver(lines[processors-1], (alignFileName + toString(processors-1) + ".temp"), (reportFileName + toString(processors-1) + ".temp"), (accnosFName + toString(processors-1) + ".temp"), filename);
1015                 
1016                 //Wait until all threads have terminated.
1017                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1018                 
1019                 //Close all thread handles and free memory allocations.
1020                 for(int i=0; i < pDataArray.size(); i++){
1021             if (pDataArray[i]->count != pDataArray[i]->end) {
1022                 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; 
1023             }
1024                         num += pDataArray[i]->count;
1025                         CloseHandle(hThreadArray[i]);
1026                         delete pDataArray[i];
1027                 }
1028                 
1029                 vector<string> nonBlankAccnosFiles;
1030                 if (!(m->isBlank(accnosFName))) { nonBlankAccnosFiles.push_back(accnosFName); }
1031                 else { m->mothurRemove(accnosFName); } //remove so other files can be renamed to it
1032                 
1033                 for (int i = 1; i < processors; i++) {
1034                         m->appendFiles((alignFileName + toString(i) + ".temp"), alignFileName);
1035                         m->mothurRemove((alignFileName + toString(i) + ".temp"));
1036                         
1037                         appendReportFiles((reportFileName + toString(i) + ".temp"), reportFileName);
1038                         m->mothurRemove((reportFileName + toString(i) + ".temp"));
1039                         
1040                         if (!(m->isBlank(accnosFName + toString(i) + ".temp"))) {
1041                                 nonBlankAccnosFiles.push_back(accnosFName + toString(i) + ".temp");
1042                         }else { m->mothurRemove((accnosFName + toString(i) + ".temp"));  }
1043                 }
1044                 
1045                 //append accnos files
1046                 if (nonBlankAccnosFiles.size() != 0) { 
1047                         rename(nonBlankAccnosFiles[0].c_str(), accnosFName.c_str());
1048                         
1049                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
1050                                 m->appendFiles(nonBlankAccnosFiles[h], accnosFName);
1051                                 m->mothurRemove(nonBlankAccnosFiles[h]);
1052                         }
1053                 }else { //recreate the accnosfile if needed
1054                         ofstream out;
1055                         m->openOutputFile(accnosFName, out);
1056                         out.close();
1057                 }       
1058 #endif  
1059                 
1060                 return num;
1061         }
1062         catch(exception& e) {
1063                 m->errorOut(e, "AlignCommand", "createProcesses");
1064                 exit(1);
1065         }
1066 }
1067 //**********************************************************************************************************************
1068
1069 void AlignCommand::appendReportFiles(string temp, string filename) {
1070         try{
1071                 
1072                 ofstream output;
1073                 ifstream input;
1074                 m->openOutputFileAppend(filename, output);
1075                 m->openInputFile(temp, input);
1076
1077                 while (!input.eof())    {       char c = input.get(); if (c == 10 || c == 13){  break;  }       } // get header line
1078                                 
1079         char buffer[4096];        
1080         while (!input.eof()) {
1081             input.read(buffer, 4096);
1082             output.write(buffer, input.gcount());
1083         }
1084                 
1085                 input.close();
1086                 output.close();
1087         }
1088         catch(exception& e) {
1089                 m->errorOut(e, "AlignCommand", "appendReportFiles");
1090                 exit(1);
1091         }
1092 }
1093 //**********************************************************************************************************************