champ.load.mEPIC <- function (directory = getwd(), methValue = "B", filterDetP = TRUE, mEPIC =T, mEPIC.manifest = mEPIC.manifest,
                              detSamplecut = 0.2, detPcut = 0.01, removeDetP = 0, filterBeads = TRUE, 
                              beadCutoff = 0.05, filterNoCG = TRUE,  filterXY = TRUE, 
                              arraytype = "EPIC") 
{
  #For mEPIC specific filtering of bad samples the detSamplecut needs to be set at a value relevant 
  #to that expected number of probes to pass for that specific mouse strain
  
  message("[=================================]")
  message("[<<<< ChAMP.LOAD mEPIC START >>>>>]")
  message("-----------------------------------")
  message("Loading data from ", directory)
  myDir <- directory
  suppressWarnings(targets <- read.metharray.sheet(myDir))
  rgSet <- read.metharray.exp(targets = targets, extended = TRUE)
  
  if (arraytype == "EPIC") 
    rgSet@annotation <- c(array = "IlluminaHumanMethylationEPIC", 
                          annotation = "ilmn10.hg19")
  
  pd <- pData(rgSet)
  mset <- preprocessRaw(rgSet)
  detP <- detectionP(rgSet)
  detP.mEPIC <- detP[rownames(detP) %in% rownames(mEPIC.manifest), ]
  head(detP.mEPIC)
  
  message("<< Read DataSet Success. >>\n")
  message("The fraction of failed positions per sample\n \n            (You may need to delete samples with high proportion of failed probes\n): ")
  
  
  if(mEPIC)
  {
    numfail <- matrix(colMeans(detP.mEPIC > detPcut))
    rownames(numfail) <- pd$Sample_Name
    colnames(numfail) <- "Failed mEPIC CpG Fraction."
  }else{
    numfail <- matrix(colMeans(detP > detPcut))
    rownames(numfail) <- pd$Sample_Name
    colnames(numfail) <- "Failed CpG Fraction."
  }
  
  
  print(numfail)
  RemainSample <- which(numfail < detSamplecut)
  if (any(numfail >= detSamplecut)) 
    message("The detSamplecut parameter is : ", detSamplecut, 
            "\nSamples : ", paste(rownames(numfail)[which(numfail >= 
                                                            detSamplecut)], collapse = ","), " will be deleted.\n", 
            "There are ", length(RemainSample), " samples left for analysis.\n")
  rgSet <- rgSet[, RemainSample]
  detP <- detP[, RemainSample]
  mset <- mset[, RemainSample]
  pd <- pd[RemainSample, ]
  if (filterDetP) {
    mset.f = mset[rowSums(detP >= detPcut) <= removeDetP, ]
    
    if (removeDetP == 0) {
      message("Filtering probes with a detection p-value above ", 
              detPcut, " in one or more samples has removed ", 
              dim(mset)[1] - dim(mset.f)[1], " probes from the analysis. If a large number of probes have been removed, ChAMP suggests you to identify potentially bad samples.")
    }
    else {
      message("Filtering probes with a detection p-value above ", 
              detPcut, " in at least ", removeDetP * 100, 
              "% of samples has removed ", dim(mset)[1] - 
                dim(mset.f)[1], " probes from the analysis. If a large number of probes have been removed, ChAMP suggests you look at the failedSample.txt file to identify potentially bad samples.")
    }
    
    #######################
    #####----mEPIC----#####
    #######################
    
    #mEPIC.probes is a vector with probes names want to use in loading
    #Mset is a enviromentally locked set with a meth table and a unmeth table which is used of beta calculation
    #it is done on a probe by probe basis and the rgset is only used in normalization to get the NEGATIVE probes
    #which are different from the type 1 and type 2 probes
    
    if(mEPIC)
    {
      mset.f <- mset[rownames(mset) %in% rownames(mEPIC.manifest),]
    }
    #########################
    mset = mset.f
    
  }
  message("<< Filter DetP Done. >>\n")
  if (filterBeads) {
    if(mEPIC){
      bc = wateRmelon::beadcount(rgSet)
      bc = bc[rownames(bc) %in% rownames(mEPIC.manifest),]
    }else{
      bc = wateRmelon::beadcount(rgSet)
      
    }
    bc2 = bc[rowSums(is.na(bc)) < beadCutoff * (ncol(bc)), 
             ]
    mset.f2 = mset[featureNames(mset) %in% row.names(bc2), 
                   ]
    message("Filtering probes with a beadcount <3 in at least ", 
            beadCutoff * 100, "% of samples, has removed ", 
            dim(mset)[1] - dim(mset.f2)[1], " from the analysis.")
    mset = mset.f2
  }
  message("<< Filter Beads Done. >>\n")
  if (filterNoCG) {
    mset.f2 = dropMethylationLoci(mset, dropCH = T)
    message("Filtering non-cg probes, has removed ", dim(mset)[1] - 
              dim(mset.f2)[1], " from the analysis.")
    mset <- mset.f2
  }
  message("<< Filter NoCG Done. >>\n")
  
  if (filterXY) {
    if (arraytype == "EPIC") 
      data(probe.features.epic)
    else data(probe.features)
    autosomes = probe.features[!probe.features$CHR %in% 
                                 c("X", "Y"), ]
    if(mEPIC){
      autosomes = mEPIC.manifest[!mEPIC.manifest$mm10_CHR %in% c("X", "Y"), ]
      message("mEPIC in MM10CHR has 634 X or Y chromosome probes\n")
    }
    mset.f2 = mset[featureNames(mset) %in% row.names(autosomes),]
    message("Filtering probes on the X or Y chromosome has removed ", 
            dim(mset)[1] - dim(mset.f2)[1], " from the analysis.")
    mset = mset.f2
  }
  message("<< Filter XY chromosome Done. >>\n")
  if (methValue == "B") 
    beta.raw = getBeta(mset, "Illumina")
  else beta.raw = getM(mset)
  message(paste(if (methValue == "B") 
    "[Beta"
    else "[M", "value is selected as output.]\n"))
  intensity <- minfi::getMeth(mset) + minfi::getUnmeth(mset)
  detP <- detP[which(row.names(detP) %in% row.names(beta.raw)), 
               ]
  if (min(beta.raw, na.rm = TRUE) <= 0) 
    beta.raw[beta.raw <= 0] <- min(beta.raw[beta.raw > 0])
  message("Zeros in your dataset have been replaced with smallest positive value.\n")
  if (max(beta.raw, na.rm = TRUE) >= 0) 
    beta.raw[beta.raw >= 1] <- max(beta.raw[beta.raw < 1])
  colnames(beta.raw) <- pd$Sample_Name
  message("One in your dataset have been replaced with largest value below 1.\n")
  message("The analysis will be proceed with ", dim(beta.raw)[1], 
          " probes and ", dim(beta.raw)[2], " samples.\n")
  message("[<<<<< ChAMP.LOAD END >>>>>>]")
  message("[===========================]")
  message("[You may want to process champ.QC() next.]\n")
  
  return(list(mset = mset, rgSet = rgSet, pd = pd, intensity = intensity, 
              beta = beta.raw, detP = detP))
}
