absolute_threshold <- function(data, threshold, operator, spell,
                               var.list, return.percent = TRUE, ncores) {
  
  library(CSIndicators)
  
  if(is.null(spell)){
    spell <- 1
  }
  
  time_dim <- 'time'
  memb_dim <- 'ensemble'
  sdate_dim <- 'syear'
  
  data_temp <- data
  
  ## Identify the month for each forecast period
  if (return.percent){ ## works only if forecast months start at 1
    start_month <- as.POSIXct(data$obs$attrs$Dates[[1]], format = "%Y-%m-%d")
    num_forecast_months <- dim(data$obs$data)['ftime'][[1]]
    forecast_months <- ((month(start_month) - 1 + 0:(num_forecast_months - 1)) %% 12) + 1
    days_per_month <- sapply(forecast_months, days_in_month)
  }
  
  if (!is.null(data$obs)) {
    result_obs <- c()
    dim_var <- which(names(dim(data$obs$data)) == "var")
    for (var in var.list) {
      data_temp$obs$data <- Subset(data$obs$data, along = "var", indices = which(var.list == var), drop = FALSE)

      data_probs <- CST_AbsToProbs(data_temp$obs, time_dim = time_dim,
                                   memb_dim = memb_dim, sdate_dim = sdate_dim,
                                   ncores = ncores)
      
      obs_percentile <- CST_QThreshold(data_temp$obs, threshold = threshold,
                                        time_dim = time_dim, memb_dim = memb_dim, 
                                        sdate_dim = sdate_dim, ncores = ncores)
      
      obs_percentile$data <- Reorder(obs_percentile$data, 
                                     order = names(dim(data_temp$obs$data)))
      original_dimnames <- names(dim(obs_percentile$data))
      

      if(spell == 1){
        ## Calculate number of days exceeding threshold
        time_exceeded <- CST_TotalTimeExceedingThreshold(
          data = data_probs, threshold = obs_percentile, 
          op = operator, time_dim = time_dim, ncores = ncores)
      
      } else if(spell > 1){
        ## calculate number of days part of a spell
        time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
          data = data_probs, threshold = obs_percentile,
          spell = spell, op = operator, time_dim = time_dim,
          ncores = ncores)
      }

      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percentage_exceeded_per_month <-multiApply::Apply(
          data = time_exceeded$data, target_dims = "ftime",  
          fun = function(exceedance, days) {(exceedance / days) * 100},
          days = days_per_month)$output1
        
        percentage_exceeded_per_month <- Reorder(percentage_exceeded_per_month, 
                                                 names(dim(time_exceeded$data)))
        
        result_obs <- abind(result_obs, percentage_exceeded_per_month,
                            along = dim_var) 
      } else {
        ## return number of days
        result_obs <- abind(result_obs, time_exceeded$data, along = dim_var) 
      }
      names(dim(result_obs)) <- names(time_exceeded$dims)
    }
    data$obs$data <- result_obs
  }
  
  if (!is.null(data$hcst)) {
    result_hcst <- c()
    dim_var <- which(names(dim(data$hcst$data)) == "var")
    for (var in var.list) {
      data_temp$hcst$data <- Subset(data$hcst$data, along = "var", indices = which(var.list == var), drop = FALSE)

      data_probs <- CST_AbsToProbs(data_temp$hcst, time_dim = time_dim,
                                   memb_dim = memb_dim, sdate_dim = sdate_dim,
                                   ncores = ncores)
      
      ens_pos <- which(names(dim(data_temp$hcst$data)) == "ensemble")
      ens_hcst <- dim(data_temp$hcst$data)[ens_pos]
      
      hcst_perc_aux <- abind(replicate(as.numeric(ens_hcst),
                                       obs_percentile$data, 
                                       simplify = FALSE), along = ens_pos)
      names(dim(hcst_perc_aux)) <- original_dimnames
      
      hcst_percentile <- obs_percentile
      hcst_percentile$data <- hcst_perc_aux
      
      if(spell == 1){
        time_exceeded <- CST_TotalTimeExceedingThreshold(
          data = data_probs, threshold = hcst_percentile, 
          op = operator, time_dim = time_dim, ncores = ncores)
        
      } else if(spell > 1){
        time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
          data = data_probs, threshold = hcst_percentile,
          spell = spell, op = operator, time_dim = time_dim,
          ncores = ncores)
      }

      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percentage_exceeded_per_month <- multiApply::Apply(
          data = time_exceeded$data, target_dims = "ftime",  
          fun = function(exceedance, days) {(exceedance / days) * 100},
          days = days_per_month)$output1
        
        percentage_exceeded_per_month <- Reorder(percentage_exceeded_per_month, 
                                                 names(dim(time_exceeded$data)))
        
        result_hcst <- abind(result_hcst, percentage_exceeded_per_month,
                             along = dim_var) 
      } else {
        ## return number of days
        result_hcst <- abind(result_hcst, time_exceeded$data, along = dim_var) 
      }
      names(dim(result_hcst)) <- names(time_exceeded$dims)
      
    }
    data$hcst$data <- result_hcst
  }
  
  if (!is.null(data$fcst)) {
    result_fcst <- c()
    dim_var <- which(names(dim(data$fcst$data)) == "var")
    for (var in var.list) {
      data_temp$fcst$data <- Subset(data$fcst$data, along = "var", indices = which(var.list == var), drop = FALSE)
      
      data_probs <- CST_AbsToProbs(data_temp$fcst, time_dim = time_dim,
                                   memb_dim = memb_dim, sdate_dim = sdate_dim,
                                   ncores = ncores)
      
      # data_temp$obs$data <- MeanDims(data_temp$obs$data, dims = sdate_dim, drop = FALSE)
      # clim_percentile <- CST_QThreshold(data_temp$obs, threshold = threshold,
      #                                   time_dim = time_dim, memb_dim = memb_dim, 
      #                                   sdate_dim = sdate_dim, ncores = ncores)
      ## Not possible to calculate with only one year

      ens_pos <- which(names(dim(data_temp$hcst$data)) == "ensemble")
      ens_fcst <- dim(data_temp$fcst$data)[ens_pos]

      fcst_perc_aux <- abind(replicate(as.numeric(ens_fcst),
                                       obs_percentile$data, 
                                       simplify = FALSE), along = ens_pos)
      names(dim(fcst_perc_aux)) <- original_dimnames
      
      ## Not sure if this approach of averaging the percentiles over syear is correct
      fcst_perc_aux <- MeanDims(fcst_perc_aux, dims = sdate_dim, drop = FALSE)
      
      fcst_percentile <- obs_percentile
      fcst_percentile$data <- fcst_perc_aux

      if(spell == 1){
        time_exceeded <- CST_TotalTimeExceedingThreshold(
          data = data_probs, threshold = fcst_percentile, 
          op = operator, time_dim = time_dim, ncores = ncores)
        
      } else if(spell > 1){
        time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
          data = data_probs, threshold = fcst_percentile,
          spell = spell, op = operator, time_dim = time_dim,
          ncores = ncores)
      }
      
      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percentage_exceeded_per_month <- multiApply::Apply(
          data = time_exceeded$data, target_dims = "ftime",  
          fun = function(exceedance, days) {(exceedance / days) * 100},
          days = days_per_month)$output1
        
        percentage_exceeded_per_month <- Reorder(percentage_exceeded_per_month, 
                                                 names(dim(time_exceeded$data)))
        
        result_fcst <- abind(result_obs, percentage_exceeded_per_month,
                             along = dim_var)         
      } else {
        ## return number of days
        result_fcst <- abind(result_fcst, time_exceeded$data, along = dim_var) 
      }
      names(dim(result_fcst)) <- names(time_exceeded$dims)
    }
    data$fcst$data <- result_fcst
  }
  
  return(data)
}
