#' @import mvtnorm
#'
NULL

#' Simulate n points of dimension p.
#'
#' Points are simulated using the \code{\link[mvtnorm]{rmvnorm}} from
#' the \code{mvtnorm}. The mean of each dimension is set to 0 and all
#' the variances to 1 with all the covariances set to 0.
#'
#' @export
simulate_matrix = function(n,p,method = "chol") {
  new = rmvnorm(n,rep(0,p),method = method)

  new.sd = as.numeric(sqrt(varls(new,permutations=NULL)))

  new = new/new.sd

  return(new)
}

#' Simulate n points of dimension p correlated with a reference matrix.
#'
#' @export
simulate_correlation = function(reference,p,r2,method = "chol") {
  n = nrow(reference)
  maxdim = max(ncol(reference),p)

  noise = simulate_matrix(n,p,method = method)

  if (maxdim == p && maxdim > ncol(reference)) {
    temp = reference
    reference = noise
    noise = temp
    switched = TRUE
  }
  else
    switched = FALSE

  noise.rotate = protate(noise,reference)

  inflate = sqrt(r2/(1-r2))

  if (switched)
    new = protate(noise.rotate * inflate + reference,
                  reference)
  else
    new = protate(reference * inflate + noise.rotate,
                  noise)

  new.sd = as.numeric(sqrt(varls(new,permutations=NULL)))

  new = new/new.sd

  return(new)
}

#simulate_matrix_tree
