setwd("/Users/alice/Desktop/VYZKUM/Hi-C/create_heatmap/to_compare")
filenames <- list.files(path = ".", pattern="*.txt", full.names=TRUE)

read_all_files_into_list_and_subset<-function(filenames){
  print(filenames)
  #for each filename, read file into a data frame and store a list of all data frames
  m<-lapply(filenames, function(x) {as.data.frame(read.table(x,header=TRUE,sep="\t"))})
  
  #dimensions of the existing dataframes
  sapply(m, function(x) {dim(x)})
  
  #what columns are shared among all data frames?
  mincol <- Reduce(intersect, lapply(m, colnames))
  #subsetting to the shared columns
  m<-lapply(m, function(x) x[mincol])
  
  #what rows are shared among all data frames?
  minrow <- Reduce(intersect, lapply(m, rownames))
  #subsetting to the shared rows
  m<-lapply(m, function(x) x[minrow,])
  
  #dimensions of the subsetted dataframes
  sapply(m, function(x) {dim(x)})
  
  return(m)
}

dfs<-read_all_files_into_list_and_subset(filenames)

#for each dataframe, calculate what is the x-th percentile of the values (most prominent interactions)
quantile_threshold<-sapply(dfs,function(x) {quantile(unlist(x),probs=c(0.9))})

binary_dfs<-list()
for (index in 1:length(dfs)) {
  print(index)
  binary_df<-dfs[[index]]>as.numeric(quantile_threshold[index])
  binary_dfs[[index]]<-as.data.frame(binary_df)
}

#join all dataframes together
#only true if true in all dataframes
#the interaction must be prominent in all datasets used
joined_dfs<-Reduce(function(d1, d2) (d1 & d2), binary_dfs)

columns_with_true_values<-t(t(apply(joined_dfs, 1, function(u) paste( names(which(u)), collapse=", " ))))
significant_interactions<-paste0(colnames(joined_dfs),": ",columns_with_true_values,"")
print(significant_interactions)
