#' @title Bootstrap estimates of the decomposed diversity indices
#'
#' @description Computes bootstrap confidence intervals of the decomposed diversity indices
#'
#' @param x Vector of dimension S (number of species) with the number of individuals observed in each species. NA values are allowed. 0 values are converted to NA.
#' @param groups Vector of dimension S of factors indicating the groups of each species.
#' @param ind Index to be computed. The default value is "shannon". The other possible value is "equitability".
#' @param B Number of bootstrap samples. The default is 1000.
#' @param cl Confidence level. A value between 0 and 1. The default is 0.95.
#'
#' @return
#' \itemize{
#'   \item \code{bt_low}: Lower limit of the confidence interval for "between groups".
#'   \item \code{bt_up}: Upper limit of the confidence interval for "between groups".
#'   \item \code{wt_low}: Lower limit of the confidence interval for "within groups".
#'   \item \code{bt_up}: Upper limit of the confidence interval for "within groups".
#' }
#'
#' @references
#' "Quantifying Diversity through Entropy Decomposition: Insights into Hominin Occupation and Carcass Processing at Qesem cave"
#'
#' @examples
#' data(Qesem_s)
#' bs_dec(Qesem_s$HU, Qesem_s$Group)
#'
#' @export
bs_dec <- function(x, groups, ind = "shannon", B = 1000, cl = 0.95){
  stopifnot(is.numeric(B),
            B==round(B),
            cl>0 & cl<1,
            ind %in% c("shannon", "equitability"),
            length(x)==length(as.character(groups)),
            is.factor(groups)
            )
  x <- ifelse(x==0, NA, x)
  xx <- na.omit(data.frame(x, groups))
  stopifnot(
    is.numeric(xx$x),
    all(xx$x > 0),
    isTRUE(all.equal(xx$x, round(xx$x)))
    )
  n <- sum(xx$x)
  m <- nrow(xx)
  for (i in 1:m){
    if (i==1) y <- data.frame(S=rep(i, xx$x[i]),
                              G=rep(xx$groups[i], xx$x[i]))
    else y <- rbind(y, data.frame(S=rep(i, xx$x[i]),
                                  G=rep(xx$groups[i], xx$x[i])))
  }
  res <- data.frame(bt=rep(NA, B), wt=rep(NA, B))
  for (i in 1:B){
    s <- sample(1:n, n, replace = T)
    yb <- y[s,]
    tab <- table(yb$S)
    if (ind=="shannon"){
      d <- dec_shannon(as.vector(tab), xx$groups[as.numeric(names(tab))])
      res$bt[i] <- d$between
      res$wt[i] <- d$within
    } else {
      d <- dec_equit(as.vector(tab), xx$groups[as.numeric(names(tab))])
      res$bt[i] <- d$between
      res$wt[i] <- d$within
    }
  }
  q_bt <- stats::quantile(res$bt, probs = sort(c(1-cl, cl)))
  q_wt <- stats::quantile(res$wt, probs = sort(c(1-cl, cl)))
  return(list(bt_low = as.numeric(q_bt[1]),
              bt_up = as.numeric(q_bt[2]),
              wt_low = as.numeric(q_wt[1]),
              wt_up = as.numeric(q_wt[2])
              )
         )

}

