
startR_call_indices <- function(type, dataset, variable, 
                               sdate_min=NULL, sdate_max=NULL, fmonth_min=NULL, fmonth_max=NULL,
                               year_min=NULL, year_max=NULL, months=NULL,
                               members = 'all', retrieve = FALSE){
  
  if (dataset == 'EC-Earth3'){
    
    if (variable == 'tos'){
      path = '/esarchive/exp/ecearth/a1ua/cmorfiles/DCPP/EC-Earth-Consortium/EC-Earth3/dcppA-hindcast/$member$/Omon/$var$/gr/v20190713/$var$_Omon_EC-Earth3_dcppA-hindcast_s$sdate$-$member$_gr_$fyear$.nc'
    } else if (variable == 'tas'){
      path = '/esarchive/exp/ecearth/a1ua/cmorfiles/DCPP/EC-Earth-Consortium/EC-Earth3/dcppA-hindcast/$member$/Amon/$var$/gr/v20190713/$var$_Amon_EC-Earth3_dcppA-hindcast_s$sdate$-$member$_gr_$fyear$.nc'
    } 
    
    data = startR::Start(dataset = path,
                         var = variable,
                         sdate = paste0(sdate_min:sdate_max),
                         fmonth = c(fmonth_min:fmonth_max),
                         lat = values(list(-10, 10)),
                         lon = values(list(0, 10)),
                         fyear = 'all',
                         member = members,
                         fyear_depends = 'sdate',
                         fmonth_across = 'fyear',
                         merge_across_dims = TRUE,
                         synonims = list(fmonth = c('fmonth','time'), lon = c('lon', 'longitude'), lat = c('lat', 'latitude')),
                         return_vars = list(lat = 'dataset', lon = 'dataset'),
                         num_procs = 4, retrieve = retrieve)
    
  } else if (dataset == 'HadGEM3'){
    
    if(variable == 'tos'){
      variable = 'ts'
    }
    
    if (variable %in% c('tas','ts')){
      path = '/esarchive/exp/CMIP6/dcppA-hindcast/hadgem3/cmip6-dcppA-hindcast_i1p1/DCPP/MOHC/HadGEM3/dcppA-hindcast/$member$/Amon/$var$/gr/v20200316/$var$_*_s$sdate$_$member$_gr_$sdate$11-$aux$03.nc'
    }
    
    data = startR::Start(dataset = path,
                         var = variable,
                         sdate = paste0(sdate_min:sdate_max),
                         fmonth = c(fmonth_min:fmonth_max),
                         aux = 'all',
                         aux_depends = 'sdate',
                         lat = values(list(-90, 90)), 
                         lon = values(list(0, 359.9)),
                         member = members,
                         synonims = list(fmonth = c('fmonth','time'), lon = c('lon', 'longitude'), lat = c('lat', 'latitude')),
                         return_vars = list(lat = 'dataset', lon = 'dataset'),
                         num_procs = 4, retrieve = retrieve)
    
  } else if (dataset == 'MPI-ESM1.2-HR'){
    
    if (variable == 'tos'){
      path = '/esarchive/exp/CMIP6/dcppA-hindcast/mpi-esm1-2-hr/cmip6-dcppA-hindcast_i1p1/DCPP/MPI-M/MPI-ESM1-2-HR/dcppA-hindcast/$member$/Omon/$var$/gr/v20200320/$var$_*_s$sdate$-$member$_gr_$sdate$11-$aux$12.nc'
    } else if (variable == 'tas'){
      path = '/esarchive/exp/CMIP6/dcppA-hindcast/mpi-esm1-2-hr/cmip6-dcppA-hindcast_i1p1/DCPP/MPI-M/MPI-ESM1-2-HR/dcppA-hindcast/$member$/Amon/$var$/gn/v20200320/$var$_*_s$sdate$-$member$_gn_$sdate$11-$aux$12.nc'
    }
    
    data = startR::Start(dataset = path,
                         var = variable,
                         sdate = paste0(sdate_min:sdate_max),
                         fmonth = c(fmonth_min:fmonth_max),
                         aux = 'all',
                         aux_depends = 'sdate',
                         lat = values(list(-90, 90)), 
                         lon = values(list(0, 359.9)),
                         member = members,
                         synonims = list(fmonth = c('fmonth','time'), lon = c('lon', 'longitude'), lat = c('lat', 'latitude')),
                         return_vars = list(lat = 'dataset', lon = 'dataset'),
                         num_procs = 4, retrieve = retrieve)
    
  } else if (dataset == 'CMCC-CM2'){
    
    stop('no data for CMCC-CM2')
    
  } else if (dataset == 'EC-Earth3_hist'){
    
    if (members == 'all'){
      exps = c('a1wk','a1tt','a1tk','a1tn','a1to','a1ts','a247','a1tp','a1tr','a1ty')
    } else if (members == '1'){
      exps = 'a1wk'
    }
    
    if (variable %in% c('tas','tos')){
      path = '/esarchive/exp/ecearth/$member$/cmorfiles/CMIP/EC-Earth-Consortium/EC-Earth3/historical/$aux$/Amon/$var$/gr/$aux2$/$var$_Amon_EC-Earth3_historical_$aux$_gr_$year$01-$year$12.nc'
    }
    
    data = Start(dataset = path,
                 var = variable,
                 year = as.character(year_min:year_max),
                 month = months,
                 lat = values(list(-90,90)),
                 lon = values(list(0,359.9)),
                 aux = 'all',
                 aux2 = 'all',
                 member = exps,
                 synonims = list(lon = c('lon', 'longitude'), lat = c('lat', 'latitude'), month = c('month','time')),
                 return_vars = list(lat = 'dataset', lon = 'dataset'),
                 lat_reorder = Sort(),
                 lon_reorder = CircularSort(0, 360),
                 num_procs = 8, retrieve = retrieve)
    
  } else if (dataset == 'HadGEM3_hist'){
    
    if (variable == 'tos'){variable = 'ts'}
    
    if (variable %in% c('tas','ts')){
      path = '/esarchive/exp/CMIP6/dcppA-hindcast/hadgem3/cmip6-dcppA-hindcast_i0p1/$var$_Amon_HadGEM3_historical_$member$_gr_$year$01-$year$12.nc'      
    }
    
    data = Start(dataset = path,
                 var = variable,
                 year = as.character(year_min:year_max),
                 month = 'all',
                 lat = values(list(-90, 90)),
                 lon = values(list(0, 359.9)),
                 member = members,
                 synonims = list(month = c('month','time'), lon = c('lon', 'longitude'), lat = c('lat', 'latitude')),
                 return_vars = list(lat = 'dataset', lon = 'dataset'),
                 lat_reorder = Sort(),
                 lon_reorder = CircularSort(0, 360),
                 num_procs = 8, retrieve = retrieve)
    
  } else if (dataset == 'MPI-ESM1.2-HR_hist'){
    
    if (variable %in% c('tas','tos')){
      
      ###################################################################################
      ## Con este modelo hay que hacerlo un poco diferente y con retrieve=T porque los ficheros estan colocados de una forma distinta
      ## Cuando Marga haga la interpolacion los pondra bien
      ## De momento se elimina el primer year (para empezar en 1961 igual que las dcpp)
      
      if (variable == 'tos'){
        path = '/esarchive/scratch/cdelgado/data_interpolated/MPI-ESM1-2-HR_hist_tos/$var$_Omon_MPI-ESM1-2-HR_historical_$member$_gn_$aux$.nc'      
      } else if (variable == 'tas'){
        path = '/esarchive/exp/CMIP6/historical/mpi-esm1-2-hr/cmip6-historical_i0p1/$var$_Amon_MPI-ESM1-2-HR_historical_$member$_gn_$aux$.nc'
      }
      
      files_aux = paste0(seq(1960,2010,by = 5),'01-',seq(1964,2014,by = 5),'12')
      
      data = Start(dataset = path,
                   var = variable,
                   aux = files_aux,
                   month = months,
                   lat = values(list(-90, 90)),
                   lon = values(list(0, 359.9)),
                   member = members,
                   synonims = list(lon = c('lon', 'longitude'), lat = c('lat', 'latitude'), month = c('month','time')),
                   return_vars = list(lat = 'dataset', lon = 'dataset'),
                   lat_reorder = Sort(),
                   lon_reorder = CircularSort(0, 360),
                   num_procs = 8, retrieve = TRUE)
      
      data_lats = as.vector(attributes(data)$Variables$dat1$lat)
      data_lons = as.vector(attributes(data)$Variables$dat1$lon)
      
      library(CSTools)
      data = CSTools::MergeDims(data = data, merge_dims = c('month','aux'), rename_dim = 'month', na.rm = FALSE)
      data = startR::Subset(x = data, along = 'month', indices = 13:dim(data)['month'])
      dim(data) <- c(dataset = as.numeric(dim(data)['dataset']), var = as.numeric(dim(data)['var']), month = 12, year = as.numeric(dim(data)['month'])/12 , lat = as.numeric(dim(data)['lat']), lon = as.numeric(dim(data)['lon']), member = as.numeric(dim(data)['member']))
      data = drop(data)
      INDEX = array(data = NA, dim = c(dim(data)['year'],dim(data)['member']))
      names(dim(INDEX)) = c('year','member')
      for (member in 1:dim(data)['member']){
        print(paste0('member ', member))
        INDEX[,member] = drop(fun(mask = FALSE, data = data[,,,,member], data_lats = data_lats, data_lons = data_lons, type = type))
      }
      if (save_output){
        saveRDS(INDEX, file = paste0(output_path,index,'_',dataset,'.rds'))
      }
      stop(paste0('Finished ', index, ' for MPI-ESM1.2-HR for historical runs.'))
      
    } else if (variable == 'tas_tos'){
      
      path_tos = '/esarchive/scratch/cdelgado/data_interpolated/MPI-ESM1-2-HR_hist_tos/$var$_Omon_MPI-ESM1-2-HR_historical_$member$_gn_$aux$.nc'      
      path_tas = '/esarchive/exp/CMIP6/historical/mpi-esm1-2-hr/cmip6-historical_i0p1/$var$_Amon_MPI-ESM1-2-HR_historical_$member$_gn_$aux$.nc'
      
      files_aux = paste0(seq(1960,2010,by = 5),'01-',seq(1964,2014,by = 5),'12')
      
      data_tas = Start(dataset = path_tas,
                       var = 'tas',
                       aux = files_aux,
                       month = months,
                       lat = values(list(-90, 90)),
                       lon = values(list(0, 359.9)),
                       member = members,
                       synonims = list(lon = c('lon', 'longitude'), lat = c('lat', 'latitude'), month = c('month','time')),
                       return_vars = list(lat = 'dataset', lon = 'dataset'),
                       lat_reorder = Sort(),
                       lon_reorder = CircularSort(0, 360),
                       num_procs = 8, retrieve = TRUE)
      
      data_tos = Start(dataset = path_tos,
                       var = 'tos',
                       aux = files_aux,
                       month = months,
                       lat = values(list(-90, 90)),
                       lon = values(list(0, 359.9)),
                       member = members,
                       synonims = list(lon = c('lon', 'longitude'), lat = c('lat', 'latitude'), month = c('month','time')),
                       return_vars = list(lat = 'dataset', lon = 'dataset'),
                       lat_reorder = Sort(),
                       lon_reorder = CircularSort(0, 360),
                       num_procs = 8, retrieve = TRUE)
      
      data_lats_tas = as.vector(attributes(data_tas)$Variables$dat1$lat)
      data_lons_tas = as.vector(attributes(data_tas)$Variables$dat1$lon)
      data_lats_tos = as.vector(attributes(data_tos)$Variables$dat1$lat)
      data_lons_tos = as.vector(attributes(data_tos)$Variables$dat1$lon)
      
      if (identical(data_lats_tas,data_lats_tos) & identical(data_lons_tas,data_lons_tos)){
        data_lats = data_lats_tas
        data_lons = data_lons_tas
      } else {
        stop('Latitudes or logitudes of tas and tos are not identical')
      }
      
      library(CSTools)
      
      data_tas = CSTools::MergeDims(data = data_tas, merge_dims = c('month','aux'), rename_dim = 'month', na.rm = FALSE)
      data_tas = startR::Subset(x = data_tas, along = 'month', indices = 13:dim(data_tas)['month'])
      dim(data_tas) <- c(dataset = as.numeric(dim(data_tas)['dataset']), var = as.numeric(dim(data_tas)['var']), month = 12, year = as.numeric(dim(data_tas)['month'])/12 , lat = as.numeric(dim(data_tas)['lat']), lon = as.numeric(dim(data_tas)['lon']), member = as.numeric(dim(data_tas)['member']))
      data_tas = drop(data_tas)
      data_tos = CSTools::MergeDims(data = data_tos, merge_dims = c('month','aux'), rename_dim = 'month', na.rm = FALSE)
      data_tos = startR::Subset(x = data_tos, along = 'month', indices = 13:dim(data_tos)['month'])
      dim(data_tos) <- c(dataset = as.numeric(dim(data_tos)['dataset']), var = as.numeric(dim(data_tos)['var']), month = 12, year = as.numeric(dim(data_tos)['month'])/12 , lat = as.numeric(dim(data_tos)['lat']), lon = as.numeric(dim(data_tos)['lon']), member = as.numeric(dim(data_tos)['member']))
      data_tos = drop(data_tos)
      
      INDEX = array(data = NA, dim = c(dim(data_tas)['year'],dim(data_tas)['member']))
      names(dim(INDEX)) = c('year','member')
      for (member in 1:dim(data_tas)['member']){
        print(paste0('member ', member))
        INDEX[,member] = drop(fun(mask = FALSE, data_tas = data_tas[,,,,member], data_tos = data_tos[,,,,member], data_lats = data_lats, data_lons = data_lons, type = type))
      }
      if (save_output){
        saveRDS(INDEX, file = paste0(output_path,index,'_',dataset,'.rds'))
      }
      stop(paste0('Finished GMST for MPI-ESM1.2-HR for historical runs.'))
      
    }
    ###################################################################################
    ###################################################################################
    
  } else if (dataset == 'CMCC-CM2_hist'){
    
    stop('no data for CMCC-CM2_hist')
    
  } else if (dataset == 'GISTEMPv4'){
    
    if (variable %in% c('tos','tas_tos')){
      variable = 'tasanomaly'
      path = '/esarchive/obs/noaa-nasa/ghcnersstgiss/monthly_mean/$var$/$var$_$year$$month$.nc'
    } else {stop('GISTEMPv4 is a combination of tas and tos')}
    
    data = Start(dataset = path,
                 var = variable,
                 year = paste0(year_min:year_max),
                 month = months,
                 lat = values(list(-90,90)),
                 lon = values(list(0,359.9)),
                 synonims = list(lat = c('lat','latitude'), lon = c('lon','longitude'), month = c('month','time')),
                 return_vars = list(lat = 'dataset', lon = 'dataset'),
                 lat_reorder = Sort(),
                 lon_reorder = CircularSort(0, 360),
                 num_procs = 8, retrieve = retrieve)
    
  } else if (dataset == 'JRA-55'){
    
    if (variable == 'tas'){
      path = '/esarchive/recon/jma/jra55/monthly_mean/$var$_f6h/$var$_$year$$month$.nc'
    }
    
    data = Start(dataset = path,
                 var = variable,
                 year = paste0(year_min:year_max),
                 month = months,
                 lat = values(list(-90,90)),
                 lon = values(list(0,359.9)),
                 synonims = list(lat = c('lat','latitude'), lon = c('lon','longitude'), month = c('month','time')),
                 return_vars = list(lat = 'dataset', lon = 'dataset'),
                 lat_reorder = Sort(),
                 lon_reorder = CircularSort(0, 360),
                 num_procs = 8, retrieve = retrieve)
    
  } else if (dataset == 'ERA5'){
    
    if (variable == 'tas'){
      path = ''
    }
    
    data = Start(dataset = path,
                 var = variable,
                 year = paste0(year_min:year_max),
                 month = 'all',
                 lat = values(list(-90,90)),
                 lon = values(list(0,359.9)),
                 synonims = list(lat = c('lat','latitude'), lon = c('lon','longitude'), month = c('month','time')),
                 return_vars = list(lat = 'dataset', lon = 'dataset'),
                 lat_reorder = Sort(),
                 lon_reorder = CircularSort(0, 360),
                 num_procs = 8, retrieve = retrieve)
    
  }
  
  return(data)
}

