## R script that takes set of multiple gene trees that can be multilabeled, and 
## Takes folloving argiments in exact order:
## 1 infile - file with gene trees in newick format
## 2 taxa_to_test - names of four taxa involved in the test in following order: hybrid, first parent, second parent, outgroup. 
##					For instance: chiloensis,vesca,iinumae,Drymocallis string specifies that trees and command files should be prepared to test scenario where chiloensis is a hybrid between vesca and iinumae using Drymocallis as an outgroup
## 3 pref - prefix for phylonet output files
## 4 seed - random seed  
## 5 command_outf - name of the command output file
## 6 bootstrap_th - gene trees bootstrap threshold. Edges in the gene trees that have support lower than threshold will be collapsed	




## Example:
## Rscript test_hybridizations_scripts/R_consensus_summary.r \
##		testing_hybridizations_input.txt \
##		chiloensis,vesca,iinumae,Drymocallis \
##		test_hybridization \
##		12345 \
##      commands_phylonet




#args=c("testing_hybridizations_input.txt", "chiloensis,vesca,iinumae,Drymocallis", "test_hybridization", "12345", "commands_phylonet")
args = commandArgs(trailingOnly=TRUE)


library(ape)

inf=args[1]
test=strsplit(args[2], ",")[[1]]
keyword=args[3]
seed=as.numeric(args[4])
command_outf=args[5]
bootstrap_th=args[6]


set.seed(seed)
seeds=round(runif(1000000, 1, 10000))


trees=scan(inf,  quiet = TRUE, what="character", sep="\n")
trees = read.tree(text = trees)

foo<-function(phy, include, seed)
{
	phy1=phy
	phy1=drop.tip(phy1, which(!phy1$tip.label %in% include))
	sps=unique(phy1$tip.label)
	d=c()
	for(sp in sps)
	{
		n_sp=length(phy1$tip.label[phy1$tip.label==sp])
		if(n_sp>5)
		{
			set.seed(seed)
			dr=sample(which(phy1$tip.label==sp), n_sp-5, replace=F)
			d=c(d, dr)
		}
	}
	phy1=drop.tip(phy1, d)

	tips_l=split(phy1$tip.label, as.factor(phy1$tip.label))
	tips_order=1:length(phy1$tip.label)
	tips_order_l=split(tips_order, as.factor(phy1$tip.label))

	tips=unlist(lapply(tips_l, function(x) paste(x[1], 1:length(x), sep="")))
	tips_order=unlist(tips_order_l)
	tips=tips[order(tips_order)]
	phy1$tip.label=as.character(tips)
	return(phy1)

}	
					


trees_edited=list()
for(i in 1:length(trees))
{
	if(i+1<length(seeds)){seed_i=seeds[i]}
	else{seed_i=seeds[i-length(seeds)+1]}
	trees_edited[[i]]=foo(phy=trees[[i]], include=test, seed=seed_i)
}

class(trees_edited) <- "multiPhylo"
trees_edited_v=write.tree(trees_edited)
k1=trees_edited[[1]]$tip.label
k1=sub("\\d+", "",k1, perl=T)
kk1=split(trees_edited[[1]]$tip.label, as.factor(k1))
kkk1=lapply(kk1,function(x) paste(names(x), ": ",paste(x, collapse=", "),  sep=""))
kkkk1=paste("  ",names(kkk1), unlist(kkk1), sep="")
	


nets=c(paste("((((",test[1],")#H1, ",test[2],"), (",test[3],", #H1)),",test[4],");", sep=""),
	paste("(((",test[1],", ",test[2],"), ",test[3],"),",test[4],");", sep=""),
	paste("(((",test[1],", ",test[3],"), ",test[2],"),",test[4],");", sep=""))

phylonet_param_1=paste("Tree g", c(1:length(trees_edited_v)), "=",trees_edited_v, sep="")
	
commands_all=c()	
for(n in 1:3)
{
	
	commands=c("#NEXUS\n", 
		"BEGIN NETWORKS;\n",
		paste("Network net = ", nets[n], sep=""),
		"\nEND;\n",
		"BEGIN TREES;\n", 
		phylonet_param_1, 
		"END;\n", 
		"BEGIN PHYLONET;\n", 
		paste("CalGTProb net (", paste(paste("g",c(1:length(trees_edited_v)), sep="" ), collapse=", "), ") -o -b ",bootstrap_th," -a <", paste(kkkk1, collapse="; "), ">;\n", sep=""), 
		"END;\n"
	)
	
	write(commands, paste(keyword,"_",n,"_phylonet.nex", sep=""))

	commands_all=c(commands_all, paste("java -Xmx2048m -jar $PATH_PHYLONET/PhyloNet_3.6.1.jar  ",keyword,"_",n,"_phylonet.nex > ",keyword,"_",n,"_phylonet.out", sep=""))
	
}


	
write(commands_all,	"commands_phylonet" )
	
	
	
	
	