#' Ratios of distances on their standard errors
#'
#' Ratios of the observed distances to their MC standard errors and of the mean MC-simulated distances to the standard error of the mean.
#'
#' @details The standard error of the mean simulated distances is \code{mean.se = MC.se/sqrt(R)} (or \code{mean.se = MC.sd/R} when object is obtained with \code{seqdistMCSE}, because there are \code{R*R} simulated distances in that case). The ratios computed are \code{diss.z = diss.o/MC.se}, where \code{diss.o} is the distance between observed sequences, and \code{MC.mean.z = MC.mean/mean.se} with \code{MC.mean} the mean of the MC-simulated distances.
#'
#' When \code{diss.o=NULL}, the \code{diss.o} element of \code{object} is used when it exists.
#'
#' This function is handy to get afterwards ratios for outcome of \code{\link{seqdistMCSE}} obtained with \code{ratios=FALSE}.
#'
#' @param object Object of class \code{distMC} as generated by \code{\link{MCseqdistSE}} and \code{\link{seqdistMCSE}}.
#' @param diss.o Matrix or \code{dist} object. Pairwise dissimilarities between observed sequences.
#'
#' @return \code{diss.z}, \code{MC.mean.z}, and \code{mean.se} (the three as \code{dist} objects).
#'
#' @seealso \code{\link{MCseqdistSE}} and \code{\link{print.MCratios}}.
#'
#' @author Gilbert Ritschard
#' @export

MCratios <- function(object, diss.o=NULL){
  if(!inherits(object, "distMC"))
    stop("argument distMC must be a distMC object!")
  toref <- attr(object,"toref")
  if (is.null(toref)) toref <- FALSE
  newdisso <- FALSE
  MC.bias <- object[["MC.bias"]]
  if (!is.null(diss.o)){
    newdisso <- TRUE
    message("Provided diss.o used instead of the diss.o element of provided MCdist object!")
    if (!toref)
      diss.o <- as.dist(diss.o)
    MC.bias <- diss.o - object[["MC.mean"]]
  }
  else {
    if (is.null(object[["diss.o"]]))
      message("No diss.o found!")
    else
      if (toref)
        diss.o <- object[["diss.o"]]
      else
        diss.o <- as.dist(object[["diss.o"]])
  }
  R <- object[["R"]]
  N <- object[["N"]]
  if (!is.null(diss.o)){
    ## should recompute standard errors when disso was provided as diss.o argument
    if (newdisso)
      MC.se <- sqrt(object[["MC.sd"]]^2 + MC.bias^2)
    else
      MC.se <- object[["MC.se"]]
    #diss.z <- diss.o / object[["MC.sd"]]
    diss.z <- diss.o / object[["MC.se"]]
    diss.z[diss.o==0] <- 0
    diss.z[diss.z>99] <- 99 ## setting upper value o z-ratio
  } else {
    diss.z=NULL
  }
  #diss.z <- object[["diss.z"]]
  if (is.null(N))
    mean.se <- object[["MC.sd"]]/R  ## for R*R simulated distances: R = sqrt(R^2)
  else
    mean.se <- object[["MC.sd"]]/sqrt(N)
  MC.mean.z <- object[["MC.mean"]] / mean.se
  #MC.mean.z <- object[["MC.mean.z"]]

  res <- list(diss.z=diss.z, MC.mean.z = MC.mean.z, mean.se = mean.se,N=N,R=R)
  if (newdisso)
    res <- c(res, list(diss.o = diss.o, MC.se=MC.se, MC.bias=MC.bias))
  class(res) <- c(class(res),"MCratios")
  attr(res,"toref") <- toref
  return(res)
}
