`fdrperm` <-
function(pvals,mtdirection="stepup"){
#pvals<-pvs
    fdrcomp <- function(pv,pvsortobs,pvpa,nit){
        #pv <-0;nit<-2000;
        true <- length(pvsortobs[pvsortobs <= pv])
        fake <- length(pvpa[pvpa <= pv])/nit
        return(max(pv,fake/true))
        }


    pvalue <- pvals[[1]]
    pvpa <- pvals[[2]]
    niter <- ncol(pvpa)
    data.info <- pvals[[3]]
    ord <- order(pvalue)
    pvsortobs <- pvalue[ord]
    pvpa <- as.vector(pvpa)

    #niter<-nrow(pvpa)
    
    allfdr <- sapply(pvsortobs,fdrcomp,pvsortobs=pvsortobs,pvpa=pvpa,nit=niter)
    
    ##enforce monotonicity, step-down procedure####
    if(mtdirection=="stepdown"){
        allfdrmt <- c(allfdr[1])
        for(i in 2:length(allfdr)) {if (allfdr[i]<allfdrmt[i-1]) allfdrmt[i] <- allfdrmt[i-1] else allfdrmt[i] <- allfdr[i]}
        } else {
    ##enforce monotonicity, step-up procedure####
        el <- length(allfdr) 
        allfdrmt <- rep(NA,el)
        allfdrmt[el] <- c(allfdr[el])
        for(i in 1:(length(allfdr)-1)) {if (allfdr[el-i]>allfdrmt[el-i+1]) allfdrmt[el-i] <- allfdrmt[el-i+1] else allfdrmt[el-i] <- allfdr[el-i]}
        }
        
    #sort fdr according to index
    invord <- order(ord)
    fdr <- allfdrmt[invord]
    fdr <- sapply(fdr,function(x) min(x,1))
    
    
    
    fdrcutoff <- 1
    #pre <- "fdr1_"
    #donlysig <- datawithsig[fdr <= fdrcutoff,]
    fdrs <- cbind(data.info,pvalue,fdr)
    return(fdrs)
}

