#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
print(args)

library(stringr)

t1 <- as.data.frame(read.table(args[1]))  #load the bed files showing where contigs map on the reference
colnames(t1)<-c("chr","start","end","cluster_string","MAPQ","strand")

cluster_number<-str_match(t1$cluster, "CL\\s*(.*?)\\s*Contig")[,2] #extract the cluster number between strings CL and Contig
t1$Cluster<-cluster_number

t2 <- as.data.frame(read.table(args[2],skip=6,header=TRUE))  #load the CLUSTER_TABLE from the RepeatMasker

df <- merge(t1, t2, by.x=c("Cluster"), by.y=c("Cluster"), all.x=TRUE) #merge by the read id
df$cluster_string<-df$Automatic_annotation
df<-df[,1:7] #only keep first 7 columns of the bedfile

#print(head(df))

df$cluster_string<-basename(as.character(df$cluster_string)) #only keep the most detailed repeat annotation
stopifnot(length(rownames(t1))==length(rownames(df))) #we want to see all contigs in the output at this point in the pipeline

df<-df[!df$cluster_string == "All", ,] #remove the rows with "All" annotation as they are not informative

completerecords <- na.omit(df) 
completerecords<-completerecords[,c("chr","start","end","cluster_string","MAPQ","strand")]

completerecords<-completerecords[with(completerecords, order(chr, start)),] #sort by chromosome and start position

annotated_file_name<-str_replace(args[1],".bed",".annotated.bed")
print(annotated_file_name)
write.table(completerecords, file = annotated_file_name, sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE)
