# RPS version for climatology 
RPS_clim <- function(obs, indices_for_clim = NULL,
                     prob_thresholds = c(1/3, 2/3), cross.val = TRUE,
                     Fair = FALSE, bin_dim_abs = NULL, return_mean = TRUE) { 
  if (is.null(indices_for_clim)){
    indices_for_clim <- 1:length(obs)
  }
  if (is.null(bin_dim_abs)) {
    obs_probs <- .GetProbs(data = obs, indices_for_quantiles = indices_for_clim, ## temporarily removed s2dv:::
                           prob_thresholds = prob_thresholds, weights = NULL,
                           cross.val = cross.val) 
  } else {
    obs_probs <- obs
  }
  # clim_probs: [bin, sdate]
  clim_probs <- c(prob_thresholds[1],
                  diff(prob_thresholds), 1 - prob_thresholds[length(prob_thresholds)])
  clim_probs <- array(clim_probs, dim = dim(obs_probs))
  
  # Calculate RPS for each time step
  probs_clim_cumsum <- apply(clim_probs, 2, cumsum)
  probs_obs_cumsum <- apply(obs_probs, 2, cumsum)
  rps_ref <- apply((probs_clim_cumsum - probs_obs_cumsum)^2, 2, sum)
  if (Fair) { # FairRPS
    ## adjustment <- rowSums(-1 * (1/R - 1/R.new) * ens.cum * (R - ens.cum)/R/(R - 1))
    ## [formula taken from SpecsVerification::EnsRps]
    ## See explanation in https://freva.met.fu-berlin.de/about/problems/
    R <- dim(obs)[2]  #years
    adjustment <- (-1) / (R - 1) * probs_clim_cumsum * (1 - probs_clim_cumsum)
    adjustment <- colSums(adjustment)
    rps_ref <- rps_ref + adjustment
  }
  
  if (return_mean == TRUE) {
    return(mean(rps_ref)) 
  } else {
    return(rps_ref)
  }
}

