#'
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=FALSE) {

  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=FALSE) {
  n = nrow(reference)
  maxdim = max(ncol(reference),p)

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

  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 = 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
