library(startR)

# Define locations
locations <- list(
  vriotajo = c(lat = 39.87, lon = 355.87)  # Example location
)

location_names <- names(locations)

# Function to find nearest index for latitude/longitude
find_nearest_index <- function(value, grid) {
  which.min(abs(grid - value))
}

# Define the years to load
years_to_load <- 2020:2024

# Load the NetCDF data using StartR for tasmin and tasmax
data_path <- "/esarchive/recon/ecmwf/era5land/daily/"

# Function to load and extract data using StartR
load_data_startR <- function(variable, years) {
  all_obs <- list()

  # Loop through years and extract data for each year
  for (year in years) {
    cat("Loading data for year:", year, "\n")
    
    # Use the Start function to load the data for a given variable and year
    data <- Start(dat = data_path, var = variable, year = year)
    
    # Extract latitude and longitude from the data
    lat_vals <- data$lat
    lon_vals <- data$lon
    
    # Loop through locations and extract data for each one
    for (loc_name in location_names) {
      loc <- locations[[loc_name]]
      
      # Find the nearest lat and lon indices for the location
      lat_idx <- find_nearest_index(loc["lat"], lat_vals)
      lon_idx <- find_nearest_index(loc["lon"], lon_vals)
      
      # Extract the data for the selected location
      loc_data <- data[[variable]][lat_idx, lon_idx, ]
      
      # Store the extracted data for the location
      all_obs[[paste0(loc_name, "_", year)]] <- loc_data
    }
  }
  
  return(all_obs)
}

# Load both tasmin and tasmax data
tasmin_data <- load_data_startR("tasmin", years_to_load)
tasmax_data <- load_data_startR("tasmax", years_to_load)

# Example of checking the loaded data
tasmin_data
tasmax_data
