#' Executing ROPES
#' 
#' @aliases executing_ropes
#'
#' @description 
#' This function executes the ROPES algorithm for the matrix that contains
#' the similar players to the player of interest according to the archetypoid
#' algorithm, and the player of interest himself.
#' 
#' @usage 
#' executing_ropes(plSim, b, w, ...)
#' 
#' @param plSim Vector with the the similar players and the player 
#' of interest.
#' @param b Matrix b from \code{\link{b_w}}.
#' @param w Matrix w from \code{\link{b_w}}.
#' @param ... Further parameters for \code{\link{ropes}}.
#' 
#' @return 
#' A list with the following values:
#' \emph{result}: List returned by \code{\link{ropes}}.
#' \emph{b_12}: Matrix b with some needed preprocessing, to be 
#' used by \code{\link{ropes}} (see below the comments in the function code).
#' \emph{w_12}: Matrix w with the same preprocessing for matrix w.
#' 
#' @author 
#' Guillermo Vinue
#'
#' @seealso 
#' \code{\link{ropes}}
#'
#' @examples 
#' # See the code.
#' 
#' @export

executing_ropes <- function(plSim, b, w, ...){

  b_1 <- b[rownames(b) %in% plSim,]
  w_1 <- w[rownames(w) %in% plSim,]
  
  # To count the number of non-NA-values in each column of b_1. 
  # This is because when filtering by players, the first ages may 
  # not contain any value.
  nonNA_cols <- apply(b_1, 2, FUN = function(x) length(x[!is.na(x)]) )
  if (length(which(nonNA_cols == 0)) != 0) {
    b_11 <- b_1[,-which(nonNA_cols == 0)]
    w_11 <- w_1[,-which(nonNA_cols == 0)] 
  }else{
    b_11 <- b_1
    w_11 <- w_1
  }

  # To count the number of non-NA-values in each row of b_11:
  # These are the players with only one measurement, so we have to remove them.
  #nonNA_rows <- apply(b_11, 1, FUN = function(x) length(x[!is.na(x)]) )
  #if (length(which(nonNA_rows == 1)) != 0) {
  #  b_12 <- b_11[-which(nonNA_rows == 1),]
  #  w_12 <- w_11[-which(nonNA_rows == 1),]
  #}else{
    b_12 <- b_11
    w_12 <- w_11
  #}

  b_12 <- as.matrix(b_12)
  w_12 <- as.matrix(w_12)
  
  result <- ropes(b_12, w_12, ...)
  dimnames(result$Z) <- dimnames(b_12)
  
  return(list(result = result, b_12 = b_12, w_12 = w_12))
}  