#' @include procmod.frame.R
#' @include multivariate.R
#'
#' @import expm
#' @import MASS
#'
#' @author Christelle Gonindard-Melodelima
#' @author Eric Coissac
NULL

#' @export
null_varls_sim = function(mat1,mat2,nperm=100) {
  sd_mat1 = t(sqrt(colMeans(mat1^2) - colMeans(mat1)^2) %*% t(rep(1,nrow(mat1))))
  sd_mat2 = t(sqrt(colMeans(mat2^2) - colMeans(mat2)^2) %*% t(rep(1,nrow(mat2))))

  d_mat1 = dim(mat1)
  d_mat2 = dim(mat2)

  l_mat1 = prod(d_mat1)
  l_mat2 = prod(d_mat1)

  varls_alea = numeric(nperm)
  for (i in seq_along(varls_alea)) {

    rmat1 = tcrossprod(scale(array(rnorm(l_mat1),dim = d_mat1)) * sd_mat1)
    rmat2 = tcrossprod(scale(array(rnorm(l_mat2),dim = d_mat2)) * sd_mat2)
    varls_alea[i]=.Trace(sqrtm(rmat1 %*% rmat2))
  }

  return(MASS::fitdistr(Re(varls_alea),"normal")$estimate['mean'])
}
