# march 13, 2018
# function to reorder blast output by sequence identity
# includeDate: whether to include date in the filename.
reorderByIdentity <- function(taxMapFile, blastOutFile, returnObjects=F, includeDate=T){
	# if returnObjects, then return original and reordered data
	taxMap <- read.delim(taxMapFile, header=F, stringsAsFactors=F) 
	bres   <- read.delim(blastOutFile, header=F, stringsAsFactors=F) 
	# split by seq. id. Names are seq. ids! takes a bit
	bresList <- split(bres, f=bres[,1])
	# reorder by identity and write the top hit to out.
	out <- as.data.frame(cbind(otuID=rep(0, length(bresList)), spec=rep("bla", length(bresList))), eval=rep(0, length(bresList)), stringsAsFactors=F)

	for(i in 1: length(bresList)){
      	      idx <- order(bresList[[i]][,3], decreasing=T)
      	      bresList[[i]]  <- bresList[[i]][idx,]
      	      out[i, "otuID"] <- bresList[[i]][1,1]
      	      out[i, "spec"]  <- bresList[[i]][1,2]
      	      out[i, "eval"]  <- bresList[[i]][1,11]
	}

	# combine with tax information. 
	idxmap <- match(out$spec, taxMap[,1])
	repOut <- data.frame(out$otuID, taxMap[idxmap, 2], out$eval, out$spec)
	cat(paste0(nrow(repOut), " sequences assigned."))
	# prep outfile name. 
	outfile <- gsub("_blast[_a-z, 0-9]*.out", "", blastOutFile)
	if (includeDate){
		outfile <- paste(outfile, "_tax_ass_identity_", Sys.Date(), ".txt", sep="")
		}else{
		outfile <- paste(outfile, "_tax_ass_identity.txt", sep="")
		}
	#cat(outfile)
	 write.table(repOut, file=outfile, quote=F, row.names=F, col.names=F, sep="\t")
	if(returnObjects){
		results <- vector("list", 2)
		names(results) <- c("originalBlast", "reordered")
		results[[1]] <- bres
		results[[2]] <- repOut 
		return(results)
	}
	
}
