require("minfi", quietly = TRUE)
require("ChIPseeker", quietly = TRUE)
require("ChIPpeakAnno", quietly = TRUE)
require("data.table", quietly = TRUE)


args <- commandArgs(trailingOnly = TRUE)
GSMTable = args[1]
IlmnTable = args[2]
gmTable = args[3]
cutoff = as.numeric(args[4])
clusterSize = as.numeric(args[5])
DMR = args[6]

#GSMTable<-("test-data/input.csv")
TAB = fread(GSMTable)
#IlmnTable <- ("test-data/IlmnTable.csv")
IlmnInfo = fread(IlmnTable)
#gmTable<-("test-data/gmTable.csv")
gmSet = fread(gmTable)

# bumphunter Run with processed data
designMatrix <- model.matrix( ~ TAB$Phenotype)

bumps <- bumphunter(
  as.matrix(gmSet),
  design = designMatrix,
  pos = IlmnInfo$BP,
  cutoff = cutoff,
  chr = IlmnInfo$CHR
)

# choose DMR's of a certain length threshold
DMRTable <- bumps$table[which(bumps$table$L >= clusterSize), ]
DMRInfo <- data.table(DMRTable$chr, DMRTable$start, DMRTable$end)


#DMR<-("test-data/DMR.bed")
write.table(
  DMRInfo,
  DMR,
  quote = F,
  sep = "\t",
  row.names = F,
  col.names = F
)
