args<-commandArgs(TRUE)
dist_file <- as.character(args[1])
CHROM <- as.character(args[2])
START <- as.character(args[3])
END <- as.character(args[4])
GAPLENGTH <- 0
dist <- read.table(dist_file, skip=1)
rownames(dist) <- dist[,1]
dist <- dist[,-1]
colnames(dist) <- rownames(dist)
dist_mtx <- apply(dist, c(1, 2), function(x) as.numeric(strsplit(x,"/")[[1]][1]))
GAPLENGTH <- unique(apply(dist, c(1, 2), function(x) as.numeric(strsplit(x,"/")[[1]][4])))[1]
tree <- tryCatch(ape::bionjs(as.dist(dist_mtx)),
    warning = function(war){return(paste0("WARNING: ", war))},
    error = function(err){return(paste0("ERROR: ", err))})
stop_if_error <- grep("ERROR:", tree)
if(length(stop_if_error)==0){
    write(paste0("#", CHROM, " ", START, " ", END, " ", GAPLENGTH), file=paste0(CHROM, ".trees"), append=TRUE)
    write(ape::write.tree(tree), file=paste0(CHROM, ".trees"), append=TRUE)
}
