#' @include internals.R
#' @import permute
#'
#' @author Christelle Gonindard-Melodelima
#' @author Eric Coissac
#'
NULL

#' Generate a permutation matrix using the permute package
#'
#' The code is copied from the \code{\link[vegan]{getPermuteMatrix}} internal function
#' of the \code{vegan} pakage. This is mainly a wrappoer around the functions of
#' the \code{permute} package.
#'
#' The permutation design is controled through the \code{\link[permute]{how}} function
#' of the \code{permute} package.
#'
#' @param perm a list of control values for the permutations
#'             as returned by the function how, or the number
#'             of permutations required, or a permutation
#'             matrix where each row gives the permuted indices.
#' @param N    number of elements to permute.
#'
#' @return a matrix of integer of size nperm x n. Each line corresponds to a
#'         permutation of n element
#'
#' @note Internal function do not use.
#'
#' @examples
#'     ProcMod:::.getPermuteMatrix(perm=how(nperm=5),N=10)
#'
#' @rdname internal.getPermuteMatrix
#'
#' @author Christelle Gonindard-Melodelima
#' @author Eric Coissac
#'
.getPermuteMatrix = function (perm, N)
{
    if (length(perm) == 1) {
        perm <- how(nperm = perm)
    }

    if (inherits(perm, "how"))
        perm <- shuffleSet(N, control = perm)
    else {
        if (!is.integer(perm) && !all(perm == round(perm)))
            stop("permutation matrix must be strictly integers: use round()")
    }
    if (is.null(attr(perm, "control")))
        attr(perm, "control") <- structure(list(within = list(type = "supplied matrix"),
            nperm = nrow(perm)), class = "how")
    perm
}
