#' @author Christelle Gonindard-Melodelima
#' @author Eric Coissac
NULL

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
icor <- function(x, y = NULL) {
  if (is.data.frame(y)) {
    y <- as.matrix(y)
  }

  if (is.data.frame(x)) {
    x <- as.matrix(x)
  }

  if (!is.matrix(x) && is.null(y)) {
    stop("supply both 'x' and 'y' or a matrix-like 'x'")
  }

  if (!(is.numeric(x) || is.logical(x))) {
    stop("'x' must be numeric")
  }

  stopifnot(is.atomic(x))

  if (!is.null(y)) {
    if (!(is.numeric(y) || is.logical(y))) {
      stop("'y' must be numeric")
    }
    stopifnot(is.atomic(y))
  }

  if (!is.matrix(x)) {
    x <- t(t(x))
  }

  if (is.null(y)) {
    y <- x
  }

  if (!is.matrix(y)) {
    y <- t(t(y))
  }

  xc <- scale(x, scale = FALSE, center = TRUE)
  yc <- scale(y, scale = FALSE, center = TRUE)

  n <- nrow(x)

  cov <- crossprod(xc, yc) / (n - 1)

  print(cov)

  sdx <- apply(x, MARGIN = 2, sd)
  sdy <- apply(y, MARGIN = 2, sd)

  rcov <- sqrt(1 / (n - 1)) * (sdx %o% sdy)

  print(rcov)

  s <- sign(cov)
  icov <- (s * cov - rcov) * s

  print(icov)

  isdx <- sqrt(1 - sqrt(1 / (n - 1))) * sdx
  isdy <- sqrt(1 - sqrt(1 / (n - 1))) * sdy

  ipearson <- icov / (isdx %o% isdy)
  ipearson
}
