#'
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, equal.var = TRUE) {
  new <- rnorm(n * p, mean = 0, sd = 1)
  dim(new) <- c(n, p)

  new <- scale(new, center = TRUE, scale = equal.var)

  attributes(new)$`scaled:center` <- NULL
  attributes(new)$`scaled:scale` <- NULL
  new.sd <- sqrt(sum(new^2) / (n - 1))
  new <- new / new.sd

  return(new)
}

#' Simulate n points of dimension p correlated with a reference matrix.
#'
#' @export

simulate_correlation <- function(reference, p, r2, equal.var = TRUE) {
  n <- nrow(reference)
  maxdim <- max(ncol(reference), p)

  noise <- simulate_matrix(n, p, equal.var = equal.var)

  if (maxdim == p && maxdim > ncol(reference)) {
    # noise is the largest matrix
    YX <- crossprod(noise, reference)
    svd.YX <- svd(YX)
    rot  <- svd.YX$v %*% t(svd.YX$u)
    rotr <- svd.YX$u %*% t(svd.YX$v)

    print(rot)
    print(rotr)

    new = ((reference %*% rot) * sqrt(r2) +
            noise              * sqrt(1 - r2)) %*% rotr
  }
  else {
    # reference is the largest matrix
    YX <- crossprod(reference, noise)
    svd.YX <- svd(YX)
    rot  <- svd.YX$v %*% t(svd.YX$u)
    rotr <- svd.YX$u %*% t(svd.YX$v)

    new = (reference       * sqrt(r2) +
           (noise %*% rot) * sqrt(1 - r2)) %*% rotr
  }

  new <- scale(new, scale = FALSE)
  attributes(new)$`scaled:center` <- NULL
  new.sd <- sqrt(sum(new^2) / (n - 1))
  new <- new / new.sd

  return(new)
}

#simulate_matrix_tree
