## R script that takes set of multiple gene trees that can be multilabeled. Tips should be labeled with their relevant species names.
## Takes folloving argiments in exact order:
## 1 infile - file with gene trees in newick format
## 2 path_to_functions - path to the file with R_functions.R file supplied with the tutorial
## 3 bootstrap_th - gene trees bootstrap threshold. Edges in the gene trees that have support lower than threshold will be collapsed	
## 4 confidence - fraction of gene trees that has to contain a cluster for the cluser to be included into species network as reticulation event  
## 5 outfile - output file where species network in extended newick format will be written




## Example:
## Rscript test_hybridizations_scripts/R_consensus_summary.r \
##		testing_hybridizations_input.txt \
##		testing_hybridizations_scripts/R_functions.R \
##		5 \
##		0.30 \
##		test_hybridizations_consensus_out


#args=c("testing_hybridizations_input.txt", "testing_hybridizations_scripts/R_functions.R",	"5",	"0.30", "test_hybridizations_consensus_out")
args = commandArgs(trailingOnly=TRUE)
library(ape)
inf=args[1]
functions_file=args[2]
bootstrap_th = as.numeric(args[3])
confidence=as.numeric(args[4])
outf=args[5]


source(functions_file)
trees=scan(inf,  quiet = TRUE, what="character", sep="\n")
trees = read.tree(text = trees)
clusters = lapply(trees, getClusters, bTh=bootstrap_th)
k=netFromClusters(cls = clusters, th = confidence)
network=k$network_string
write(network, outf)


