percentile_threshold <- function(data, percentile, operator, spell, 
                                 forecast_periods, 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

  browser()
  
  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)
      
      ## Loop over forecast time
      for(ftime in forecast_periods){
        
        ## need to subset data by forecast time
        data_ftime <- CST_SelectPeriodOnData(data = data_temp$obs, 
                                             start = list(1, ftime), 
                                             end = list(31, ftime),
                                             ncores = ncores)
        ## Calculate percentiles
        data_threshold <- CST_Threshold(data = data_temp$obs, threshold = percentile,
                                        start = list(1,ftime), end = list(31,ftime),
                                        time_dim = time_dim, memb_dim = memb_dim,
                                        sdate_dim = sdate_dim, na.rm = TRUE)
        
        if(spell == 1){
          ## Calculate number of days exceeding threshold
          time_exceeded <- CST_TotalTimeExceedingThreshold(
            data = data_ftime, threshold = data_threshold$data,
            start = list(1,ftime), end = list(31,ftime),
            op = operator, na.rm = TRUE, ncores = ncores)
          
        } else if(spell > 1){
          ## calculate number of days part of a spell
          time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
            data = data_temp$obs, threshold = data_threshold$data,
            spell = spell, op = operator, ncores = ncores)
        }
        
        ## remove time dimension
        dims <- dim(time_exceeded$data)
        dims_without_time <- dims[-which(names(dims) == "time")]
        time_exceeded$data <- array(time_exceeded$data, 
                                        dim = dims_without_time, 
                                        dimnames = dimnames(time_exceeded$data)
                                        [-which(names(dims) == "time")])
        
        ## Combine results
        result_obs <- abind(result_obs$data, time_exceeded$data,
                            along = length(dim(time_exceeded$data))+1,
                            new.names = "new_dim")
        
        names(dim(result_obs)) <-  names(time_exceeded$dims)
      }
      
      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percent_days <- multiApply::Apply( data = time_exceeded$data,
                                           target_dims = "ftime",  
                                           fun = function(exceedance, days) {
                                             (exceedance / days) * 100},
                                           days = days_per_month)$output1
        percent_days <- Reorder(percent_days, 
                                names(dim(time_exceeded$data)))
        result_obs <- abind(result_obs, percent_days, 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)
      
      ## Calculate percentiles
      data_threshold <- CST_Threshold(data = data_temp$hcst, threshold = percentile,
                                      time_dim = time_dim, memb_dim = memb_dim,
                                      sdate_dim = sdate_dim, na.rm = TRUE, 
                                      ncores = ncores)
      
      if(spell == 1){
        ## Calculate number of days exceeding threshold
        time_exceeded <- CST_TotalTimeExceedingThreshold(
          data = data_temp$hcst, threshold = data_threshold$data,
          op = operator, na.rm = TRUE, ncores = ncores)
        
      } else if(spell > 1){
        ## calculate number of days part of a spell
        time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
          data = data_temp$hcst, threshold = data_threshold$data,
          spell = spell, op = operator, ncores = ncores)
      }
      
      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percent_days <- multiApply::Apply(data = time_exceeded$data,
                                          target_dims = "ftime",  
                                          fun = function(exceedance, days) {
                                            (exceedance / days) * 100},
                                          days = days_per_month)$output1
        percent_days <- Reorder(percent_days, 
                                names(dim(time_exceeded$data)))
        result_hcst <- abind(result_hcst, percent_days, 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)
      
      ## Calculate percentiles
      data_threshold <- CST_Threshold(data = data_temp$fcst, threshold = percentile,
                                      time_dim = time_dim, memb_dim = memb_dim,
                                      sdate_dim = sdate_dim, na.rm = TRUE,
                                      ncores = ncores)
      
      if(spell == 1){
        ## Calculate number of days exceeding threshold
        time_exceeded <- CST_TotalTimeExceedingThreshold(
          data = data_temp$fcst, threshold = data_threshold$data,
          op = operator, na.rm = TRUE, ncores = ncores)
        
      } else if(spell > 1){
        ## calculate number of days part of a spell
        time_exceeded <- CST_TotalSpellTimeExceedingThreshold(
          data = data_temp$fcst, threshold = data_threshold$data,
          spell = spell, op = operator, ncores = ncores)
      }
      
      if (return.percent) {
        ## Calculate percentage of days exceeding threshold
        percent_days <- multiApply::Apply(data = time_exceeded$data,
                                          target_dims = "ftime",  
                                          fun = function(exceedance, days) {
                                            (exceedance / days) * 100},
                                          days = days_per_month)$output1
        percent_days <- Reorder(percent_days, names(dim(time_exceeded$data)))
        result_fcst <- abind(result_fcst, percent_days, 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
  } else {
    data$fcst$data <- NULL
  }
  
  return(data)
}
