
# Creation: 6/2016
# Author: Nicola Cortesi
# Aim: to generate a multimodel of CMIP5 simulation for a set of wine indices defined by the user, and estimate and visualize their projected climate change for two emission scenarios.
# I/O: input CMIP5 simulations. Output maps of measured and estimated wine indices.
# Assumption: none, the user can set all the parameters.
# Branch: multimodels

rm(list=ls())
#gc()
#source("~/.Rprofile")

#save.image(file=paste0(outputdir,"/Bodega_base.RData"))

rean=TRUE # put FALSE if you want to load reanalisis data from file
ensemble=TRUE # put true to load also the multimodel computation, if you already analyzed all the runs once
if(rean==FALSE && ensemble==FALSE) load("/home/Earth/ncortesi/Downloads/Bodegas_Torre/Bodega_base.RData")  # store reanalisis data
if(rean==FALSE && ensemble==TRUE) load("/home/Earth/ncortesi/Downloads/Bodegas_Torre/models/Ensemble/Bodega_base_ensemble.RData")

########### User-defined Variables ############################################

model.names=c("BCC-CSM1-1","BCC-CSM1-1-m","BNU-ESM","CCSM4","CNRM-CM5","CSIRO-Mk3-6-0","EC-EARTH","FIO-ESM","GFDL-CM3","GISS-E2-H","IPSL-CM5a-LR","IPSL-CM5A-MR","MIROC5","MPI-ESM-LR","MPI-ESM-MR")

# number of runs for each model (warning: the run starting with r0 is not a run, but the land/sea mask, so the runs start with r1):
# each run must consist in 1 file for temp and 1 for prec starting with the year 1850 for the historical runs or 2006 for the proyections, and can end with any year.
# beware that if you change the size of these matrices, or the number of indices <n.indices>, also the code to calculate the ensemble must be changed!

n.max.models=15 # maximum numb.of possible models (each one must have a subdir in the path_data dir)
n.max.runs=5 # maximum number of possible runs for each model (for both scenarios) # beware that if you change this value also the code to calculate the ensemble must be changed!

# matrix with the number of the runs for each model used for the scenary 2.6: (runs eliminated: mod1 r1, mod3 r1, mod6 r2, mod8 r2)
n.runs.rcp26<-matrix(0,n.max.runs,n.max.models) 
n.runs.rcp26[1,]=c(1,1,1,0,0,2,8, 2,1,1,1,1,1,1,1) # its first row stores the num.of the first run associated to each model: model #1 has run1, model #4 has no run associated, model #6 has run2
n.runs.rcp26[2,]=c(0,0,0,0,0,0,12,0,0,0,2,0,2,2,0) # its second row stores the num.of the eventual second run associated to each model (i.e: model #11 has run2 (r2i1p1) associated) 
n.runs.rcp26[3,]=c(0,0,0,0,0,0,0, 0,0,0,3,0,3,3,0) # its third row shows the number of the eventual third run associated to each model
n.runs.rcp26[4,]=c(0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) # its fourth row shows the number of the eventual fourth run associated to each model
n.runs.rcp26[5,]=c(0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) # its fifth row shows the number of the eventual fifth run associated to each model

# matrix with the number of the runs for each model used for the scenary 8.5:  (runs eliminated: mod3 r1)
n.runs.rcp85<-matrix(0,n.max.runs,n.max.models) 
n.runs.rcp85[1,]=c(0,0,1,2,0,0,0,0,0,0,1,1,1,1,1) # its first row stores the num.of the first run associated to each model: model #1 has run1, model #4 has no run associated, model #6 has run2
n.runs.rcp85[2,]=c(0,0,0,3,0,0,0,0,0,0,2,0,2,2,0) # its second row stores the num.of the eventual second run associated to each model (i.e: model #11 has run2 (r2i1p1) associated) 
n.runs.rcp85[3,]=c(0,0,0,4,0,0,0,0,0,0,3,0,3,3,0) # its third row shows the number of the eventual third run associated to each model
n.runs.rcp85[4,]=c(0,0,0,5,0,0,0,0,0,0,0,0,0,0,0) 
n.runs.rcp85[5,]=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)

# Root directory with all input data from CMIP4 models (historical and the two scenaries RCP 8.5 and 2.6), one subfolder for each model:
# (subfolder name must be an increasing number for 1 to the total number of models)
path.data='/home/Earth/ncortesi/Downloads/Bodegas_Torre/models'

# output dir for the reanalisis data (you must create them):
outputdir="/home/Earth/ncortesi/Downloads/Bodegas_Torre/reanalisis"

# names of the variables to open to calculate the climate indices:
vars=c("tas","pr")       # up to now there can be only exactly two values

n.indices=6  # total number of indices to evaluate, actually 6:

# 1. "Temperatura Media Anual"
# 2. "Temperatura media del ciclo vegetativo (Octubre a Abril)"
# 3. "Indice de Winkler para el periodo vegetativo (Octubre a Abril)"
# 4. "Winter Severity Index"
# 5. "Precipitacion Anual"
# 6. "Precipitacion durante el ciclo vegetativo (Octubre a Abril)

# notice that both tas and pr historical data must begin in January and in the same year (the exact year is not important since it is detected looking at the file name)
first.year.hist=1985  # The first year of the historical data (both for renalaysis and models). It is really 1986, but we need to start from the october of the previous year to calculate some indices
last.year.hist=2005   # The last year of the historical data. 

# notice that both tas and pr data for scenary RCP 2.6 AND 8.5 must begin in January and in the same year (the exact year is not important since it is detected looking at the file name)

first.year.rcp=2030   # The first year of the projections. Note that it is really 2031, but we need to start from the october of the previous year to calculate some indices)
last.year.rcp=2050   # The last year of the projections. Note that all years must obviously fall inside the time period of data files (1850-2005 fot the historical runs and 2006-2099 for the proyections)

# Localizacion parcelas::
parcelas.names=c("Coyhaique","Ñirehuao","La Tapera","Lago Verde")
parcelas.lat=c(-45.59,-45.27,-44.65,-44.24)
parcelas.lon=c(-72.06,-71.72,-71.67,-71.85)

# Localizacion malla de parcelas:
grid.nlon=7 # number of points in the longitudinal sense
grid.nlat=15 # number of points in the latitudinal sense
grid.res.lon=0.703125 # resolution in grados in the long. sense
grid.res.lat=0.70175 # resolution in grados in the latitud. sense
grid.corner=c(-47.3683028,-73.82812) # lat/lon coordinates of the lower left corn of the grid of parcelas

# Coordinates of the box of our Patagonia area:
pata.latmax=-43.5
pata.latmin=-46
pata.lonmin=285.5
pata.lonmax=290

# Extended Coordinates of the box of our Patagonia area: (the area shown in the maps)
bigpata.latmax=pata.latmax+10
bigpata.latmin=pata.latmin-10
bigpata.lonmax=pata.lonmax+2
bigpata.lonmin=pata.lonmin-2

dmax.idw=300 # maximum distance in km to calculate the correlations or the IDW

################  Graphical variables ############################################################################

# Escala de colores (see http://vis.supstat.com/2013/04/plotting-symbols-and-color-palettes/)
my.palette1<-c("lightblue","white",brewer.pal(9, "YlOrRd"))  #rev(brewer.pal(11, "RdYlBu"))  # it has only 11 colors!
my.palette2<-c("lightblue","white",brewer.pal(9, "YlOrRd")) #rev(brewer.pal(11, "RdYlBu"))  
my.palette3<-brewer.pal(9, "Greens") # only 9 colors
my.palette4<-rev(brewer.pal(9, "BuPu"))  
my.palette5<-brewer.pal(9, "Blues")
my.palette6<-brewer.pal(9, "Blues")  
my.palette<-list(my.palette1,my.palette2,my.palette3,my.palette4,my.palette5,my.palette6) 

# Intervalos:
my.brks1<-seq(-4,30,2) #c(-60,-40,-20,seq(-10,30,0.5),40)
my.brks2<-seq(-4,30,2) #c(-60,-40,-20,seq(-10,30,0.5),40)
my.brks3<-c(0,1,seq(200,3000,200),6000)
my.brks4<-c(-100,seq(0,10,0.5),40)
my.brks5<-c(seq(0,2000,10),4000,8000)
my.brks6<-c(seq(0,2000,10),4000,8000)
my.brks<-list(my.brks1,my.brks2,my.brks3,my.brks4,my.brks5,my.brks6)

# Units of measure:
my.units<-c("Grados Celsius","Grados Celsius","Grados Celsius","Grados Celsius","mm","mm")

# skip some labels not to show all labels in some plot:
my.subsampleg=c(1,1,1,1,5,5)

# the same but for the leyend added with colorBar:
my.subsamplegbar=c(1,1,1,1,5,5)

# show the line with 1200 degree days for the Winkler idex:
my.brks.dos<-list(NULL,NULL,1200,-15,NULL,NULL)

# change the color of the line to separate areas where grape can grow and where it can't:
my.contours.col<-list(NULL,NULL,"black","red",NULL,NULL)

# Escala de colores para los mapas de tendencias
my.palette1.trend<-brewer.pal(9,"YlOrBr")
my.palette2.trend<-brewer.pal(9,"YlOrBr")
my.palette3.trend<-brewer.pal(9,"Greens") # Winkler's Index
my.palette4.trend<-brewer.pal(9,"YlOrBr") # rev(brewer.pal(11,"RdBu"))
my.palette5.trend<-rev(brewer.pal(11,"RdBu"))
my.palette6.trend<-rev(brewer.pal(11,"RdBu"))
my.palette.trend<-list(my.palette1.trend,my.palette2.trend,my.palette3.trend,my.palette4.trend,my.palette5.trend,my.palette6.trend)

# Intervalos para los mapas de tendencias:
my.brks1.trend<-seq(0,2,0.1)
my.brks2.trend<-seq(0,2,0.1)
my.brks3.trend<-c(seq(0,300,30),400,500)
my.brks4.trend<-seq(0,1.4,0.1)
my.brks5.trend<-seq(-200,200,40)
my.brks6.trend<-seq(-200,200,40)
my.brks.trend<-list(my.brks1.trend,my.brks2.trend,my.brks3.trend,my.brks4.trend,my.brks5.trend,my.brks6.trend)

################  Derived variables ############################################################################
#n.models.hist<-length(models.hist) # total number of historical models
#n.models.rcp26<-length(models.rcp26) # total number of RCP 2.6 models
#n.models.rcp85<-length(models.rcp85) # total number of RCP 8.5 models

n.vars<-length(vars) # total number of model variables
          
index.name<-c("Temperatura Media Anual",
              "Temperatura Media (Octubre a Abril)",
              "Indice de Winkler (Octubre a Abril)",
              "Winter Severity Index",
              "Precipitacion Anual",
              "Precipitacion (Octubre a Abril)")

index.name.short<-c("Temp.Media Anual",
              "Temp.Media Oct-Abr",
              "Indice de Winkler",
              "Winter Sev.Index",
              "Prec.Anual",
              "Prec.Oct-Abr")

index.name0<-c("Temperatura_Media_Anual",
              "Temperatura_Media_Vegetativa",
              "Indice_de_Winkler",
              "Winter_Severity_Index",
              "Precipitacion_Anual",
              "Precipitacion_Vegetativa")

index.name.very.short<-c("Temp_med","Temp_veget","Winkler","W_Severity","Prec_anual","Prec_veget")

n.parcelas<-length(parcelas.names) # number of parcelas



n.months.hist<-((last.year.hist-first.year.hist+1)*12) # number of historical months to extract starting from the first year
n.years.hist=n.months.hist/12

n.months.rcp<-((last.year.rcp-first.year.rcp+1)*12) # number of future months to extract starting from the first year for both rcp26 and rcp85 (usually it is the same as n.months.hist)
n.years.rcp=n.months.rcp/12

n.years.trans<-first.year.rcp-last.year.hist-1  #24 # number of years in the transition period from year following the last year of the historical period to the year before the first year of the rcp period
n.years.tot <- n.years.hist + n.years.trans + n.years.rcp # total number of years

# grid de parcelas:
n.grid.points<-grid.nlon*grid.nlat
grid.lat.list<-rev(seq(grid.corner[1],grid.corner[1]+(grid.nlat-1)*grid.res.lat,by=grid.res.lat))   # ex: -44,-45,-46,-47
grid.lon.list<-seq(grid.corner[2],grid.corner[2]+(grid.nlon-1)*grid.res.lon,by=grid.res.lon)       # ex: -73,-72,-71
grid.lat<-rep(grid.lat.list,grid.nlon)  # ex:  -44,-45,-46,-47, -44,-45,-46,-47, -44,-45,-46,-47
grid.lon<-rep(grid.lon.list,each=grid.nlat) # ex: -73,-73,-73,-73,-72,-72,-72,-72,-71,-71,-71,-71

########### Load the observed data of temp and prec from Reanalysis and calculate and save all indices and maps ########
if(rean==TRUE){
  
var1<-Load(var='tas',exp=NULL,obs = 'ERAint' ,sdates=paste0(first.year.hist,"0101"), storefreq = "monthly", sampleperiod = 1,output = "lonlat", method = "conservative")#, grid='r512x256')
var2<-Load(var='prlr',exp=NULL,obs = 'ERAint' ,sdates=paste0(first.year.hist,"0101"), storefreq = "monthly", sampleperiod = 1, output = "lonlat", method = "conservative")#, grid='r512x256')

temp.rean<-var1$obs[1,1,1,1:n.months.hist,,] # var1 format: 1,1,1,month,lat,lon;   temperature format: month,lat,lon
prec.rean<-var2$obs[1,1,1,1:n.months.hist,,]
#temp.rea2<-apply(temp.rea,2,rev)

#lat.rea<-sort(var1$lat)
#lon.rea<-sort(var1$lon)
lat.rean<-var1$lat  # ojo que la latitud esta desde valores mas altos a mas bajos, pero tambien si no la inviertes, la funcion PlotEquiMap dibuja bien la latitud.
lon.rean<-var1$lon
n.lat.rean<-length(lat.rean)
n.lon.rean<-length(lon.rean)

temp.rean<-temp.rean-273.15
prec.rean<-prec.rean*60*60*24*1000 # convert prec.from m/s to mm for day; must still convert from mm/day to mm/month:

month31=c(1,3,5,7,8,10,12) # meses con 31 dias
my.months31<-rep(month31,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month31)) # select only months with 31 days
prec.rean[my.months31,,]<-prec.rean[my.months31,,]*31 # multiply prec of these months for 31

month30=c(4,6,9,11) # meses con 30 dias
my.months30<-rep(month30,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month30)) # select only months with 30 days
prec.rean[my.months30,,]<-prec.rean[my.months30,,]*30 # multiply prec of these months for 30

month28=2 # meses con 28 dias
my.months28<-rep(month28,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month28)) # select only months with 28 days
prec.rean[my.months28,,]<-prec.rean[my.months28,,]*28.25 # multiply prec of these months for 28.25

rm(var1,var2)

# Calculate the climate index for the reanlaysis and for each run and save results:
index.rean<-indices(temp.rean,prec.rean,n.months.hist) # For Reanalysis
save(index.rean,file=paste0(outputdir,"/indices.RData"))

# Save global maps with indices::
for(my.index in 1:n.indices){
    png(filename=paste0(outputdir,"/Worldmap_indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
    layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
    #layout.show(2)
    my.toptitle<-paste(index.name[my.index],"(ERAI)")
    PlotEquiMap2(index.rean[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,t(index.rean[[my.index]]),t(index.rean[[my.index]]),NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=FALSE)
    ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=1)
    dev.off()
}

# the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
my.lat.pos<-which(lat.rean<pata.latmax & lat.rean>pata.latmin)
my.lon.pos<-which(lon.rean<pata.lonmax & lon.rean>pata.lonmin)
my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
my.lon<-lon.rean[my.lon.pos]

for(my.index in 1:n.indices){
    png(filename=paste0(outputdir,"/Patagonia_indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
    layout(matrix(c(1,1,1,1,1,1,2), 1, 7, byrow = TRUE))  #layout.show(2) to see the window distribution
    par(oma=c(1,0,0,0)) # add 1 cm of white space to the bottom border
    my.toptitle<-paste(index.name[my.index],"(ERAI)")
    PlotEquiMap2(index.rean[[my.index]][my.lat.pos,my.lon.pos],my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,t(index.rean[[my.index]][my.lat.pos,my.lon.pos]),t(index.rean[[my.index]][my.lat.pos,my.lon.pos]),NULL,NULL)[[my.index]],
            brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
    
    my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
    map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
    ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=T,cex=1,subsampleg=my.subsamplegbar[[my.index]])

    dev.off()
}

# the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
my.lat.pos<-which(lat.rean<bigpata.latmax & lat.rean>bigpata.latmin)
my.lon.pos<-which(lon.rean<bigpata.lonmax & lon.rean>bigpata.lonmin)
my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
my.lon<-lon.rean[my.lon.pos]

for(my.index in 1:n.indices){
    png(filename=paste0(outputdir,"/BigPatagonia_indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
    layout(matrix(c(1,1,1,1,2), 1, 5, byrow = TRUE))
    #layout.show(2)
    par(oma=c(1,0,0,0.5)) # add 1 cm of white space to the bottom border
    my.toptitle<-paste(index.name.short[my.index],"(ERAI)")
    PlotEquiMap2(index.rean[[my.index]][my.lat.pos,my.lon.pos],my.lon,my.lat,toptitle=my.toptitle,sizetit = 1,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,t(index.rean[[my.index]][my.lat.pos,my.lon.pos]),t(index.rean[[my.index]][my.lat.pos,my.lon.pos]),NULL,NULL)[[my.index]],
            brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
    
    my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
    map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas    
    ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=T,cex=1.5,subsampleg=my.subsamplegbar[[my.index]])
    
    dev.off()
}


# assign each parcela to a grid point of the reanalysis:
p.pos.rean<-list()
for (p in 1:n.parcelas) p.pos.rean[[p]]=nearest(parcelas.lat[p],parcelas.lon[p],lat.rean,lon.rean)

# save the index values for each of the parcelas:
parcelas.indices.rean<-array(NA,c(n.parcelas,n.indices))
for (p in 1:n.parcelas) { for (i in 1:n.indices) { parcelas.indices.rean[p,i]<-index.rean[[i]][p.pos.rean[[p]][1],p.pos.rean[[p]][2]] } }
save(parcelas.indices.rean,file=paste0(outputdir,"/indices_parcelas.RData"))

# save the yearly values of the indexes for each of the parcelas:
index.rean.year<-array(NA,c(n.indices,n.years.hist,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),first.year.hist:last.year.hist,paste0("Parcela",1:n.parcelas)))

for (p in 1:n.parcelas) {
   for (year in 1:(n.years.hist)) {
      begin.month = 1 + 12*(year-1)
      my.months<-begin.month:n.months.hist
      
      # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
      tt.rean<-array(temp.rean[my.months,p.pos.rean[[p]][1],p.pos.rean[[p]][2]],c(length(my.months),1,1))
      pp.rean<-array(prec.rean[my.months,p.pos.rean[[p]][1],p.pos.rean[[p]][2]],c(length(my.months),1,1))

      index.rean.year[1,year,p]<-index1(tt.rean,12) # starting from 1985, select only one year of data at time
      if (year < n.years.hist) index.rean.year[2,year,p]<-index2(tt.rean,24) # starting from 1985, select 2 years of data at time 
      if (year < n.years.hist) index.rean.year[3,year,p]<-index3(tt.rean,24) # starting from 1985, select 2 years of data at time 
      index.rean.year[4,year,p]<-index4(tt.rean,12) # starting from 1985, select only one year of data at time 
      index.rean.year[5,year,p]<-index5(pp.rean,12) # starting from 1985, select only one year of data at time 
      if (year < n.years.hist) index.rean.year[6,year,p]<-index6(pp.rean,24) # starting from 1985, select 2 years of data at time 
   }
}

#plot(1985:2005,index.rean.year[1,,1],type="o")
save(index.rean.year,file=paste0(outputdir,"/indices_parcelas_anuales.RData"))

# same as above, but for the grid of parcelas:
grid.pos.rean<-list()
for (p in 1:n.grid.points) grid.pos.rean[[p]]=nearest(grid.lat[p],grid.lon[p],lat.rean,lon.rean)

# save the index values for each of the grid points:
grid.indices.rean<-array(NA,c(n.grid.points,n.indices))
for (p in 1:n.grid.points) { for (i in 1:n.indices) { grid.indices.rean[p,i]<-index.rean[[i]][grid.pos.rean[[p]][1],grid.pos.rean[[p]][2]] } }
save(grid.indices.rean,file=paste0(outputdir,"/indices_grid_parcelas.RData"))

#save.image("/home/ncortesi/Downloads/Bodegas_Torre/Bodega_base.RData")

} # close if on rean



##########################################################################################################################################################   
############### Load, calculate indices, interpolate, visualize and save all the runs for the historical period and for the two scenarios ################
##########################################################################################################################################################

print("Loading model data...")
#mod=1 # number of the model to load in the path.data dir
#run=1 # number of the run to load in the path.data/mod dir
rcp26<-rcp85<-FALSE
for(my.mod in 1:n.max.models){
  for(my.run in 1:n.max.runs){
    mod=my.mod
    if(n.runs.rcp26[my.run,my.mod]!=0 || n.runs.rcp85[my.run,my.mod]!=0){
       if(n.runs.rcp26[my.run,my.mod]!=0 && n.runs.rcp85[my.run,my.mod]==0){
         run=n.runs.rcp26[my.run,my.mod]
         rcp26=TRUE # put true if the selected model and run has all the data for scenary RCP 2.6
         rcp85=FALSE  # put true if the selected model and run has all the data for scenary RCP 8.5
       }
       if(n.runs.rcp26[my.run,my.mod]==0 && n.runs.rcp85[my.run,my.mod]!=0){
         run=n.runs.rcp85[my.run,my.mod]
         rcp26=FALSE # put true if the selected model and run has all the data for scenary RCP 2.6
         rcp85=TRUE  # put true if the selected model and run has all the data for scenary RCP 8.5
       }
       if(n.runs.rcp26[my.run,my.mod]!=0 && n.runs.rcp85[my.run,my.mod]!=0){ 
         run=n.runs.rcp26[my.run,my.mod]  # in this case it is indifferent which of two two run number we select because they are the same, so we select that for rcp 2.6
         rcp26=TRUE # put true if the selected model and run has all the data for scenary RCP 2.6
         rcp85=TRUE  # put true if the selected model and run has all the data for scenary RCP 8.5
       }

#print(my.mod);print(my.run);print(n.runs.rcp26[my.run,my.mod]);print(n.runs.rcp85[my.run,my.mod]);print(rcp26);print(rcp85)  # for the debug
       
########### Load the historic data of temp and prec from each run of CMIP5 and calculate and save all indices and maps ########

print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(paste0("           Analyzing Model ",mod," Run ",run))
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

# import the selected run of the selected model:

#my.bar<-tkProgressBar(title = "Analyzing data...", label = "Please wait",min = 0, max = 100, initial = 0, width = 500)

    #setTkProgressBar(my.bar, run*100/n.runs.hist[mod], label="Please wait")
    cat("Processing Historical...")

    my.dir.hist<-paste0(path.data,"/",mod,"/r",run,"/historical")
    my.files<-list.files(path=my.dir.hist,pattern="\\.nc$") # select all files inside the input data directory
    if(length(my.files)==0) print(paste0("There are no files in the input directory ",my.dir.hist))
    my.files.splitted<-strsplit(my.files,"_") # separate the suffix from the time range in the file name
    first.year.hist.file <- as.integer(substr(my.files.splitted[[1]][2],1,4)) # The first year of data in ALL the historical files for tas and prec (usually 1850)
    shift.hist<-12*(first.year.hist-first.year.hist.file) # number of months from the beginning of the data file (year 1850) to the beginning of the historical period used in the study (1985 in our case)

    # load the data for the first variable (i.e: tas):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[1]) my.file.var1<-my.files[f]
    
    my.path1<-paste0(my.dir.hist,"/",my.file.var1) # the full path of the first file in the directory (there is only one)
    my.ncdf1<-open.ncdf(my.path1) # open the netcdf file
    var1<-get.var.ncdf(my.ncdf1,varid=vars[1]) # var1 format: [lon,lat,month]

    # load the data for the second variable (i.e: pr):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[2]) my.file.var2<-my.files[f]
    my.path2<-paste0(my.dir.hist,"/",my.file.var2) # the full path of the first file in the directory (there is only one)
    my.ncdf2<-open.ncdf(my.path2) # open the netcdf file
    var2<-get.var.ncdf(my.ncdf2,varid=vars[2]) # var1 format: [lon,lat,month]

    # Get lat and lon list:
    lat.hist<-get.var.ncdf(my.ncdf1,varid="latitude") # <- get the latitude (it is the same both for temp and prec data and for all runs of the same model)
    lon.hist<-get.var.ncdf(my.ncdf1,varid="longitude") # <- get the longitude
    n.lat.hist<-length(lat.hist)
    n.lon.hist<-length(lon.hist)      
    
    close(my.ncdf1)
    close(my.ncdf2)
    
    #array where to put all the data of the runs (format: [lon,lat,month])
    temp.hist<-prec.hist<-array(NA,c(n.lon.hist,n.lat.hist,n.months.hist)) 

    # select only the months in the historical period selected because we know that the first year of loaded data starts always in the same year:
    temp.hist[,,]<-var1[,,(1+shift.hist):(n.months.hist+shift.hist)] 
    prec.hist[,,]<-var2[,,(1+shift.hist):(n.months.hist+shift.hist)]

    rm(var1,var2)    
    
    # check if the first dimension is the longitude or the latitude:
    if(dim(temp.hist)[1]>dim(temp.hist)[2])  models.firstdim="lon"
    if(dim(temp.hist)[1]<dim(temp.hist)[2])  models.firstdim="lat"
    if(dim(temp.hist)[1]==dim(temp.hist)[2]) models.firstdim="lon" # only the model num.11, IPSL-CM5A-LR, has the same number of points for both dimensions

    # temp.hist and prec.hist format is usually: [lon,lat,month] but we must change it to [month,lat,lon] to calculate the climate indices:    
    if(models.firstdim=="lon"){
       temp.hist<-aperm(temp.hist,c(3,2,1))
       prec.hist<-aperm(prec.hist,c(3,2,1))
    } else {  # in this case, the first dimension is the latitude, so we haven't to swap it:
       temp.hist<-aperm(temp.hist,c(3,1,2))
       prec.hist<-aperm(prec.hist,c(3,1,2))
    }
    
    # Convert temperature to Celsius:
    temp.hist<-temp.hist-273.15
    prec.hist<-prec.hist*60*60*24 # convert prec.from kg m-2 s-1 to mm for day; must still convert from mm/day to mm/month:

    month31=c(1,3,5,7,8,10,12) # meses con 31 dias
    my.months31<-rep(month31,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month31)) # select only months with 31 days
    prec.hist[my.months31,,]<-prec.hist[my.months31,,]*31 # multiply prec of these months for 31

    month30=c(4,6,9,11) # meses con 30 dias
    my.months30<-rep(month30,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month30)) # select only months with 30 days
    prec.hist[my.months30,,]<-prec.hist[my.months30,,]*30 # multiply prec of these months for 30

    month28=2 # meses con 28 dias
    my.months28<-rep(month28,n.years.hist)+rep(0:(n.years.hist-1)*12,each=length(month28)) # select only months with 28 days
    prec.hist[my.months28,,]<-prec.hist[my.months28,,]*28.25 # multiply prec of these months for 28.25

    # Calculate the climate index for each historical model and for each run and save the results:
    index.hist<-indices(temp.hist,prec.hist,n.months.hist) # For Historical
    #save(index.hist,file=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_indices.RData"))
    save(index.hist,file=paste0(path.data,"/",mod,"/r",run,"/historical/Indices.RData"))

    # Save global maps with indices:
    for(my.index in 1:n.indices){
       #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
       png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

       layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
       #layout.show(2)
       my.toptitle<-paste0(index.name[my.index]," (Historical Model ",mod," Run ",run,")")
       if(models.firstdim=="lat") {contour.data<-index.hist[[my.index]]} else {contour.data<-t(index.hist[[my.index]])}
       if(models.firstdim=="lat") {plot.data<-index.hist[[my.index]]} else {plot.data<-t(index.hist[[my.index]])}

       PlotEquiMap2(plot.data,lon.hist,lat.hist,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,contour.data,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

       ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
       dev.off()
    }
    
    # the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.hist<pata.latmax & lat.hist>pata.latmin)
    my.lon.pos<-which(lon.hist<pata.lonmax & lon.hist>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.hist<pata.latmax+2 & lat.hist>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.hist<pata.lonmax+2 & lon.hist>pata.lonmin-2)
    my.lat<-lat.hist[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.hist[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
        my.toptitle<-paste0(index.name[my.index]," (Historical Model ",mod," Run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.hist[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.hist[[my.index]][my.lat.pos,my.lon.pos]}
        
        layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
        #layout.show(2)
        #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
        dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.hist < bigpata.latmax & lat.hist > bigpata.latmin)
    my.lon.pos<-which(lon.hist < bigpata.lonmax & lon.hist > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.hist<bigpata.latmax+2 & lat.hist>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.hist<bigpata.lonmax+2 & lon.hist>bigpata.lonmin-2)
    my.lat<-lat.hist[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.hist[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

        my.toptitle<-paste0(index.name.short[my.index]," (Historical Model ",mod," Run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.hist[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.hist[[my.index]][my.lat.pos,my.lon.pos]}
        
        layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
        #layout.show(2)
        par(oma=c(1,0,0,0.2))
        #par(mfrow=c(2,1))
        #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
        dev.off()
    }
    
    # assign each parcela to a grid point of the historical model:
    p.pos.hist<-list()
    for (p in 1:n.parcelas) p.pos.hist[[p]]=nearest(parcelas.lat[p],parcelas.lon[p],lat.hist,lon.hist)

    # save the index values for each of the parcelas and the number of different grid points:
    parcelas.indices.hist<-array(NA,c(n.parcelas,n.indices))
    for (p in 1:n.parcelas) { for (i in 1:n.indices) { parcelas.indices.hist[p,i]<-index.hist[[i]][p.pos.hist[[p]][1],p.pos.hist[[p]][2]] } }
    #save(parcelas.indices.hist,file=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_indices_parcelas.RData"))
    save(parcelas.indices.hist,file=paste0(path.data,"/",mod,"/r",run,"/historical/Indices_parcelas.RData"))

    # save the yearly values of the indexes for each of the parcelas:
    index.hist.year<-array(NA,c(n.indices,n.years.hist,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),first.year.hist:last.year.hist,paste0("Parcela",1:n.parcelas)))

    for (p in 1:n.parcelas) {
       for (year in 1:(n.years.hist)) {
          begin.month = 1 + 12*(year-1)
          my.months<-begin.month:n.months.hist
      
          # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
          tt.hist<-array(temp.hist[my.months,p.pos.hist[[p]][1],p.pos.hist[[p]][2]],c(length(my.months),1,1))
          pp.hist<-array(prec.hist[my.months,p.pos.hist[[p]][1],p.pos.hist[[p]][2]],c(length(my.months),1,1))

          index.hist.year[1,year,p]<-index1(tt.hist,12) # starting from 1985, select only one year of data at time
          if (year < n.years.hist) index.hist.year[2,year,p]<-index2(tt.hist,24) # starting from 1985, select 2 years of data at time 
          if (year < n.years.hist) index.hist.year[3,year,p]<-index3(tt.hist,24) # starting from 1985, select 2 years of data at time 
          index.hist.year[4,year,p]<-index4(tt.hist,12) # starting from 1985, select only one year of data at time 
          index.hist.year[5,year,p]<-index5(pp.hist,12) # starting from 1985, select only one year of data at time 
          if (year < n.years.hist) index.hist.year[6,year,p]<-index6(pp.hist,24) # starting from 1985, select 2 years of data at time 
       }
    }

    #plot(1985:2005,index.hist.year[1,,1],type="o")

    #save(index.hist.year,file=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_indices_parcelas_anuales.RData"))
    save(index.hist.year,file=paste0(path.data,"/",mod,"/r",run,"/historical/Indices_parcelas_anuales.RData"))

    # same as above, but for the grid of parcelas:
    grid.pos.hist<-list()
    for (p in 1:n.grid.points) grid.pos.hist[[p]]=nearest(grid.lat[p],grid.lon[p],lat.hist,lon.hist)

    # save the index values for each of the grid points:
    grid.indices.hist<-array(NA,c(n.grid.points,n.indices))
    for (p in 1:n.grid.points) { for (i in 1:n.indices) { grid.indices.hist[p,i]<-index.hist[[i]][grid.pos.hist[[p]][1],grid.pos.hist[[p]][2]] } }
    save(grid.indices.hist,file=paste0(path.data,"/",mod,"/r",run,"/historical/Indices_grid_parcelas.RData"))

    
    # interpolate each indice on the same grid of the Reanalysis:
    index.hist.array<-array(NA,c(n.indices,n.lat.hist,n.lon.hist))
    for(i in 1:n.indices) index.hist.array[i,,]<-index.hist[[i]]

    #if(exists("index.hist.interp")==TRUE) rm(index.hist.interp)
    cat("done\n");cat("Interpolating...")
    index.hist.interp<-bilinear(lat.rean,lon.rean,lat.hist,lon.hist,index.hist.array)  # interpolation with the bilinear method
    cat("done\n");cat("Plotting data...")

    # there is a bug that sometimes returns false values from the bilinear function if it returns a list; so we modified it to return a matrix instead, but we must convert it back to a list to plot it:
    interp<-list(); for(l in 1:n.indices) interp[[l]]<-index.hist.interp[l,,]
    rm(index.hist.interp); index.hist.interp=interp; rm(interp)

    save(index.hist.interp,file=paste0(path.data,"/",mod,"/r",run,"/historical/Indices_interp.RData"))

    # Save global interpolated maps of indices:
    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/Interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Historical Model ",mod," Run ",run," interpolated)")
      if(models.firstdim=="lat") {contour.data<-index.hist.interp[[my.index]]} else {contour.data<-t(index.hist.interp[[my.index]])}

      PlotEquiMap2(index.hist.interp[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,contour.data,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)
      
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for interpolated Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean<pata.latmax & lat.rean>pata.latmin)
    my.lon.pos<-which(lon.rean<pata.lonmax & lon.rean>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<pata.latmax+2 & lat.rean>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<pata.lonmax+2 & lon.rean>pata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/Interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
      my.toptitle<-paste0(index.name[my.index]," (Historical Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.hist.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.hist.interp[[my.index]][my.lat.pos,my.lon.pos]}

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/historical/Interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      my.toptitle<-paste0(index.name.short[my.index]," (Historical Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.hist.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.hist.interp[[my.index]][my.lat.pos,my.lon.pos]}

      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=4,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }
    

#~~~Load the projections from CMIP5 2.6~~~

#my.bar<-tkProgressBar(title = "Analizing data...", label = "Please wait",min = 0, max = 100, initial = 0, width = 500)
if(rcp26==TRUE){
    print("done");cat("Processing scenary RCP 2.6...")
    
    #setTkProgressBar(my.bar, run*100/n.runs[mod], label="Please wait")
    my.dir.rcp26<-paste0(path.data,"/",mod,"/r",run,"/2.6")
    my.files<-list.files(path=my.dir.rcp26,pattern="\\.nc$") # select all files inside the input data directory
    if(length(my.files)==0) print(paste0("There are no files in the input directory ",my.dir.rcp26))
    my.files.splitted<-strsplit(my.files,"_") # separate the suffix from the time range in the file name
    first.year.rcp.file <- as.integer(substr(my.files.splitted[[1]][2],1,4)) # The first year of data in ALL the rcp 2.6 and 8.5 files for tas and prec (usually 2006)    
    shift.rcp<-12*(first.year.rcp-first.year.rcp.file) # number of months from the beginning of the data file (year 2006) to the beginning of the future period used in the study (2030 in our case)

    # load the data for the first variable (i.e: tas):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[1]) my.file.var1<-my.files[f]
    my.path1<-paste0(my.dir.rcp26,"/",my.file.var1) # the full path of the first file in the directory (there is only one)
    my.ncdf1<-open.ncdf(my.path1) # open the netcdf file
    var1<-get.var.ncdf(my.ncdf1,varid=vars[1]) # var1 format: [lon,lat,month]

    # load the data for the second variable (i.e: pr):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[2]) my.file.var2<-my.files[f]
    my.path2<-paste0(my.dir.rcp26,"/",my.file.var2) # the full path of the first file in the directory (there is only one)
    my.ncdf2<-open.ncdf(my.path2) # open the netcdf file
    var2<-get.var.ncdf(my.ncdf2,varid=vars[2]) # var1 format: [lon,lat,month]

    lat.rcp26<-get.var.ncdf(my.ncdf1,varid="latitude") # <- get the latitude (it is the same both for temp and prec data and for all runs of the same model)
    lon.rcp26<-get.var.ncdf(my.ncdf1,varid="longitude") # <- get the longitude
    n.lat.rcp26<-length(lat.rcp26)
    n.lon.rcp26<-length(lon.rcp26)      
    
    close(my.ncdf1)
    close(my.ncdf2)
    
    #array where to put all the data of the runs during the study period (format: [lon,lat,month])
    temp.rcp26<-prec.rcp26<-array(NA,c(n.lon.rcp26,n.lat.rcp26,n.months.rcp))

    temp.rcp26[,,]<-var1[,,(1+shift.rcp):(n.months.rcp+shift.rcp)] 
    prec.rcp26[,,]<-var2[,,(1+shift.rcp):(n.months.rcp+shift.rcp)]

    #array where to put all the data of the runs for the transition period starting from last day of historica data (2006) up to the beginning of the future period (2030) (format: [lon,lat,month])
    temp.trans26<-prec.trans26<-array(NA,c(n.lon.rcp26,n.lat.rcp26,shift.rcp))
    temp.trans26[,,]<-var1[,,1:shift.rcp] 
    prec.trans26[,,]<-var2[,,1:shift.rcp]
    
    rm(var1,var2)
    
    # check if the first dimension is the longitude or the latitude:
    if(dim(temp.rcp26)[1]>dim(temp.rcp26)[2])  models.firstdim="lon"
    if(dim(temp.rcp26)[1]<dim(temp.rcp26)[2])  models.firstdim="lat"
    if(dim(temp.rcp26)[1]==dim(temp.rcp26)[2]) models.firstdim="lon"  # only the model num.11, IPSL-CM5A-LR, has the same number of points for both dimensions
    
    # temp.fut1 and prec.fut1 format is: [lon,lat,month] but we must change it to [month,lat,lon] to calculate the climate indices:
    if(models.firstdim=="lon"){
       temp.rcp26<-aperm(temp.rcp26,c(3,2,1))
       prec.rcp26<-aperm(prec.rcp26,c(3,2,1))
       temp.trans26<-aperm(temp.trans26,c(3,2,1))
       prec.trans26<-aperm(prec.trans26,c(3,2,1))
    } else {  # in this case, the first dimension is the latitude, so we haven't to swap it:
       temp.rcp26<-aperm(temp.rcp26,c(3,1,2))
       prec.rcp26<-aperm(prec.rcp26,c(3,1,2))
       temp.trans26<-aperm(temp.trans26,c(3,1,2))
       prec.trans26<-aperm(prec.trans26,c(3,1,2))
    }
    
    # Convert temperature to Celsius:
    temp.rcp26<-temp.rcp26-273.15
    prec.rcp26<-prec.rcp26*60*60*24 # convert prec.from kg m-2 s-1 to mm for day; must still convert from mm/day to mm/month:
    temp.trans26<-temp.trans26-273.15
    prec.trans26<-prec.trans26*60*60*24
    
    month31=c(1,3,5,7,8,10,12) # meses con 31 dias
    my.months31<-rep(month31,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month31)) # select only months with 31 days
    prec.rcp26[my.months31,,]<-prec.rcp26[my.months31,,]*31 # multiply prec of these months for 31
    my.months31<-rep(month31,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month31)) # select only months with 31 days
    prec.trans26[my.months31,,]<-prec.trans26[my.months31,,]*31 # multiply prec of these months for 31

    month30=c(4,6,9,11) # meses con 30 dias
    my.months30<-rep(month30,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month30)) # select only months with 30 days
    prec.rcp26[my.months30,,]<-prec.rcp26[my.months30,,]*30 # multiply prec of these months for 30
    my.months30<-rep(month30,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month30)) # select only months with 30 days
    prec.trans26[my.months30,,]<-prec.trans26[my.months30,,]*30 # multiply prec of these months for 30

    month28=2 # meses con 28 dias
    my.months28<-rep(month28,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month28)) # select only months with 28 days
    prec.rcp26[my.months28,,]<-prec.rcp26[my.months28,,]*28.25 # multiply prec of these months for 28.25
    my.months28<-rep(month28,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month28)) # select only months with 28 days
    prec.trans26[my.months28,,]<-prec.trans26[my.months28,,]*28.25 # multiply prec of these months for 28.25

    # Calculate the climate index for each model and for each run and save results:
    index.rcp26<-indices(temp.rcp26,prec.rcp26,n.months.rcp) 
    #save(index.rcp26,file=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_indices.RData"))
    save(index.rcp26,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices.RData"))
                       
    # Save global maps with indices:
    for(my.index in 1:n.indices){
       #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
       png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

       layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
       #layout.show(2)
       my.toptitle<-paste0(index.name[my.index]," (RCP 2.6 ","Model ",mod," Run ",run,")")
       if(models.firstdim=="lat") {contour.data<-index.rcp26[[my.index]]} else {contour.data<-t(index.rcp26[[my.index]])}
       if(models.firstdim=="lat") {plot.data<-index.rcp26[[my.index]]} else {plot.data<-t(index.rcp26[[my.index]])}

       PlotEquiMap2(plot.data,lon.rcp26,lat.rcp26,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

       ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
       dev.off()
    }
    
    # the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rcp26<pata.latmax & lat.rcp26>pata.latmin)
    my.lon.pos<-which(lon.rcp26<pata.lonmax & lon.rcp26>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rcp26<pata.latmax+2 & lat.rcp26>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rcp26<pata.lonmax+2 & lon.rcp26>pata.lonmin-2)
    my.lat<-lat.rcp26[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rcp26[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)

        my.toptitle<-paste0(index.name[my.index]," (RCP 2.6 Model ",mod," Run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.rcp26[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp26[[my.index]][my.lat.pos,my.lon.pos]}
        
        layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
        #layout.show(2)
        #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
        dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rcp26 < bigpata.latmax & lat.rcp26 > bigpata.latmin)
    my.lon.pos<-which(lon.rcp26 < bigpata.lonmax & lon.rcp26 > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rcp26<bigpata.latmax+2 & lat.rcp26>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rcp26<bigpata.lonmax+2 & lon.rcp26>bigpata.lonmin-2)
    my.lat<-lat.rcp26[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rcp26[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

        my.toptitle<-paste0(index.name.short[my.index]," (RCP 2.6 Model ",mod," Run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.rcp26[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp26[[my.index]][my.lat.pos,my.lon.pos]}  
        if(models.firstdim=="lat") {contour.data<-index.rcp26[[my.index]][my.lon.pos,my.lat.pos]} else {contour.data<-t(index.rcp26[[my.index]][my.lat.pos,my.lon.pos])}
        
        layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
        #layout.show(2)
        par(oma=c(1,0,0,0.5))
        #par(mfrow=c(2,1))
        #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
            #contours=NULL,intylat=1,intxlon=1,drawleg=F)
    
        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
        dev.off()
    }
    
    # assign each parcela to a grid point of the rcp26 model:
    p.pos.rcp26<-list()
    for (p in 1:n.parcelas) p.pos.rcp26[[p]]=nearest(parcelas.lat[p],parcelas.lon[p],lat.rcp26,lon.rcp26)

    # save the index values for each of the parcelas and the number of different grid points:
    parcelas.indices.rcp26<-array(NA,c(n.parcelas,n.indices))
    for (p in 1:n.parcelas) { for (i in 1:n.indices) { parcelas.indices.rcp26[p,i]<-index.rcp26[[i]][p.pos.rcp26[[p]][1],p.pos.rcp26[[p]][2]] } }
    #save(parcelas.indices.rcp26,file=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_indices_parcelas.RData"))
    save(parcelas.indices.rcp26,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices_parcelas.RData"))

    # save the yearly values of the indexes for each of the parcelas for the  period 2030-2050:
    index.rcp26.year<-array(NA,c(n.indices,n.years.rcp,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),first.year.rcp:last.year.rcp,paste0("Parcela",1:n.parcelas)))

    for (p in 1:n.parcelas) {
       for (year in 1:(n.years.rcp)) {
          begin.month = 1 + 12*(year-1)
          my.months<-begin.month:n.months.rcp
      
          # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
          tt.rcp26<-array(temp.rcp26[my.months,p.pos.rcp26[[p]][1],p.pos.rcp26[[p]][2]],c(length(my.months),1,1))
          pp.rcp26<-array(prec.rcp26[my.months,p.pos.rcp26[[p]][1],p.pos.rcp26[[p]][2]],c(length(my.months),1,1))

          index.rcp26.year[1,year,p]<-index1(tt.rcp26,12) # starting from 2030, select only one year of data at time
          if (year < n.years.rcp) index.rcp26.year[2,year,p]<-index2(tt.rcp26,24) # starting from 2030, select 2 years of data at time 
          if (year < n.years.rcp) index.rcp26.year[3,year,p]<-index3(tt.rcp26,24) # starting from 2030, select 2 years of data at time 
          index.rcp26.year[4,year,p]<-index4(tt.rcp26,12) # starting from 2030, select only one year of data at time 
          index.rcp26.year[5,year,p]<-index5(pp.rcp26,12) # starting from 2030, select only one year of data at time 
          if (year < n.years.rcp) index.rcp26.year[6,year,p]<-index6(pp.rcp26,24) # starting from 2030, select 2 years of data at time 
       }
    }

    # save the yearly values of the indexes for each of the parcelas for the transition period 2006-2029:
    index.trans26.year<-array(NA,c(n.indices,shift.rcp/12,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),(last.year.hist+1):(first.year.rcp-1),paste0("Parcela",1:n.parcelas)))

    for (p in 1:n.parcelas) {
       for (year in 1:(shift.rcp/12)) {
          begin.month = 1 + 12*(year-1)
          my.months<-begin.month:shift.rcp
      
          # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
          tt.trans26<-array(temp.trans26[my.months,p.pos.rcp26[[p]][1],p.pos.rcp26[[p]][2]],c(length(my.months),1,1))
          pp.trans26<-array(prec.trans26[my.months,p.pos.rcp26[[p]][1],p.pos.rcp26[[p]][2]],c(length(my.months),1,1))

          index.trans26.year[1,year,p]<-index1(tt.trans26,12) # starting from 2006, select only one year of data at time
          if (year < shift.rcp/12) index.trans26.year[2,year,p]<-index2(tt.trans26,24) # starting from 2006, select 2 years of data at time 
          if (year < shift.rcp/12) index.trans26.year[3,year,p]<-index3(tt.trans26,24) 
          index.trans26.year[4,year,p]<-index4(tt.trans26,12)
          index.trans26.year[5,year,p]<-index5(pp.trans26,12)
          if (year < shift.rcp/12) index.trans26.year[6,year,p]<-index6(pp.trans26,24)
       }
    }

    #plot(2030:2050,index.rcp26.year[1,,1],type="o")
         
    #save(index.rcp26.year,file=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_indices_parcelas_anuales.RData"))
    save(index.rcp26.year,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices_parcelas_anuales.RData"))

    #plot(2006:2029,index.trans26.year[1,,1],type="o")
    
    #save(index.trans26.year,file=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_indices_parcelas_anuales_transition.RData"))
    save(index.trans26.year,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices_parcelas_anuales_transition.RData"))

    # same as above, but for the grid of parcelas:
    grid.pos.rcp26<-list()
    for (p in 1:n.grid.points) grid.pos.rcp26[[p]]=nearest(grid.lat[p],grid.lon[p],lat.rcp26,lon.rcp26)

    # save the index values for each of the grid points:
    grid.indices.rcp26<-array(NA,c(n.grid.points,n.indices))
    for (p in 1:n.grid.points) { for (i in 1:n.indices) { grid.indices.rcp26[p,i]<-index.rcp26[[i]][grid.pos.rcp26[[p]][1],grid.pos.rcp26[[p]][2]] } }
    #save(grid.indices.rean,file=paste0(outputdir,"/indices_reanalisis/indices_grid_parcelas.RData"))
    save(grid.indices.rcp26,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices_grid_parcelas.RData"))


    # interpolate each indice on the same grid of the Reanalysis:
    index.rcp26.array<-array(NA,c(n.indices,n.lat.rcp26,n.lon.rcp26))
    for(i in 1:n.indices) index.rcp26.array[i,,]<-index.rcp26[[i]]

    #rm(index.rcp26.interp) #  if there is already an object with this name
    print("done");cat("Interpolating...")
    index.rcp26.interp<-bilinear(lat.rean,lon.rean,lat.rcp26,lon.rcp26,index.rcp26.array)  # interpolation with the idw
    print("done");cat("Plotting data...")

    # there is a bug that sometimes returns false values from the bilinear function if it returns a list; so we modified it to return a matrix instead, but we must convert it back to a list to plot it:
    interp<-list(); for(l in 1:n.indices) interp[[l]]<-index.rcp26.interp[l,,]
    rm(index.rcp26.interp); index.rcp26.interp=interp; rm(interp)

    save(index.rcp26.interp,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices_interp.RData"))
    
    # Save global interpolated maps of indices:
    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/Interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (RCP 2.6 Model ",mod," Run ",run," interpolated)")
      if(models.firstdim=="lat") {contour.data<-index.rcp26.interp[[my.index]]} else {contour.data<-t(index.rcp26.interp[[my.index]])}  
      PlotEquiMap2(index.rcp26.interp[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean<pata.latmax & lat.rean>pata.latmin)
    my.lon.pos<-which(lon.rean<pata.lonmax & lon.rean>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<pata.latmax+2 & lat.rean>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<pata.lonmax+2 & lon.rean>pata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/Interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)

      my.toptitle<-paste0(index.name[my.index]," (RCP 2.6 Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.rcp26.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp26.interp[[my.index]][my.lat.pos,my.lon.pos]}

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }


    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/Interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (RCP 2.6 Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.rcp26.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp26.interp[[my.index]][my.lat.pos,my.lon.pos]}
      if(models.firstdim=="lat") {contour.data<-index.rcp26.interp[[my.index]][my.lon.pos,my.lat.pos]} else {contour.data<-t(index.rcp26.interp[[my.index]][my.lat.pos,my.lon.pos])}  
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
                   # contours=NULL,intylat=1,intxlon=1,drawleg=F)
                   
      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }

    # the same charts as above, but plotting the difference between the rcp 2.6 and the historical data:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp26/",models.rcp26[mod],"_run_",run,"_interp_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/2.6/interp_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (RCP 2.6 - Historical Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {
        plot.data<-index.rcp26.interp[[my.index]][my.lon.pos,my.lat.pos]-index.hist.interp[[my.index]][my.lon.pos,my.lat.pos]
      } else {
        plot.data<-index.rcp26.interp[[my.index]][my.lat.pos,my.lon.pos]-index.hist.interp[[my.index]][my.lat.pos,my.lon.pos]
      }

      layout(matrix(c(1,1,1,1,2), 1, 5, byrow = TRUE))
      par(oma=c(1,0,0,0.2))
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=TRUE,cex=1.3)
      
      dev.off()
    }

} # close if on rcp26
#close(my.bar)

   
#~~~Load the projections from CMIP5 RCP 8.5 ~~~

#my.bar<-tkProgressBar(title = "Analizing data...", label = "Please wait",min = 0, max = 100, initial = 0, width = 500)
if(rcp85==TRUE){
    print("done");cat("Processing scenary RCP 8.5...")

    #setTkProgressBar(my.bar, run*100/n.runs[mod], label="Please wait")
    my.dir.rcp85<-paste0(path.data,"/",mod,"/r",run,"/8.5")
    my.files<-list.files(path=my.dir.rcp85,pattern="\\.nc$") # select all files inside the input data directory
    if(length(my.files)==0) print(paste0("There are no files in the input directory ",my.dir.rcp85))
    my.files.splitted<-strsplit(my.files,"_") # separate the suffix from the time range in the
    first.year.rcp.file <- as.integer(substr(my.files.splitted[[1]][2],1,4)) # The first year of data in ALL the rcp 2.6 and 8.5 files for tas and prec (usually 2006)    
    shift.rcp<-12*(first.year.rcp-first.year.rcp.file) # number of months from the beginning of the data file (year 2006) to the beginning of the future period used in the study (2030 in our case)
    
    # load the data for the first variable (i.e: tas):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[1]) my.file.var1<-my.files[f]
    my.path1<-paste0(my.dir.rcp85,"/",my.file.var1) # the full path of the first file in the directory (there is only one)
    my.ncdf1<-open.ncdf(my.path1) # open the netcdf file
    var1<-get.var.ncdf(my.ncdf1,varid=vars[1]) # var1 format: [lon,lat,month]

    # load the data for the second variable (i.e: pr):
    for(f in 1:length(my.files.splitted)) if(my.files.splitted[[f]][1]==vars[2]) my.file.var2<-my.files[f]
    my.path2<-paste0(my.dir.rcp85,"/",my.file.var2) # the full path of the first file in the directory (there is only one)
    my.ncdf2<-open.ncdf(my.path2) # open the netcdf file
    var2<-get.var.ncdf(my.ncdf2,varid=vars[2]) # var1 format: [lon,lat,month]

    lat.rcp85<-get.var.ncdf(my.ncdf1,varid="latitude") # <- get the latitude (it is the same both for temp and prec data and for all runs of the same model)
    lon.rcp85<-get.var.ncdf(my.ncdf1,varid="longitude") # <- get the longitude
    n.lat.rcp85<-length(lat.rcp85)
    n.lon.rcp85<-length(lon.rcp85)      

    close(my.ncdf1)
    close(my.ncdf2)
    
    #array where to put all the data of the runs during the study period (format: [lon,lat,month])
    temp.rcp85<-prec.rcp85<-array(NA,c(n.lon.rcp85,n.lat.rcp85,n.months.rcp))

    temp.rcp85[,,]<-var1[,,(1+shift.rcp):(n.months.rcp+shift.rcp)] 
    prec.rcp85[,,]<-var2[,,(1+shift.rcp):(n.months.rcp+shift.rcp)]

    #array where to put all the data of the runs for the transition period starting from last day of historica data (2006) up to the beginning of the future period (2030) (format: [lon,lat,month])
    temp.trans85<-prec.trans85<-array(NA,c(n.lon.rcp85,n.lat.rcp85,shift.rcp))
    temp.trans85[,,]<-var1[,,1:shift.rcp] 
    prec.trans85[,,]<-var2[,,1:shift.rcp]
    
    rm(var1,var2)

    # check if the first dimension is the longitude or the latitude:
    if(dim(temp.rcp85)[1]>dim(temp.rcp85)[2])  models.firstdim="lon"
    if(dim(temp.rcp85)[1]<dim(temp.rcp85)[2])  models.firstdim="lat"
    if(dim(temp.rcp85)[1]==dim(temp.rcp85)[2]) models.firstdim="lon" # only the model num.11, IPSL-CM5A-LR, has the same number of points for both dimensions
    
    # temp.fut1 and prec.fut1 format is: [lon,lat,month] but we must change it to [run,month,lat,lon] to calculate the climate indices:
    if(models.firstdim=="lon"){
       temp.rcp85<-aperm(temp.rcp85,c(3,2,1))
       prec.rcp85<-aperm(prec.rcp85,c(3,2,1))
       temp.trans85<-aperm(temp.trans85,c(3,2,1))
       prec.trans85<-aperm(prec.trans85,c(3,2,1))
    } else {  # in this case, the first dimension is the latitude, so we haven't to swap it:
       temp.rcp85<-aperm(temp.rcp85,c(3,1,2))
       prec.rcp85<-aperm(prec.rcp85,c(3,1,2))
       temp.trans85<-aperm(temp.trans85,c(3,1,2))
       prec.trans85<-aperm(prec.trans85,c(3,1,2))
    }
    
    # Convert temperature to Celsius:
    temp.rcp85<-temp.rcp85-273.15
    prec.rcp85<-prec.rcp85*60*60*24 # convert prec.from kg m-2 s-1 to mm for day; must still convert from mm/day to mm/month:
    temp.trans85<-temp.trans85-273.15
    prec.trans85<-prec.trans85*60*60*24
    
    month31=c(1,3,5,7,8,10,12) # meses con 31 dias
    my.months31<-rep(month31,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month31)) # select only months with 31 days
    prec.rcp85[my.months31,,]<-prec.rcp85[my.months31,,]*31 # multiply prec of these months for 31
    my.months31<-rep(month31,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month31)) # select only months with 31 days
    prec.trans85[my.months31,,]<-prec.trans85[my.months31,,]*31 # multiply prec of these months for 31

    month30=c(4,6,9,11) # meses con 30 dias
    my.months30<-rep(month30,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month30)) # select only months with 30 days
    prec.rcp85[my.months30,,]<-prec.rcp85[my.months30,,]*30 # multiply prec of these months for 30
    my.months30<-rep(month30,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month30)) # select only months with 30 days
    prec.trans85[my.months30,,]<-prec.trans85[my.months30,,]*30 # multiply prec of these months for 30

    month28=2 # meses con 28 dias
    my.months28<-rep(month28,n.years.rcp)+rep(0:(n.years.rcp-1)*12,each=length(month28)) # select only months with 28 days
    prec.rcp85[my.months28,,]<-prec.rcp85[my.months28,,]*28.25 # multiply prec of these months for 28.25
    my.months28<-rep(month28,shift.rcp/12)+rep(0:(shift.rcp/12-1)*12,each=length(month28)) # select only months with 28 days
    prec.trans85[my.months28,,]<-prec.trans85[my.months28,,]*28.25 # multiply prec of these months for 28.25

    # Calculate the climate index for each  model and for each run and save results:
    index.rcp85<-indices(temp.rcp85,prec.rcp85,n.months.rcp) # For Reanalysis
    #save(index.rcp85,file=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_indices.RData"))
    save(index.rcp85,file=paste0(path.data,"/",mod,"/r",run,"/2.6/Indices.RData"))

    # Save global maps with indices:
    for(my.index in 1:n.indices){
       #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
       png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

       layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
       #layout.show(2)
       my.toptitle<-paste0(index.name[my.index]," (RCP 8.5 Model ",mod," Run ",run,")")
       if(models.firstdim=="lat") {contour.data<-index.rcp85[[my.index]]} else {contour.data<-t(index.rcp85[[my.index]])}
       if(models.firstdim=="lat") {plot.data<-index.rcp85[[my.index]]} else {plot.data<-t(index.rcp85[[my.index]])}

       PlotEquiMap2(plot.data,lon.rcp85,lat.rcp85,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

       ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
       dev.off()
    }
    
    # the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rcp85<pata.latmax & lat.rcp85>pata.latmin)
    my.lon.pos<-which(lon.rcp85<pata.lonmax & lon.rcp85>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rcp85<pata.latmax+2 & lat.rcp85>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rcp85<pata.lonmax+2 & lon.rcp85>pata.lonmin-2)
    my.lat<-lat.rcp85[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rcp85[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)

        my.toptitle<-paste0(index.name[my.index]," (RCP 8.5 Model ",mod," Run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.rcp85[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp85[[my.index]][my.lat.pos,my.lon.pos]}
        
        layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
        #layout.show(2)
        #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
        dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rcp85 < bigpata.latmax & lat.rcp85 > bigpata.latmin)
    my.lon.pos<-which(lon.rcp85 < bigpata.lonmax & lon.rcp85 > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rcp85<bigpata.latmax+2 & lat.rcp85>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rcp85<bigpata.lonmax+2 & lon.rcp85>bigpata.lonmin-2)
    my.lat<-lat.rcp85[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rcp85[my.lon.pos]
   
    for(my.index in 1:n.indices){
        #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
        png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

        my.toptitle<-paste0(index.name.short[my.index]," (RCP 8.5 Model ",mod," run ",run,")")

        # to solve some bugs of PlotEquiMap:
        if(models.firstdim=="lat") {plot.data<-index.rcp85[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp85[[my.index]][my.lat.pos,my.lon.pos]}
        if(models.firstdim=="lat") {contour.data<-index.rcp85[[my.index]][my.lon.pos,my.lat.pos]} else {contour.data<-t(index.rcp85[[my.index]][my.lat.pos,my.lon.pos])}  
        layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
        #layout.show(2)
        par(oma=c(1,0,0,0.5))
        #par(mfrow=c(2,1))
        #x11(width=4,height=.8)
        PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
            brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
            filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
            contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
            # contours=NULL,intylat=1,intxlon=1,drawleg=F)
        
        my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
        map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
        ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
        dev.off()
    }
    

    # assign each parcela to a grid point of the rcp85 model:
    p.pos.rcp85<-list()
    for (p in 1:n.parcelas) p.pos.rcp85[[p]]=nearest(parcelas.lat[p],parcelas.lon[p],lat.rcp85,lon.rcp85)

    # save the index values for each of the parcelas and the number of different grid points:
    parcelas.indices.rcp85<-array(NA,c(n.parcelas,n.indices))
    for (p in 1:n.parcelas) { for (i in 1:n.indices) { parcelas.indices.rcp85[p,i]<-index.rcp85[[i]][p.pos.rcp85[[p]][1],p.pos.rcp85[[p]][2]] } }
    #save(parcelas.indices.rcp85,file=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_indices_parcelas.RData"))
    save(parcelas.indices.rcp85,file=paste0(path.data,"/",mod,"/r",run,"/8.5/Indices_parcelas.RData"))

    # save the yearly values of the indexes for each of the parcelas for the  period 2030-2050:
    index.rcp85.year<-array(NA,c(n.indices,n.years.rcp,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),first.year.rcp:last.year.rcp,paste0("Parcela",1:n.parcelas)))

    for (p in 1:n.parcelas) {
       for (year in 1:(n.years.rcp)) {
          begin.month = 1 + 12*(year-1)
          my.months<-begin.month:n.months.rcp
      
          # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
          tt.rcp85<-array(temp.rcp85[my.months,p.pos.rcp85[[p]][1],p.pos.rcp85[[p]][2]],c(length(my.months),1,1))
          pp.rcp85<-array(prec.rcp85[my.months,p.pos.rcp85[[p]][1],p.pos.rcp85[[p]][2]],c(length(my.months),1,1))

          index.rcp85.year[1,year,p]<-index1(tt.rcp85,12) # starting from 2030, select only one year of data at time
          if (year < n.years.rcp) index.rcp85.year[2,year,p]<-index2(tt.rcp85,24) # starting from 2030, select 2 years of data at time 
          if (year < n.years.rcp) index.rcp85.year[3,year,p]<-index3(tt.rcp85,24) # starting from 2030, select 2 years of data at time 
          index.rcp85.year[4,year,p]<-index4(tt.rcp85,12) # starting from 2030, select only one year of data at time 
          index.rcp85.year[5,year,p]<-index5(pp.rcp85,12) # starting from 2030, select only one year of data at time 
          if (year < n.years.rcp) index.rcp85.year[6,year,p]<-index6(pp.rcp85,24) # starting from 2030, select 2 years of data at time 
       }
    }

    # save the yearly values of the indexes for each of the parcelas for the transition period 2006-2029:
    index.trans85.year<-array(NA,c(n.indices,shift.rcp/12,n.parcelas),dimnames=list(paste0("Indice",1:n.indices),(last.year.hist+1):(first.year.rcp-1),paste0("Parcela",1:n.parcelas)))

    for (p in 1:n.parcelas) {
       for (year in 1:(shift.rcp/12)) {
          begin.month = 1 + 12*(year-1)
          my.months<-begin.month:shift.rcp
      
          # create a 3D array with 2 dummy variables corresponding to lat and lon to be able to use the indexX functions that need an array:
          tt.trans85<-array(temp.trans85[my.months,p.pos.rcp85[[p]][1],p.pos.rcp85[[p]][2]],c(length(my.months),1,1))
          pp.trans85<-array(prec.trans85[my.months,p.pos.rcp85[[p]][1],p.pos.rcp85[[p]][2]],c(length(my.months),1,1))

          index.trans85.year[1,year,p]<-index1(tt.trans85,12) # starting from 2006, select only one year of data at time
          if (year < shift.rcp/12) index.trans85.year[2,year,p]<-index2(tt.trans85,24) # starting from 2006, select 2 years of data at time 
          if (year < shift.rcp/12) index.trans85.year[3,year,p]<-index3(tt.trans85,24) 
          index.trans85.year[4,year,p]<-index4(tt.trans85,12)
          index.trans85.year[5,year,p]<-index5(pp.trans85,12)
          if (year < shift.rcp/12) index.trans85.year[6,year,p]<-index6(pp.trans85,24)
       }
    }

    #plot(2030:2050,index.rcp85.year[1,,1],type="o")
    
    #save(index.rcp85.year,file=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_indices_parcelas_anuales.RData"))
    save(index.rcp85.year,file=paste0(path.data,"/",mod,"/r",run,"/8.5/Indices_parcelas_anuales.RData"))

    #plot(2006:2029,index.trans85.year[1,,1],type="o")

    #save(index.trans85.year,file=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_indices_parcelas_anuales_transition.RData"))
    save(index.trans85.year,file=paste0(path.data,"/",mod,"/r",run,"/8.5/Indices_parcelas_anuales_transition.RData"))

     # same as above, but for the grid of parcelas:
    grid.pos.rcp85<-list()
    for (p in 1:n.grid.points) grid.pos.rcp85[[p]]=nearest(grid.lat[p],grid.lon[p],lat.rcp85,lon.rcp85)

    # save the index values for each of the grid points:
    grid.indices.rcp85<-array(NA,c(n.grid.points,n.indices))
    for (p in 1:n.grid.points) { for (i in 1:n.indices) { grid.indices.rcp85[p,i]<-index.rcp85[[i]][grid.pos.rcp85[[p]][1],grid.pos.rcp85[[p]][2]] } }
    save(grid.indices.rcp85,file=paste0(path.data,"/",mod,"/r",run,"/8.5/Indices_grid_parcelas.RData"))
    
    # interpolate each indice on the same grid of the Reanalysis:
    index.rcp85.array<-array(NA,c(n.indices,n.lat.rcp85,n.lon.rcp85))
    for(i in 1:n.indices) index.rcp85.array[i,,]<-index.rcp85[[i]]

    #rm(index.rcp85.interp) #  if there is already an object with this name
    print("done");cat("Interpolating...")
    index.rcp85.interp<-bilinear(lat.rean,lon.rean,lat.rcp85,lon.rcp85,index.rcp85.array)  # interpolation with the bilinear method
    print("done");print("Plotting data...")

     # there is a bug that sometimes returns false values from the bilinear function if it returns a list; so we modified it to return a matrix instead, but we must convert it back to a list to plot it:
    interp<-list(); for(l in 1:n.indices) interp[[l]]<-index.rcp85.interp[l,,]
    rm(index.rcp85.interp); index.rcp85.interp=interp; rm(interp)

    save(index.rcp85.interp,file=paste0(path.data,"/",mod,"/r",run,"/8.5/Indices_interp.RData"))

    # Save global interpolated maps of indices:
    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/Interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (RCP 8.5 Model ",mod," Run ",run," interpolated)")
      if(models.firstdim=="lat") {contour.data<-index.rcp85.interp[[my.index]]} else {contour.data<-t(index.rcp85.interp[[my.index]])}  
      PlotEquiMap2(index.rcp85.interp[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean<pata.latmax & lat.rean>pata.latmin)
    my.lon.pos<-which(lon.rean<pata.lonmax & lon.rean>pata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<pata.latmax+2 & lat.rean>pata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<pata.lonmax+2 & lon.rean>pata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/Interp_Patagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=600,height=480)

      my.toptitle<-paste0(index.name[my.index]," (RCP 8.5 Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.rcp85.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp85.interp[[my.index]][my.lat.pos,my.lon.pos]}

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      #par(oma=c(0,4,0,0)) #par(mfrow=c(2,1)) #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=1,col=c("purple","blue","red","black"))  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/Interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (RCP 8.5 Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {plot.data<-index.rcp85.interp[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-index.rcp85.interp[[my.index]][my.lat.pos,my.lon.pos]}
      if(models.firstdim=="lat") {contour.data<-index.rcp85.interp[[my.index]][my.lon.pos,my.lat.pos]} else {contour.data<-t(index.rcp85.interp[[my.index]][my.lat.pos,my.lon.pos])}  
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,contour.data,contour.data,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
                   # contours=NULL,intylat=1,intxlon=1,drawleg=F)
                   
      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }

    # the same charts as above, but plotting the difference between the rcp 8.5 and the historical data:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_rcp85/",models.rcp85[mod],"_run_",run,"_interp_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/",mod,"/r",run,"/8.5/interp_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (RCP 8.5 - Historical Model ",mod," Run ",run," interpolated)")

      # to solve some bugs of PlotEquiMap:
      if(models.firstdim=="lat") {
        plot.data<-index.rcp85.interp[[my.index]][my.lon.pos,my.lat.pos]-index.hist.interp[[my.index]][my.lon.pos,my.lat.pos]
      } else {
        plot.data<-index.rcp85.interp[[my.index]][my.lat.pos,my.lon.pos]-index.hist.interp[[my.index]][my.lat.pos,my.lon.pos]
      }

      layout(matrix(c(1,1,1,1,2), 1, 5, byrow = TRUE))
      par(oma=c(1,0,0,0.2))
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=TRUE,cex=1.3)
      
      dev.off()
    }

} # close if on rcp85
#close(my.bar)

#print("Saving R session...")
#save.image(file=paste0(path.data,"/",mod,"/r",run,"/run.RData"))

print("Finished")

#parcelas.cambio26<-parcelas.indices.rcp26-parcelas.indices.hist
#parcelas.cambio85<-parcelas.indices.rcp85-parcelas.indices.hist


       
    } # close the loop on the run to analyze       
  } # close the loop on the run to analyze       
} # close the loop on the run to analyze       




















############################################## Ensemble creation ###################################################

if(ensemble==TRUE){  
# you need to have already analyized all runs individually and saved the data of each one before computing the ensemble

# select the patagonia zoom (in tis case over the area of the 4 parcelas) to calculate the weighted ensemble and the  Taylor's diagram (RMSE, SD ratio, R) only for a selected area: 
zoom.lat.min=12 # the latitudinal position of the first pixel (lower lat.value) of the reanalysis dataset inside the BigPatagonia area
zoom.lat.max=20 # the latitudinal position of the last pixel (higher lat.value) of the reanalysis dataset inside the BigPatagonia area
zoom.lon.min=4  # ...
zoom.lon.max=9  # ...

col.taylor=c(brewer.pal(12, "Paired"),"gray60","magenta","black") # model colors for the taylor diagram
col.taylor[11]<-"sienna4" # replace yellow with brown

# suffix to add to the output file name of all the taylor's diagrams (+legend file):  (i.e: selected_runs, alternative_weights)
suffix=""

########################################################33

# variables ensemble:
run.rcp26<-run.rcp85<-list() # list with the data of each run and model for RCP 2.6 or to RCP 8.5
run.hist26<-run.hist85<-list() # list with the data of each run and model for historial associated to RCP 2.6 or to RCP 8.5

# calculate the number of runs for each model:
#ntot.runs.hist<-colSums(n.runs.hist != 0)
ntot.runs.rcp26<-colSums(n.runs.rcp26 != 0)
ntot.runs.rcp85<-colSums(n.runs.rcp85 != 0)

# calculate the number of models really used in each scenario:
#ntot.models.hist<-length(which(ntot.runs.hist != 0))
ntot.models.rcp26<-length(which(ntot.runs.rcp26 != 0))
ntot.models.rcp85<-length(which(ntot.runs.rcp85 != 0))

# define some void lists of 0s that will be attributed to not-existing runs:
void.index<-matrix(0,n.lat.rean,n.lon.rean)
void.run<-list(void.index,void.index,void.index,void.index,void.index,void.index)

# load all runs in a list of run data:
for(mod in 1:n.max.models){
   run.rcp26[[mod]]<-list()
   run.hist26[[mod]]<-list()
   run.rcp85[[mod]]<-list()
   run.hist85[[mod]]<-list()
   
   # load all the rcp 2.6 data and its historial of the indices of runs of the same model: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
        run.rcp26[[mod]][[run]]<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/2.6/Indices_interp.RData")))
        run.hist26[[mod]][[run]]<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/historical/Indices_interp.RData")))
      } else {
        run.rcp26[[mod]][[run]]<-void.run
        run.hist26[[mod]][[run]]<-void.run
      }
   }

   # load all the rcp 8.5 data and its historial of the indices of runs of the same model: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
        run.rcp85[[mod]][[run]]<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/8.5/Indices_interp.RData")))
        run.hist85[[mod]][[run]]<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/historical/Indices_interp.RData")))
      } else {
        run.rcp85[[mod]][[run]]<-void.run
        run.hist85[[mod]][[run]]<-void.run
      }
   }
}

# load all runs for the parcelas:
run.rcp26.parcelas<-run.rcp85.parcelas<-list() # list with the parcelas data of each run and model for RCP 2.6 or RCP 8.5
run.hist26.parcelas<-run.hist85.parcelas<-list() # list with the parcelas data of each run and model for historial associated to RCP 2.6 or to RCP 8.5
void.index.parcelas<-rep(0,n.parcelas)
#void.run.parcelas<-list(void.index.parcelas,void.index.parcelas,void.index.parcelas,void.index.parcelas,void.index.parcelas,void.index.parcelas)
void.run.parcelas<-rep(list(void.index.parcelas),n.indices)

for(mod in 1:n.max.models){
   run.rcp26.parcelas[[mod]]<-list()
   run.hist26.parcelas[[mod]]<-list()
   run.rcp85.parcelas[[mod]]<-list()
   run.hist85.parcelas[[mod]]<-list()
  
   # load all the rcp 2.6 data and its historial for the 4 parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/2.6/Indices_parcelas.RData")))
        run.rcp26.parcelas[[mod]][[run]]<-list(tmp[,1],tmp[,2],tmp[,3],tmp[,4],tmp[,5],tmp[,6]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/historical/Indices_parcelas.RData")))
        run.hist26.parcelas[[mod]][[run]]<-list(tmph[,1],tmph[,2],tmph[,3],tmph[,4],tmph[,5],tmph[,6]) # create a list of six vectors, one for each index
      } else {
        run.rcp26.parcelas[[mod]][[run]]<-void.run.parcelas
        run.hist26.parcelas[[mod]][[run]]<-void.run.parcelas
      }
   }
 
  # load all the rcp 8.5 data and its historial for the 4 parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/8.5/Indices_parcelas.RData")))
        run.rcp85.parcelas[[mod]][[run]]<-list(tmp[,1],tmp[,2],tmp[,3],tmp[,4],tmp[,5],tmp[,6]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/historical/Indices_parcelas.RData")))
        run.hist85.parcelas[[mod]][[run]]<-list(tmph[,1],tmph[,2],tmph[,3],tmph[,4],tmph[,5],tmph[,6]) # create a list of six vectors, one for each index
      } else {
        run.rcp85.parcelas[[mod]][[run]]<-void.run.parcelas
        run.hist85.parcelas[[mod]][[run]]<-void.run.parcelas
      }
   }
   
}

# load all runs for the grid of parcelas:
run.rcp26.grid.parcelas<-run.rcp85.grid.parcelas<-list() # list with the parcelas data of each run and model for RCP 2.6 or RCP 8.5
run.hist26.grid.parcelas<-run.hist85.grid.parcelas<-list() # list with the parcelas data of each run and model for historial associated to RCP 2.6 or to RCP 8.5
void.index.grid.parcelas<-rep(0,n.grid.points)
#void.run.grid.parcelas<-list(void.index.grid.parcelas,void.index.grid.parcelas,void.index.grid.parcelas,void.index.grid.parcelas,void.index.grid.parcelas,void.index.grid.parcelas)
void.run.grid.parcelas<-rep(list(void.index.grid.parcelas),n.indices)

for(mod in 1:n.max.models){
   run.rcp26.grid.parcelas[[mod]]<-list()
   run.hist26.grid.parcelas[[mod]]<-list()
   run.rcp85.grid.parcelas[[mod]]<-list()
   run.hist85.grid.parcelas[[mod]]<-list()
  
   # load all the rcp 2.6 data and its historial for the grid of parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/2.6/Indices_grid_parcelas.RData")))
        run.rcp26.grid.parcelas[[mod]][[run]]<-list(tmp[,1],tmp[,2],tmp[,3],tmp[,4],tmp[,5],tmp[,6]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/historical/Indices_grid_parcelas.RData")))
        run.hist26.grid.parcelas[[mod]][[run]]<-list(tmph[,1],tmph[,2],tmph[,3],tmph[,4],tmph[,5],tmph[,6]) # create a list of six vectors, one for each index
      } else {
        run.rcp26.grid.parcelas[[mod]][[run]]<-void.run.grid.parcelas
        run.hist26.grid.parcelas[[mod]][[run]]<-void.run.grid.parcelas
      }
   }
 
  # load all the rcp 8.5 data and its historial for the grid of parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/8.5/Indices_grid_parcelas.RData")))
        run.rcp85.grid.parcelas[[mod]][[run]]<-list(tmp[,1],tmp[,2],tmp[,3],tmp[,4],tmp[,5],tmp[,6]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/historical/Indices_grid_parcelas.RData")))
        run.hist85.grid.parcelas[[mod]][[run]]<-list(tmph[,1],tmph[,2],tmph[,3],tmph[,4],tmph[,5],tmph[,6]) # create a list of six vectors, one for each index
      } else {
        run.rcp85.grid.parcelas[[mod]][[run]]<-void.run.grid.parcelas
        run.hist85.grid.parcelas[[mod]][[run]]<-void.run.grid.parcelas
      }
   }
   
}


# load all yearly runs for the parcelas:
run.rcp26.yearly.parcelas<-run.rcp85.yearly.parcelas<-run.trans26.yearly.parcelas<-list() # list with the parcelas data of each run and model for RCP 2.6 or RCP 8.5
run.hist26.yearly.parcelas<-run.hist85.yearly.parcelas<-run.trans85.yearly.parcelas<-list() # list with the parcelas data of each run and model for historial associated to RCP 2.6 or to RCP 8.5

void.index.yearly.parcelas.rcp<-matrix(0,n.years.rcp,n.parcelas)
void.index.yearly.parcelas.hist<-matrix(0,n.years.hist,n.parcelas)
void.index.yearly.parcelas.trans<-matrix(0,n.years.trans,n.parcelas)

void.run.yearly.parcelas.rcp<-rep(list(void.index.yearly.parcelas.rcp),n.indices)
void.run.yearly.parcelas.hist<-rep(list(void.index.yearly.parcelas.hist),n.indices)
void.run.yearly.parcelas.trans<-rep(list(void.index.yearly.parcelas.trans),n.indices)

for(mod in 1:n.max.models){
   run.rcp26.yearly.parcelas[[mod]]<-list()
   run.hist26.yearly.parcelas[[mod]]<-list()
   run.trans26.yearly.parcelas[[mod]]<-list()

   run.rcp85.yearly.parcelas[[mod]]<-list()
   run.hist85.yearly.parcelas[[mod]]<-list()
   run.trans85.yearly.parcelas[[mod]]<-list()

   # load all the rcp 2.6 data and its historial for the 4 parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/2.6/Indices_parcelas_anuales.RData")))
        run.rcp26.yearly.parcelas[[mod]][[run]]<-list(tmp[1,,],tmp[2,,],tmp[3,,],tmp[4,,],tmp[5,,],tmp[6,,]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/historical/Indices_parcelas_anuales.RData")))
        run.hist26.yearly.parcelas[[mod]][[run]]<-list(tmph[1,,],tmph[2,,],tmph[3,,],tmph[4,,],tmph[5,,],tmph[6,,]) # create a list of six vectors, one for each index
        tmpr<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp26[run,mod],"/2.6/Indices_parcelas_anuales_transition.RData")))
        run.trans26.yearly.parcelas[[mod]][[run]]<-list(tmpr[1,,],tmpr[2,,],tmpr[3,,],tmpr[4,,],tmpr[5,,],tmpr[6,,]) # create a list of six vectors, one for each index
        
      } else {
        run.rcp26.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.rcp
        run.hist26.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.hist
        run.trans26.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.trans
      }
   }
 
  # load all the rcp 8.5 data and its historial for the 4 parcelas: 
   for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
        tmp<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/8.5/Indices_parcelas_anuales.RData")))
        run.rcp85.yearly.parcelas[[mod]][[run]]<-list(tmp[1,,],tmp[2,,],tmp[3,,],tmp[4,,],tmp[5,,],tmp[6,,]) # create a list of six vectors, one for each index
        tmph<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/historical/Indices_parcelas_anuales.RData")))
        run.hist85.yearly.parcelas[[mod]][[run]]<-list(tmph[1,,],tmph[2,,],tmph[3,,],tmph[4,,],tmph[5,,],tmph[6,,]) # create a list of six vectors, one for each index
        tmpr<-get(load(paste0(path.data,"/",mod,"/r",n.runs.rcp85[run,mod],"/8.5/Indices_parcelas_anuales_transition.RData")))
        run.trans85.yearly.parcelas[[mod]][[run]]<-list(tmpr[1,,],tmpr[2,,],tmpr[3,,],tmpr[4,,],tmpr[5,,],tmpr[6,,]) # create a list of six vectors, one for each index
      } else {
        run.rcp85.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.rcp
        run.hist85.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.hist
        run.trans85.yearly.parcelas[[mod]][[run]]<-void.run.yearly.parcelas.trans
      }
   }
   
}


# calculate the ensemble mean of each run in the same model:
ensemble.runs.rcp26<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist26<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.rcp85<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist85<-list() # list with the ensemble of all runs for one specific model

for(mod in 1:n.max.models){
   if(ntot.runs.rcp26[mod]!=0){
     ensemble.runs.rcp26[[mod]] <-lapply(seq_along(run.rcp26[[mod]][[1]]),function(i) (matrix((unlist(run.rcp26[[mod]][[1]][i]) + unlist(run.rcp26[[mod]][[2]][i]) + unlist(run.rcp26[[mod]][[3]][i]) + unlist(run.rcp26[[mod]][[4]][i]) + unlist(run.rcp26[[mod]][[5]][i]))/ntot.runs.rcp26[mod],n.lat.rean,n.lon.rean)))
     ensemble.runs.hist26[[mod]] <-lapply(seq_along(run.hist26[[mod]][[1]]),function(i) (matrix((unlist(run.hist26[[mod]][[1]][i]) + unlist(run.hist26[[mod]][[2]][i]) + unlist(run.hist26[[mod]][[3]][i]) + unlist(run.hist26[[mod]][[4]][i]) + unlist(run.hist26[[mod]][[5]][i]))/ntot.runs.rcp26[mod],n.lat.rean,n.lon.rean)))
   } else {
     ensemble.runs.rcp26[[mod]]<-void.run
     ensemble.runs.hist26[[mod]]<-void.run
   }

   if(ntot.runs.rcp85[mod]!=0){
     ensemble.runs.rcp85[[mod]] <-lapply(seq_along(run.rcp85[[mod]][[1]]),function(i) (matrix((unlist(run.rcp85[[mod]][[1]][i]) + unlist(run.rcp85[[mod]][[2]][i]) + unlist(run.rcp85[[mod]][[3]][i]) + unlist(run.rcp85[[mod]][[4]][i]) + unlist(run.rcp85[[mod]][[5]][i]))/ntot.runs.rcp85[mod],n.lat.rean,n.lon.rean)))
     ensemble.runs.hist85[[mod]] <-lapply(seq_along(run.hist85[[mod]][[1]]),function(i) (matrix((unlist(run.hist85[[mod]][[1]][i]) + unlist(run.hist85[[mod]][[2]][i]) + unlist(run.hist85[[mod]][[3]][i]) + unlist(run.hist85[[mod]][[4]][i]) + unlist(run.hist85[[mod]][[5]][i]))/ntot.runs.rcp85[mod],n.lat.rean,n.lon.rean)))
   } else {
     ensemble.runs.rcp85[[mod]]<-void.run
     ensemble.runs.hist85[[mod]]<-void.run
   }
}


# calculate the ensemble mean of each run in the same model for the parcelas:
ensemble.runs.rcp26.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist26.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.rcp85.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist85.parcelas<-list() # list with the ensemble of all runs for one specific model

for(mod in 1:n.max.models){
   if(ntot.runs.rcp26[mod]!=0){
     ensemble.runs.rcp26.parcelas[[mod]] <-lapply(seq_along(run.rcp26.parcelas[[mod]][[1]]),function(i) ((unlist(run.rcp26.parcelas[[mod]][[1]][i]) + unlist(run.rcp26.parcelas[[mod]][[2]][i]) + unlist(run.rcp26.parcelas[[mod]][[3]][i]) + unlist(run.rcp26.parcelas[[mod]][[4]][i]) + unlist(run.rcp26.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod]))
     ensemble.runs.hist26.parcelas[[mod]] <-lapply(seq_along(run.hist26.parcelas[[mod]][[1]]),function(i) ((unlist(run.hist26.parcelas[[mod]][[1]][i]) + unlist(run.hist26.parcelas[[mod]][[2]][i]) + unlist(run.hist26.parcelas[[mod]][[3]][i]) + unlist(run.hist26.parcelas[[mod]][[4]][i]) + unlist(run.hist26.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod]))
   } else {
     ensemble.runs.rcp26.parcelas[[mod]]<-void.run.parcelas
     ensemble.runs.hist26.parcelas[[mod]]<-void.run.parcelas
   }

   if(ntot.runs.rcp85[mod]!=0){
     ensemble.runs.rcp85.parcelas[[mod]] <-lapply(seq_along(run.rcp85.parcelas[[mod]][[1]]),function(i) ((unlist(run.rcp85.parcelas[[mod]][[1]][i]) + unlist(run.rcp85.parcelas[[mod]][[2]][i]) + unlist(run.rcp85.parcelas[[mod]][[3]][i]) + unlist(run.rcp85.parcelas[[mod]][[4]][i]) + unlist(run.rcp85.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod]))
     ensemble.runs.hist85.parcelas[[mod]] <-lapply(seq_along(run.hist85.parcelas[[mod]][[1]]),function(i) ((unlist(run.hist85.parcelas[[mod]][[1]][i]) + unlist(run.hist85.parcelas[[mod]][[2]][i]) + unlist(run.hist85.parcelas[[mod]][[3]][i]) + unlist(run.hist85.parcelas[[mod]][[4]][i]) + unlist(run.hist85.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod]))
   } else {
     ensemble.runs.rcp85.parcelas[[mod]]<-void.run.parcelas
     ensemble.runs.hist85.parcelas[[mod]]<-void.run.parcelas
   }
}

# calculate the ensemble mean of each run in the same model for the grid of parcelas:
ensemble.runs.rcp26.grid.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist26.grid.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.rcp85.grid.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist85.grid.parcelas<-list() # list with the ensemble of all runs for one specific model

for(mod in 1:n.max.models){
   if(ntot.runs.rcp26[mod]!=0){
     ensemble.runs.rcp26.grid.parcelas[[mod]] <-lapply(seq_along(run.rcp26.grid.parcelas[[mod]][[1]]),function(i) ((unlist(run.rcp26.grid.parcelas[[mod]][[1]][i]) + unlist(run.rcp26.grid.parcelas[[mod]][[2]][i]) + unlist(run.rcp26.grid.parcelas[[mod]][[3]][i]) + unlist(run.rcp26.grid.parcelas[[mod]][[4]][i]) + unlist(run.rcp26.grid.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod]))
     ensemble.runs.hist26.grid.parcelas[[mod]] <-lapply(seq_along(run.hist26.grid.parcelas[[mod]][[1]]),function(i) ((unlist(run.hist26.grid.parcelas[[mod]][[1]][i]) + unlist(run.hist26.grid.parcelas[[mod]][[2]][i]) + unlist(run.hist26.grid.parcelas[[mod]][[3]][i]) + unlist(run.hist26.grid.parcelas[[mod]][[4]][i]) + unlist(run.hist26.grid.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod]))
   } else {
     ensemble.runs.rcp26.grid.parcelas[[mod]]<-void.run.grid.parcelas
     ensemble.runs.hist26.grid.parcelas[[mod]]<-void.run.grid.parcelas
   }

   if(ntot.runs.rcp85[mod]!=0){
     ensemble.runs.rcp85.grid.parcelas[[mod]] <-lapply(seq_along(run.rcp85.grid.parcelas[[mod]][[1]]),function(i) ((unlist(run.rcp85.grid.parcelas[[mod]][[1]][i]) + unlist(run.rcp85.grid.parcelas[[mod]][[2]][i]) + unlist(run.rcp85.grid.parcelas[[mod]][[3]][i]) + unlist(run.rcp85.grid.parcelas[[mod]][[4]][i]) + unlist(run.rcp85.grid.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod]))
     ensemble.runs.hist85.grid.parcelas[[mod]] <-lapply(seq_along(run.hist85.grid.parcelas[[mod]][[1]]),function(i) ((unlist(run.hist85.grid.parcelas[[mod]][[1]][i]) + unlist(run.hist85.grid.parcelas[[mod]][[2]][i]) + unlist(run.hist85.grid.parcelas[[mod]][[3]][i]) + unlist(run.hist85.grid.parcelas[[mod]][[4]][i]) + unlist(run.hist85.grid.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod]))
   } else {
     ensemble.runs.rcp85.grid.parcelas[[mod]]<-void.run.grid.parcelas
     ensemble.runs.hist85.grid.parcelas[[mod]]<-void.run.grid.parcelas
   }
}

# calculate the ensemble mean of each yearly run in the same model for the parcelas:
ensemble.runs.rcp26.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist26.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.trans26.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model

ensemble.runs.rcp85.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.hist85.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model
ensemble.runs.trans85.yearly.parcelas<-list() # list with the ensemble of all runs for one specific model

for(mod in 1:n.max.models){
   if(ntot.runs.rcp26[mod]!=0){
     ensemble.runs.rcp26.yearly.parcelas[[mod]] <-lapply(seq_along(run.rcp26.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.rcp26.yearly.parcelas[[mod]][[1]][i]) + unlist(run.rcp26.yearly.parcelas[[mod]][[2]][i]) + unlist(run.rcp26.yearly.parcelas[[mod]][[3]][i]) + unlist(run.rcp26.yearly.parcelas[[mod]][[4]][i]) + unlist(run.rcp26.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod],n.years.rcp,n.parcelas)))
     ensemble.runs.hist26.yearly.parcelas[[mod]] <-lapply(seq_along(run.hist26.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.hist26.yearly.parcelas[[mod]][[1]][i]) + unlist(run.hist26.yearly.parcelas[[mod]][[2]][i]) + unlist(run.hist26.yearly.parcelas[[mod]][[3]][i]) + unlist(run.hist26.yearly.parcelas[[mod]][[4]][i]) + unlist(run.hist26.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod],n.years.hist,n.parcelas)))
     ensemble.runs.trans26.yearly.parcelas[[mod]] <-lapply(seq_along(run.trans26.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.trans26.yearly.parcelas[[mod]][[1]][i]) + unlist(run.trans26.yearly.parcelas[[mod]][[2]][i]) + unlist(run.trans26.yearly.parcelas[[mod]][[3]][i]) + unlist(run.trans26.yearly.parcelas[[mod]][[4]][i]) + unlist(run.trans26.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp26[mod],n.years.trans,n.parcelas)))
   } else {
     ensemble.runs.rcp26.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.rcp
     ensemble.runs.hist26.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.hist
     ensemble.runs.trans26.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.trans
   }

   if(ntot.runs.rcp85[mod]!=0){
     ensemble.runs.rcp85.yearly.parcelas[[mod]] <-lapply(seq_along(run.rcp85.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.rcp85.yearly.parcelas[[mod]][[1]][i]) + unlist(run.rcp85.yearly.parcelas[[mod]][[2]][i]) + unlist(run.rcp85.yearly.parcelas[[mod]][[3]][i]) + unlist(run.rcp85.yearly.parcelas[[mod]][[4]][i]) + unlist(run.rcp85.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod],n.years.rcp,n.parcelas)))
     ensemble.runs.hist85.yearly.parcelas[[mod]] <-lapply(seq_along(run.hist85.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.hist85.yearly.parcelas[[mod]][[1]][i]) + unlist(run.hist85.yearly.parcelas[[mod]][[2]][i]) + unlist(run.hist85.yearly.parcelas[[mod]][[3]][i]) + unlist(run.hist85.yearly.parcelas[[mod]][[4]][i]) + unlist(run.hist85.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod],n.years.hist,n.parcelas)))
     ensemble.runs.trans85.yearly.parcelas[[mod]] <-lapply(seq_along(run.trans85.yearly.parcelas[[mod]][[1]]),function(i) (matrix((unlist(run.trans85.yearly.parcelas[[mod]][[1]][i]) + unlist(run.trans85.yearly.parcelas[[mod]][[2]][i]) + unlist(run.trans85.yearly.parcelas[[mod]][[3]][i]) + unlist(run.trans85.yearly.parcelas[[mod]][[4]][i]) + unlist(run.trans85.yearly.parcelas[[mod]][[5]][i]))/ntot.runs.rcp85[mod],n.years.trans,n.parcelas)))
   } else {
     ensemble.runs.rcp85.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.rcp
     ensemble.runs.hist85.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.hist
     ensemble.runs.trans85.yearly.parcelas[[mod]]<-void.run.yearly.parcelas.trans
   }
}


# calculate the percentiles of the delta RCP26 - Hist26 for the parcelas:
percentil75.delta.rcp26.parcelas<-percentil25.delta.rcp26.parcelas<-matrix(NA,n.indices,n.parcelas)

for(ind in 1:n.indices){
  tmp<-matrix(NA,n.max.models*n.max.runs,n.parcelas)
  for(mod in 1:n.max.models){
    for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
         tmp[(mod-1)*n.max.runs+run,] <- run.rcp26.parcelas[[mod]][[run]][[ind]] - run.hist26.parcelas[[mod]][[run]][[ind]]
      }
    } 
  }
  percentil75.delta.rcp26.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.75)
  percentil25.delta.rcp26.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.25)
}

# calculate the percentiles of the delta RCP85 - Hist85 for the parcelas:
percentil75.delta.rcp85.parcelas<-percentil25.delta.rcp85.parcelas<-matrix(NA,n.indices,n.parcelas)

for(ind in 1:n.indices){
  tmp<-matrix(NA,n.max.models*n.max.runs,n.parcelas)
  for(mod in 1:n.max.models){
    for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
         tmp[(mod-1)*n.max.runs+run,] <- run.rcp85.parcelas[[mod]][[run]][[ind]] - run.hist85.parcelas[[mod]][[run]][[ind]]
      }
    } 
  }
  percentil75.delta.rcp85.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.75)
  percentil25.delta.rcp85.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.25)
}


# calculate the percentiles of the delta RCP26 - Hist26 for the grid of parcelas:
percentil75.delta.rcp26.grid.parcelas<-percentil25.delta.rcp26.grid.parcelas<-matrix(NA,n.indices,n.grid.points)

for(ind in 1:n.indices){
  tmp<-matrix(NA,n.max.models*n.max.runs,n.grid.points)
  for(mod in 1:n.max.models){
    for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod]!=0){
         tmp[(mod-1)*n.max.runs+run,] <- run.rcp26.grid.parcelas[[mod]][[run]][[ind]] - run.hist26.grid.parcelas[[mod]][[run]][[ind]]
      }
    } 
  }
  percentil75.delta.rcp26.grid.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.75)
  percentil25.delta.rcp26.grid.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.25)
}

# calculate the percentiles of the delta RCP85 - Hist85 for the grid of parcelas:
percentil75.delta.rcp85.grid.parcelas<-percentil25.delta.rcp85.grid.parcelas<-matrix(NA,n.indices,n.grid.points)

for(ind in 1:n.indices){
  tmp<-matrix(NA,n.max.models*n.max.runs,n.grid.points)
  for(mod in 1:n.max.models){
    for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod]!=0){
         tmp[(mod-1)*n.max.runs+run,] <- run.rcp85.grid.parcelas[[mod]][[run]][[ind]] - run.hist85.grid.parcelas[[mod]][[run]][[ind]]
      }
    } 
  }
  percentil75.delta.rcp85.grid.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.75)
rseis  percentil25.delta.rcp85.grid.parcelas[ind,] <- apply(tmp,2,quantile,na.rm=TRUE,probs=0.25)
}



# calculate the ensemble mean of all models:
ensemble.hist26<-lapply(seq_along(ensemble.runs.hist26[[1]]),function(i) (matrix((unlist(ensemble.runs.hist26[[1]][i]) + unlist(ensemble.runs.hist26[[2]][i]) + unlist(ensemble.runs.hist26[[3]][i]) + unlist(ensemble.runs.hist26[[4]][i]) + unlist(ensemble.runs.hist26[[5]][i]) + unlist(ensemble.runs.hist26[[6]][i]) + unlist(ensemble.runs.hist26[[7]][i]) + unlist(ensemble.runs.hist26[[8]][i]) + unlist(ensemble.runs.hist26[[9]][i]) + unlist(ensemble.runs.hist26[[10]][i]) + unlist(ensemble.runs.hist26[[11]][i]) + unlist(ensemble.runs.hist26[[12]][i]) + unlist(ensemble.runs.hist26[[13]][i]) + unlist(ensemble.runs.hist26[[14]][i]) + unlist(ensemble.runs.hist26[[15]][i]))/ntot.models.rcp26,n.lat.rean,n.lon.rean)))

ensemble.hist85<-lapply(seq_along(ensemble.runs.hist85[[1]]),function(i) (matrix((unlist(ensemble.runs.hist85[[1]][i]) + unlist(ensemble.runs.hist85[[2]][i]) + unlist(ensemble.runs.hist85[[3]][i]) + unlist(ensemble.runs.hist85[[4]][i]) + unlist(ensemble.runs.hist85[[5]][i]) + unlist(ensemble.runs.hist85[[6]][i]) + unlist(ensemble.runs.hist85[[7]][i]) + unlist(ensemble.runs.hist85[[8]][i]) + unlist(ensemble.runs.hist85[[9]][i]) + unlist(ensemble.runs.hist85[[10]][i]) + unlist(ensemble.runs.hist85[[11]][i]) + unlist(ensemble.runs.hist85[[12]][i]) + unlist(ensemble.runs.hist85[[13]][i]) + unlist(ensemble.runs.hist85[[14]][i]) + unlist(ensemble.runs.hist85[[15]][i]))/ntot.models.rcp85,n.lat.rean,n.lon.rean)))

ensemble.rcp26<-lapply(seq_along(ensemble.runs.rcp26[[1]]),function(i) (matrix((unlist(ensemble.runs.rcp26[[1]][i]) + unlist(ensemble.runs.rcp26[[2]][i]) + unlist(ensemble.runs.rcp26[[3]][i]) + unlist(ensemble.runs.rcp26[[4]][i]) + unlist(ensemble.runs.rcp26[[5]][i]) + unlist(ensemble.runs.rcp26[[6]][i]) + unlist(ensemble.runs.rcp26[[7]][i]) + unlist(ensemble.runs.rcp26[[8]][i]) + unlist(ensemble.runs.rcp26[[9]][i]) + unlist(ensemble.runs.rcp26[[10]][i]) + unlist(ensemble.runs.rcp26[[11]][i]) + unlist(ensemble.runs.rcp26[[12]][i]) + unlist(ensemble.runs.rcp26[[13]][i]) + unlist(ensemble.runs.rcp26[[14]][i]) + unlist(ensemble.runs.rcp26[[15]][i]))/ntot.models.rcp26,n.lat.rean,n.lon.rean)))

ensemble.rcp85<-lapply(seq_along(ensemble.runs.rcp85[[1]]),function(i) (matrix((unlist(ensemble.runs.rcp85[[1]][i]) + unlist(ensemble.runs.rcp85[[2]][i]) + unlist(ensemble.runs.rcp85[[3]][i]) + unlist(ensemble.runs.rcp85[[4]][i]) + unlist(ensemble.runs.rcp85[[5]][i]) + unlist(ensemble.runs.rcp85[[6]][i]) + unlist(ensemble.runs.rcp85[[7]][i]) + unlist(ensemble.runs.rcp85[[8]][i]) + unlist(ensemble.runs.rcp85[[9]][i]) + unlist(ensemble.runs.rcp85[[10]][i]) + unlist(ensemble.runs.rcp85[[11]][i]) + unlist(ensemble.runs.rcp85[[12]][i]) + unlist(ensemble.runs.rcp85[[13]][i]) + unlist(ensemble.runs.rcp85[[14]][i]) + unlist(ensemble.runs.rcp85[[15]][i]))/ntot.models.rcp85,n.lat.rean,n.lon.rean)))

## in the future you can replace the three above calculations with a function like this:
# multimodel.ensemble<-function(multirun=list(),ntot.models,n.lat,n.lon){
#  multimodel<-lapply(seq_along(multirun[[1]]),function(i) (matrix((unlist(multirun[[1]][i]) + unlist(multirun[[2]][i]) + unlist(multirun[[3]][i]) + unlist(multirun[[4]][i]) + unlist(multirun[[5]][i]) + unlist(multirun[[6]][i]) + unlist(multirun[[7]][i]) + unlist(multirun[[8]][i]) + unlist(multirun[[9]][i]) + unlist(multirun[[10]][i]) + unlist(multirun[[11]][i]) + unlist(multirun[[12]][i]) + unlist(multirun[[13]][i]) + unlist(multirun[[14]][i]) + unlist(multirun[[15]][i]))/ntot.models,n.lat,n.lon)))
#  return(multimodel)
#}

# calculate the ensemble mean of all models for the parcelas:
ensemble.hist26.parcelas<-lapply(seq_along(ensemble.runs.hist26.parcelas[[1]]),function(i) ((unlist(ensemble.runs.hist26.parcelas[[1]][i]) + unlist(ensemble.runs.hist26.parcelas[[2]][i]) + unlist(ensemble.runs.hist26.parcelas[[3]][i]) + unlist(ensemble.runs.hist26.parcelas[[4]][i]) + unlist(ensemble.runs.hist26.parcelas[[5]][i]) + unlist(ensemble.runs.hist26.parcelas[[6]][i]) + unlist(ensemble.runs.hist26.parcelas[[7]][i]) + unlist(ensemble.runs.hist26.parcelas[[8]][i]) + unlist(ensemble.runs.hist26.parcelas[[9]][i]) + unlist(ensemble.runs.hist26.parcelas[[10]][i]) + unlist(ensemble.runs.hist26.parcelas[[11]][i]) + unlist(ensemble.runs.hist26.parcelas[[12]][i]) + unlist(ensemble.runs.hist26.parcelas[[13]][i]) + unlist(ensemble.runs.hist26.parcelas[[14]][i]) + unlist(ensemble.runs.hist26.parcelas[[15]][i]))/ntot.models.rcp26))

ensemble.hist85.parcelas<-lapply(seq_along(ensemble.runs.hist85.parcelas[[1]]),function(i) ((unlist(ensemble.runs.hist85.parcelas[[1]][i]) + unlist(ensemble.runs.hist85.parcelas[[2]][i]) + unlist(ensemble.runs.hist85.parcelas[[3]][i]) + unlist(ensemble.runs.hist85.parcelas[[4]][i]) + unlist(ensemble.runs.hist85.parcelas[[5]][i]) + unlist(ensemble.runs.hist85.parcelas[[6]][i]) + unlist(ensemble.runs.hist85.parcelas[[7]][i]) + unlist(ensemble.runs.hist85.parcelas[[8]][i]) + unlist(ensemble.runs.hist85.parcelas[[9]][i]) + unlist(ensemble.runs.hist85.parcelas[[10]][i]) + unlist(ensemble.runs.hist85.parcelas[[11]][i]) + unlist(ensemble.runs.hist85.parcelas[[12]][i]) + unlist(ensemble.runs.hist85.parcelas[[13]][i]) + unlist(ensemble.runs.hist85.parcelas[[14]][i]) + unlist(ensemble.runs.hist85.parcelas[[15]][i]))/ntot.models.rcp85))

ensemble.rcp26.parcelas<-lapply(seq_along(ensemble.runs.rcp26.parcelas[[1]]),function(i) ((unlist(ensemble.runs.rcp26.parcelas[[1]][i]) + unlist(ensemble.runs.rcp26.parcelas[[2]][i]) + unlist(ensemble.runs.rcp26.parcelas[[3]][i]) + unlist(ensemble.runs.rcp26.parcelas[[4]][i]) + unlist(ensemble.runs.rcp26.parcelas[[5]][i]) + unlist(ensemble.runs.rcp26.parcelas[[6]][i]) + unlist(ensemble.runs.rcp26.parcelas[[7]][i]) + unlist(ensemble.runs.rcp26.parcelas[[8]][i]) + unlist(ensemble.runs.rcp26.parcelas[[9]][i]) + unlist(ensemble.runs.rcp26.parcelas[[10]][i]) + unlist(ensemble.runs.rcp26.parcelas[[11]][i]) + unlist(ensemble.runs.rcp26.parcelas[[12]][i]) + unlist(ensemble.runs.rcp26.parcelas[[13]][i]) + unlist(ensemble.runs.rcp26.parcelas[[14]][i]) + unlist(ensemble.runs.rcp26.parcelas[[15]][i]))/ntot.models.rcp26))

ensemble.rcp85.parcelas<-lapply(seq_along(ensemble.runs.rcp85.parcelas[[1]]),function(i) ((unlist(ensemble.runs.rcp85.parcelas[[1]][i]) + unlist(ensemble.runs.rcp85.parcelas[[2]][i]) + unlist(ensemble.runs.rcp85.parcelas[[3]][i]) + unlist(ensemble.runs.rcp85.parcelas[[4]][i]) + unlist(ensemble.runs.rcp85.parcelas[[5]][i]) + unlist(ensemble.runs.rcp85.parcelas[[6]][i]) + unlist(ensemble.runs.rcp85.parcelas[[7]][i]) + unlist(ensemble.runs.rcp85.parcelas[[8]][i]) + unlist(ensemble.runs.rcp85.parcelas[[9]][i]) + unlist(ensemble.runs.rcp85.parcelas[[10]][i]) + unlist(ensemble.runs.rcp85.parcelas[[11]][i]) + unlist(ensemble.runs.rcp85.parcelas[[12]][i]) + unlist(ensemble.runs.rcp85.parcelas[[13]][i]) + unlist(ensemble.runs.rcp85.parcelas[[14]][i]) + unlist(ensemble.runs.rcp85.parcelas[[15]][i]))/ntot.models.rcp85))

# calculate the ensemble mean of all models for the grid of parcelas:
ensemble.hist26.grid.parcelas<-lapply(seq_along(ensemble.runs.hist26.grid.parcelas[[1]]),function(i) ((unlist(ensemble.runs.hist26.grid.parcelas[[1]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[2]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[3]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[4]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[5]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[6]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[7]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[8]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[9]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[10]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[11]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[12]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[13]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[14]][i]) + unlist(ensemble.runs.hist26.grid.parcelas[[15]][i]))/ntot.models.rcp26))

ensemble.hist85.grid.parcelas<-lapply(seq_along(ensemble.runs.hist85.grid.parcelas[[1]]),function(i) ((unlist(ensemble.runs.hist85.grid.parcelas[[1]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[2]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[3]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[4]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[5]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[6]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[7]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[8]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[9]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[10]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[11]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[12]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[13]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[14]][i]) + unlist(ensemble.runs.hist85.grid.parcelas[[15]][i]))/ntot.models.rcp85))

ensemble.rcp26.grid.parcelas<-lapply(seq_along(ensemble.runs.rcp26.grid.parcelas[[1]]),function(i) ((unlist(ensemble.runs.rcp26.grid.parcelas[[1]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[2]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[3]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[4]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[5]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[6]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[7]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[8]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[9]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[10]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[11]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[12]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[13]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[14]][i]) + unlist(ensemble.runs.rcp26.grid.parcelas[[15]][i]))/ntot.models.rcp26))

ensemble.rcp85.grid.parcelas<-lapply(seq_along(ensemble.runs.rcp85.grid.parcelas[[1]]),function(i) ((unlist(ensemble.runs.rcp85.grid.parcelas[[1]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[2]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[3]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[4]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[5]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[6]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[7]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[8]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[9]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[10]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[11]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[12]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[13]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[14]][i]) + unlist(ensemble.runs.rcp85.grid.parcelas[[15]][i]))/ntot.models.rcp85))

# calculate the ensemble mean of all models for the yearly parcelas:
ensemble.hist26.yearly.parcelas<-lapply(seq_along(ensemble.runs.hist26.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.hist26.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.hist26.yearly.parcelas[[15]][i]))/ntot.models.rcp26,n.years.hist,n.parcelas)))

ensemble.hist85.yearly.parcelas<-lapply(seq_along(ensemble.runs.hist85.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.hist85.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.hist85.yearly.parcelas[[15]][i]))/ntot.models.rcp85,n.years.hist,n.parcelas)))

ensemble.rcp26.yearly.parcelas<-lapply(seq_along(ensemble.runs.rcp26.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.rcp26.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.rcp26.yearly.parcelas[[15]][i]))/ntot.models.rcp26,n.years.rcp,n.parcelas)))

ensemble.rcp85.yearly.parcelas<-lapply(seq_along(ensemble.runs.rcp85.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.rcp85.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.rcp85.yearly.parcelas[[15]][i]))/ntot.models.rcp85,n.years.rcp,n.parcelas)))

ensemble.trans26.yearly.parcelas<-lapply(seq_along(ensemble.runs.trans26.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.trans26.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.trans26.yearly.parcelas[[15]][i]))/ntot.models.rcp26,n.years.trans,n.parcelas)))

ensemble.trans85.yearly.parcelas<-lapply(seq_along(ensemble.runs.trans85.yearly.parcelas[[1]]),function(i) (matrix((unlist(ensemble.runs.trans85.yearly.parcelas[[1]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[2]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[3]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[4]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[5]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[6]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[7]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[8]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[9]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[10]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[11]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[12]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[13]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[14]][i]) + unlist(ensemble.runs.trans85.yearly.parcelas[[15]][i]))/ntot.models.rcp85,n.years.trans,n.parcelas)))

# calculate the delta for the parcelas:
ensemble.delta26.parcelas <- lapply(seq_along(ensemble.runs.rcp26.parcelas[[1]]),function(i) (unlist(ensemble.rcp26.parcelas[i]) - unlist(ensemble.hist26.parcelas[i])))
ensemble.delta85.parcelas <- lapply(seq_along(ensemble.runs.rcp85.parcelas[[1]]),function(i) (unlist(ensemble.rcp85.parcelas[i]) - unlist(ensemble.hist85.parcelas[i])))

# calculate the delta for the grid of parcelas:
ensemble.delta26.grid.parcelas <- lapply(seq_along(ensemble.runs.rcp26.grid.parcelas[[1]]),function(i) (unlist(ensemble.rcp26.grid.parcelas[i]) - unlist(ensemble.hist26.grid.parcelas[i])))
ensemble.delta85.grid.parcelas <- lapply(seq_along(ensemble.runs.rcp85.grid.parcelas[[1]]),function(i) (unlist(ensemble.rcp85.grid.parcelas[i]) - unlist(ensemble.hist85.grid.parcelas[i])))

# save the values for the grid of parcelas:
my.lat.lon.grid<-cbind(lat=grid.lat,lon=grid.lon)
my.grid.indices.rean<-as.data.frame(grid.indices.rean,col.names=index.name0);names(my.grid.indices.rean)<-paste("Obs",index.name.very.short,sep="_")
my.ensemble.delta26.grid.parcelas<-as.data.frame(matrix(unlist(ensemble.delta26.grid.parcelas),n.grid.points,n.indices));names(my.ensemble.delta26.grid.parcelas)<-paste("MM26",index.name.very.short,sep="_")
my.ensemble.delta85.grid.parcelas<-as.data.frame(matrix(unlist(ensemble.delta85.grid.parcelas),n.grid.points,n.indices));names(my.ensemble.delta85.grid.parcelas)<-paste("MM85",index.name.very.short,sep="_")
my.percentil25.delta.rcp26.grid.parcelas<-as.data.frame(t(percentil25.delta.rcp26.grid.parcelas));names(my.percentil25.delta.rcp26.grid.parcelas)<-paste("MM26_p25_",index.name.very.short,sep="_")
my.percentil75.delta.rcp26.grid.parcelas<-as.data.frame(t(percentil75.delta.rcp26.grid.parcelas));names(my.percentil75.delta.rcp26.grid.parcelas)<-paste("MM26_p75_",index.name.very.short,sep="_")
my.percentil25.delta.rcp85.grid.parcelas<-as.data.frame(t(percentil25.delta.rcp85.grid.parcelas));names(my.percentil25.delta.rcp85.grid.parcelas)<-paste("MM85_p25_",index.name.very.short,sep="_")
my.percentil75.delta.rcp85.grid.parcelas<-as.data.frame(t(percentil75.delta.rcp85.grid.parcelas));names(my.percentil75.delta.rcp85.grid.parcelas)<-paste("MM85_p75_",index.name.very.short,sep="_")
my.output.arcgis<-cbind(my.lat.lon.grid,my.grid.indices.rean,my.ensemble.delta26.grid.parcelas,my.percentil25.delta.rcp26.grid.parcelas,my.percentil75.delta.rcp26.grid.parcelas,my.ensemble.delta85.grid.parcelas,my.percentil25.delta.rcp85.grid.parcelas,my.percentil75.delta.rcp85.grid.parcelas)

write.table(my.output.arcgis,file=paste0(path.data,"/input_gis.txt"), row.names=FALSE)

# Maps of the ensemble of the Historical for RCP 2.6 (for each index):
    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
      png(filename=paste0(path.data,"/Ensemble/Ensemble_Historical26_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble Historical for RCP 2.6)")
      #if(models.firstdim=="lat") {contour.data<-ensemble.hist26[[my.index]]} else {contour.data<-t(ensemble.hist26[[my.index]])}
      contour.data<-ensemble.hist26[[my.index]] # since the Ensemble always starts with the lat

      PlotEquiMap2(ensemble.hist26[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)
      
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

 # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/Ensemble/Ensemble_Historical26_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      my.toptitle<-paste0(index.name.short[my.index]," (Ensemble Historical for RCP 2.6)")

      # to solve some bugs of PlotEquiMap:
      # if(models.firstdim=="lat") {plot.data<-ensemble.hist26[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-ensemble.hist26[[my.index]][my.lat.pos,my.lon.pos]}
      plot.data<-ensemble.hist26[[my.index]][my.lat.pos,my.lon.pos] # since the Ensemble data always starts with the lat
      
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=4,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }


# Maps of the ensemble of the Historical for RCP 8.5 (for each index):
    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)
      png(filename=paste0(path.data,"/Ensemble/Ensemble_Historical85_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble Historical for RCP 8.5)")
      #if(models.firstdim=="lat") {contour.data<-ensemble.hist26[[my.index]]} else {contour.data<-t(ensemble.hist26[[my.index]])}
      contour.data<-ensemble.hist85[[my.index]] # since the Ensemble always starts with the lat

      PlotEquiMap2(ensemble.hist85[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)
      
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

 # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    if(length(my.lat.pos)<=1) my.lat.pos<-which(lat.rean<bigpata.latmax+2 & lat.rean>bigpata.latmin-2) # to plot at least 2 grid points for lat and 2 grid points for lon
    if(length(my.lon.pos)<=1) my.lon.pos<-which(lon.rean<bigpata.lonmax+2 & lon.rean>bigpata.lonmin-2)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      #png(filename=paste0(outputdir,"/indices_historical/",models.hist[mod],"_run_",run,"_interp_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      png(filename=paste0(path.data,"/Ensemble/Ensemble_Historical85_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)
      my.toptitle<-paste0(index.name.short[my.index]," (Ensemble Historical for RCP 8.5)")

      # to solve some bugs of PlotEquiMap:
      # if(models.firstdim=="lat") {plot.data<-ensemble.hist26[[my.index]][my.lon.pos,my.lat.pos] } else {plot.data<-ensemble.hist26[[my.index]][my.lat.pos,my.lon.pos]}
      plot.data<-ensemble.hist85[[my.index]][my.lat.pos,my.lon.pos] # since the Ensemble data always starts with the lat
      
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=4,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }


### calculate the ensemble weighted of the historical of the RCP 2.6 with the inverse of the RMSE:
my.lat.pos.zoom<-my.lat.pos[zoom.lat.min:zoom.lat.max]
my.lon.pos.zoom<-my.lon.pos[zoom.lon.min:zoom.lon.max]

# first, calculate the weights of each run:
rmse26<-array(NA,c(n.max.runs,n.max.models,n.indices))
for(mod in 1:n.max.models){
   for(run in 1:n.max.runs){
      if(n.runs.rcp26[run,mod] != 0){
        for(ind in 1:n.indices){
           rmse26[run,mod,ind]<-RMSE(as.vector(index.rean[[ind]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(run.hist26[[mod]][[run]][[ind]][my.lat.pos.zoom,my.lon.pos.zoom]))
        }
      }
    }
 }

# then, calculate the weights of each model as the mean of the weights of its runs:
rmse26.ensemble<-apply(rmse26,c(2,3),mean,na.rm=T)  # in the rows of rmse.ensemble there are the models and in the columns the indices

## alternative way to calculate the weights of each model:
#rmse26.ensemble<-array(NA,c(n.max.models,n.indices))
#for(mod in 1:n.max.models){
#      if(ntot.runs.rcp26[mod] != 0){
#        for(ind in 1:n.indices){
#           rmse26.ensemble[mod,ind]<-RMSE(as.vector(index.rean[[ind]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(ensemble.runs.hist26[[mod]][[ind]][my.lat.pos.zoom,my.lon.pos.zoom]))
#        }
#      }
# }

# weight calculation as the inverse of the rmse:
weight26<-1/rmse26.ensemble
ss<-which(is.na(rmse26.ensemble))
if(length(ss)>0) weight26[ss]<-0 # if there are models with no runs we must put them to 0 weight
sum.weight26<-colSums(weight26)

# finally, calculate the weighted ensemble:
ensemble.hist26.weighted<-lapply(seq_along(ensemble.runs.hist26[[1]]),function(i) (matrix((unlist(ensemble.runs.hist26[[1]][i])*weight26[1,i] + unlist(ensemble.runs.hist26[[2]][i])*weight26[2,i] + unlist(ensemble.runs.hist26[[3]][i])*weight26[3,i] + unlist(ensemble.runs.hist26[[4]][i])*weight26[4,i] + unlist(ensemble.runs.hist26[[5]][i])*weight26[5,i] + unlist(ensemble.runs.hist26[[6]][i])*weight26[6,i] + unlist(ensemble.runs.hist26[[7]][i])*weight26[7,i] + unlist(ensemble.runs.hist26[[8]][i])*weight26[8,i] + unlist(ensemble.runs.hist26[[9]][i])*weight26[9,i] + unlist(ensemble.runs.hist26[[10]][i])*weight26[10,i] + unlist(ensemble.runs.hist26[[11]][i])*weight26[11,i] + unlist(ensemble.runs.hist26[[12]][i])*weight26[12,i] + unlist(ensemble.runs.hist26[[13]][i])*weight26[13,i] + unlist(ensemble.runs.hist26[[14]][i])*weight26[14,i] + unlist(ensemble.runs.hist26[[15]][i])*weight26[15,i])/sum.weight26[i],n.lat.rean,n.lon.rean)))

### calculate the ensemble weighted of the historical of the RCP 8.5 with the inverse of the RMSE:
my.lat.pos.zoom<-my.lat.pos[zoom.lat.min:zoom.lat.max]
my.lon.pos.zoom<-my.lon.pos[zoom.lon.min:zoom.lon.max]

# first, calculate the weights of each run:
rmse85<-array(NA,c(n.max.runs,n.max.models,n.indices))
for(mod in 1:n.max.models){
   for(run in 1:n.max.runs){
      if(n.runs.rcp85[run,mod] != 0){
        for(ind in 1:n.indices){
           rmse85[run,mod,ind]<-RMSE(as.vector(index.rean[[ind]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(run.hist85[[mod]][[run]][[ind]][my.lat.pos.zoom,my.lon.pos.zoom]))
        }
      }
    }
 }

# then, calculate the weights of each model as the mean of the weights of its runs:
rmse85.ensemble<-apply(rmse85,c(2,3),mean,na.rm=T)  # in the rows of rmse.ensemble there are the models and in the columns the indices

## alternative way to calculate the weights of each model:
#rmse85.ensemble<-array(NA,c(n.max.models,n.indices))
#for(mod in 1:n.max.models){
#      if(ntot.runs.rcp85[mod] != 0){
#        for(ind in 1:n.indices){
#           rmse85.ensemble[mod,ind]<-RMSE(as.vector(index.rean[[ind]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(ensemble.runs.hist85[[mod]][[ind]][my.lat.pos.zoom,my.lon.pos.zoom]))
#        }
#      }
# }
#

weight85<-1/rmse85.ensemble
ss<-which(is.na(rmse85.ensemble))
if(length(ss)>0) weight85[ss]<-0 # if there are models with no runs we must put them to 0 weight
sum.weight85<-colSums(weight85)

# finally, calculate the weighted ensemble:
ensemble.hist85.weighted<-lapply(seq_along(ensemble.runs.hist85[[1]]),function(i) (matrix((unlist(ensemble.runs.hist85[[1]][i])*weight85[1,i] + unlist(ensemble.runs.hist85[[2]][i])*weight85[2,i] + unlist(ensemble.runs.hist85[[3]][i])*weight85[3,i] + unlist(ensemble.runs.hist85[[4]][i])*weight85[4,i] + unlist(ensemble.runs.hist85[[5]][i])*weight85[5,i] + unlist(ensemble.runs.hist85[[6]][i])*weight85[6,i] + unlist(ensemble.runs.hist85[[7]][i])*weight85[7,i] + unlist(ensemble.runs.hist85[[8]][i])*weight85[8,i] + unlist(ensemble.runs.hist85[[9]][i])*weight85[9,i] + unlist(ensemble.runs.hist85[[10]][i])*weight85[10,i] + unlist(ensemble.runs.hist85[[11]][i])*weight85[11,i] + unlist(ensemble.runs.hist85[[12]][i])*weight85[12,i] + unlist(ensemble.runs.hist85[[13]][i])*weight85[13,i] + unlist(ensemble.runs.hist85[[14]][i])*weight85[14,i] + unlist(ensemble.runs.hist85[[15]][i])*weight85[15,i])/sum.weight85[i],n.lat.rean,n.lon.rean)))


# Taylor diagram of all historical runs for RCP 2.6:
# only check index 1 (Mean Annual Temp) and index 5 (Total Precipitation), use x11() to open a new window
for(my.index in 1:n.indices){
  png(filename=paste0(path.data,"/Ensemble/Taylor",suffix,"_RCP26_",my.index,"_",index.name0[my.index],".png"),width=500,height=500)
      my.obs<-as.vector(index.rean[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom])
      first.point=0
      for(mod in 1:n.max.models){
         for(run in 1:n.max.runs){
            if(n.runs.rcp26[run,mod] != 0){
              #print(paste(mod,run,cor(as.vector(index.rean[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(run.hist[[mod]][[run]][[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]))))

              my.pred<-as.vector(run.hist26[[mod]][[run]][[my.index]][my.lat.pos.zoom,my.lon.pos.zoom])
              if(first.point==0) my.taylor(my.obs,my.pred,sd.arcs=1,normalize=TRUE,main=paste0(index.name.short[my.index]),pcex=.7,cex.axis=1,xlab="Variance Ratio",ylab="Variance Ratio",ngamma=6, gamma.col="darkseagreen", mar = c(4, 4, 2, 2), BIAS=FALSE, my.text="", text.cex=1, col=col.taylor[mod])
              if(first.point==1) my.taylor(my.obs,my.pred,sd.arcs=1,normalize=TRUE,main=paste0(index.name.short(my.index)),pcex=.7,cex.axis=1,xlab="Variance Ratio",ylab="Variance Ratio",ngamma=6, gamma.col="darkseagreen", mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=1, col=col.taylor[mod])
              #Sys.sleep(1)
              first.point=1
            }
          }
       }

      ### add reanalysis point:
      my.taylor(my.obs,my.obs,sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1.5,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=13, col="black")

      ### add ensemble point (the red *) to the Taylor's diagram (red *):
      my.taylor(my.obs,as.vector(ensemble.hist26[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=8, col="red")

      ### add to the Taylor's diagram the point of the weighted ensemble (brown *):
      #my.taylor(my.obs,as.vector(ensemble.hist26.weighted[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=8, col="brown")

  dev.off()
  
} # close for on my.index


# add legend of the Taylor's diagram in another plot:
png(filename=paste0(path.data,"/Ensemble/Taylor",suffix,"_legend_RCP26.png"),width=300,height=500)  
    legend.labels<-legend.colors<-c()
    for(mod in 1:n.max.models){
       for(run in 1:n.max.runs){
          if(n.runs.rcp26[run,mod] != 0){
            legend.labels<-c(legend.labels,paste0("Modelo ",model.names[mod],"  Run #",n.runs.rcp26[run,mod]))
            legend.colors<-c(legend.colors,col.taylor[mod])
          }
        }
     }

    #legend.labels<-c(legend.labels,"Multimodel","Weighted Multimodel")
    legend.labels<-c(legend.labels,"Multimodelo","Multimodelo ponderado","Observaciones (ERA-Interim)")
    legend.colors<-c(legend.colors,"red","blue","black")

    par(oma=c(0,0,0,0))
    plot(1, type = "n", axes = FALSE, ann = FALSE); # title("Legend")
    legend("top", legend = legend.labels, col = legend.colors,  ncol = 1, cex = .9, lwd = NA, pch=c(rep(20, sum(ntot.runs.rcp26,na.rm=T)),8,8,13), text.font = 1, text.col = legend.colors)
dev.off()

#save(ensemble.rcp26,file=paste0(path.data,"/Ensemble/","Ensemble_Rcp26.RData"))
#save(ensemble.hist26,file=paste0(path.data,"/Ensemble/","Ensemble_Historical26.RData"))
#save(ensemble.hist,file=paste0(path.data,"/Ensemble/","Ensemble_Historical.RData"))
#rm(ensemble.hist26,ensemble.hist26.weighted,ensemble.runs.hist26)

# Taylor diagram of all historical runs for RCP 8.5:
# only check index 1 (Mean Annual Temp) and index 5 (Total Precipitation), use x11() to open a new window
for(my.index in 1:n.indices){
  my.obs<-as.vector(index.rean[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom])
  png(filename=paste0(path.data,"/Ensemble/Taylor",suffix,"_RCP85_",my.index,"_",index.name0[my.index],".png"),width=500,height=500)  
      first.point=0
      for(mod in 1:n.max.models){
         for(run in 1:n.max.runs){
            if(n.runs.rcp85[run,mod] != 0){
              #print(paste(mod,run,cor(as.vector(index.rean[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),as.vector(run.hist[[mod]][[run]][[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]))))

              my.pred<-as.vector(run.hist85[[mod]][[run]][[my.index]][my.lat.pos.zoom,my.lon.pos.zoom])
              if(first.point==0) my.taylor(my.obs,my.pred,sd.arcs=1,normalize=TRUE,main=paste0(index.name.short[my.index]),pcex=.6,cex.axis=1,xlab="Variance Ratio",ylab="Variance Ratio",ngamma=6, gamma.col="darkseagreen", mar = c(4, 4, 2, 2), BIAS=FALSE, my.text="", text.cex=1, col=col.taylor[mod])
              if(first.point==1) my.taylor(my.obs,my.pred,sd.arcs=1,normalize=TRUE,main=paste0(index.name.short(my.index)),pcex=.6,cex.axis=1,xlab="Variance Ratio",ylab="Variance Ratio",ngamma=6, gamma.col="darkseagreen", mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=1, col=col.taylor[mod])
              #Sys.sleep(1)
              first.point=1
            }
          }
       }


      ### add reanalysis point:
      my.taylor(my.obs,my.obs,sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1.5,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=13, col="black")

      ### add ensemble point (the red *) to the Taylor's diagram:
      my.taylor(my.obs,as.vector(ensemble.hist85[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=8, col="red")

      ### add to the Taylor's diagram the point of the weighted ensemble (the blue *):
      #my.taylor(my.obs,as.vector(ensemble.hist85.weighted[[my.index]][my.lat.pos.zoom,my.lon.pos.zoom]),sd.arcs=1,normalize=TRUE,main=paste0("Historial Ensemble Index ",my.index),pcex=1,cex.axis=1,xlab="RMSE",ylab="Variance Ratio",ngamma=6,mar = c(4, 4, 2, 2), add=TRUE, BIAS=FALSE, my.text="", text.cex=.7, pch=8, col="blue")

  dev.off()
  
} # close for on my.index


# add legend of the Taylor's diagram in another plot:
png(filename=paste0(path.data,"/Ensemble/Taylor",suffix,"legend_RCP85.png"),width=300,height=500)  
    legend.labels<-legend.colors<-c()
    for(mod in 1:n.max.models){
       for(run in 1:n.max.runs){
          if(n.runs.rcp85[run,mod] != 0){
            legend.labels<-c(legend.labels,paste0("Modelo ",model.names[mod],"  Run #",n.runs.rcp85[run,mod]))
            legend.colors<-c(legend.colors,col.taylor[mod])
          }
        }
     }

    #legend.labels<-c(legend.labels,"Multimodel","Weighted Multimodel")
    legend.labels<-c(legend.labels,"Multimodelo","Multimodelo ponderado","Observaciones (ERA-Interim)")
    legend.colors<-c(legend.colors,"red","blue","black")

    par(oma=c(0,0,0,0))
    plot(1, type = "n", axes = FALSE, ann = FALSE); # title("Legend")
    legend("top", legend = legend.labels, col = legend.colors,  ncol = 1, cex = .9, lwd = NA, pch=c(rep(20, sum(ntot.runs.rcp85,na.rm=T)),8,8,13), text.font = 1, text.col = legend.colors)
dev.off()


############ ENSEMBLE FUTURE SCENARIO with the selected runs ######################################################################

# Maps of the Ensemble of RCP 2.6:
    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP26_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble RCP 2.6)")
      
      PlotEquiMap2(ensemble.rcp26[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP26_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (Ensemble RCP 2.6)")

      # to solve some bugs of PlotEquiMap:
      plot.data<-ensemble.rcp26[[my.index]][my.lat.pos,my.lon.pos]
      #contour.data<-index.rcp26.interp[[my.index]][my.lon.pos,my.lat.pos]
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
                   # contours=NULL,intylat=1,intxlon=1,drawleg=F)
                   
      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }

    # the same charts as above, but plotting the difference between the rcp 2.6 and the historical data:
    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP26_tendency_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble RCP 8.5 - Historical)")
      plot.data<-ensemble.rcp26[[my.index]]-ensemble.hist26[[my.index]]
        
      PlotEquiMap2(plot.data,lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP26_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (RCP 8.5 - Historical)")

      # to solve some bugs of PlotEquiMap:
      plot.data<-ensemble.rcp26[[my.index]][my.lat.pos,my.lon.pos]-ensemble.hist26[[my.index]][my.lat.pos,my.lon.pos]

      layout(matrix(c(1,1,1,1,2), 1, 5, byrow = TRUE))
      par(oma=c(1,0,0,0.2))
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=TRUE,cex=1.3)
      
      dev.off()
    }


# Maps of the Ensemble of RCP 8.5:
    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP85_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble RCP 8.5)")
      
      PlotEquiMap2(ensemble.rcp85[[my.index]],lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }

    # the same charts as above, but only for the Big Patagonia and plotting the location of the four parcelas:
    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP85_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (Ensemble RCP 8.5)")

      # to solve some bugs of PlotEquiMap:
      plot.data<-ensemble.rcp85[[my.index]][my.lat.pos,my.lon.pos]
      #contour.data<-index.rcp85.interp[[my.index]][my.lon.pos,my.lat.pos]
      layout(matrix(c(1,1,1,1,1,2), 1, 6, byrow = TRUE))
      #layout.show(2)
      par(oma=c(1,0,0,0.5))
      #par(mfrow=c(2,1))
      #x11(width=4,height=.8)
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],intylat=1,intxlon=1,drawleg=F)
                   # contours=NULL,intylat=1,intxlon=1,drawleg=F)
                   
      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks[[my.index]],cols=colorRampPalette(my.palette[[my.index]])(length(my.brks[[my.index]])-1),vert=TRUE,cex=1.3,my.subsamplegbar[[my.index]])
      dev.off()
    }


    # the same charts as above, but plotting the difference between the rcp 8.5 and the historical data:
    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP85_tendency_Worldmap_Indice_",my.index,"_",index.name0[my.index],".png"),width=800,height=480)

      layout(matrix(c(1,1,1,1,1,1,1,1,2), 9, 1, byrow = TRUE))
      #layout.show(2)
      my.toptitle<-paste0(index.name[my.index]," (Ensemble RCP 8.5 - Historical)")
      plot.data<-ensemble.rcp85[[my.index]]-ensemble.hist85[[my.index]]
        
      PlotEquiMap2(plot.data,lon.rean,lat.rean,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],
                   contours=list(NULL,NULL,NULL,NULL,NULL,NULL)[[my.index]],brks2=my.brks.dos[[my.index]],contours.col=my.contours.col[[my.index]],drawleg=F)

      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=F,cex=.8)
      dev.off()
    }


    my.lat.pos<-which(lat.rean < bigpata.latmax & lat.rean > bigpata.latmin)
    my.lon.pos<-which(lon.rean < bigpata.lonmax & lon.rean > bigpata.lonmin)
    my.lat<-lat.rean[my.lat.pos] # select only Patagonia pixels
    my.lon<-lon.rean[my.lon.pos]

    for(my.index in 1:n.indices){
      png(filename=paste0(path.data,"/Ensemble/Ensemble_RCP85_tendency_BigPatagonia_Indice_",my.index,"_",index.name0[my.index],".png"),width=500,height=1500)

      my.toptitle<-paste0(index.name.short[my.index]," (Ensemble RCP 8.5 - Historical)")

      # to solve some bugs of PlotEquiMap:
      plot.data<-ensemble.rcp85[[my.index]][my.lat.pos,my.lon.pos]-ensemble.hist85[[my.index]][my.lat.pos,my.lon.pos]

      layout(matrix(c(1,1,1,1,2), 1, 5, byrow = TRUE))
      par(oma=c(1,0,0,0.2))
      PlotEquiMap2(plot.data,my.lon,my.lat,toptitle=my.toptitle,sizetit = 0.6,
                   brks=my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),
                   filled.continents=F,units=my.units[my.index],subsampleg=my.subsampleg[my.index],contours=NULL,intylat=1,intxlon=1,drawleg=F)

      my.parcelas<-data.frame(name=parcelas.names,lat=parcelas.lat,long=parcelas.lon,pop=0,capital=0,stringsAsFactors=F)
      map.cities(my.parcelas,pch=3,cex=3,col=c("purple","blue","red","black"),label=FALSE)  # add the 4 points of the 4 parcelas
      ColorBar(my.brks.trend[[my.index]],cols=colorRampPalette(my.palette.trend[[my.index]])(length(my.brks.trend[[my.index]])-1),vert=TRUE,cex=1.3)
      
      dev.off()
    }


  

# plot yearly time serie of each index:

ind=1

#png(filename=paste0(path.data,"/Ensemble/Time_series_",ind,"_",index.name0[ind],".png"),width=1000,height=480)

ensemble.obs.trans.rcp26.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)
ensemble.obs.trans.rcp85.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)

index.rean.year.full<-as.numeric(c(index.rean.year[ind,,par],rep(NA,n.years.trans+n.years.rcp)))

for(par in 1:n.parcelas) ensemble.obs.trans.rcp26.yearly.parcelas[,par]<-c(rep(NA,n.years.hist),ensemble.trans26.yearly.parcelas[[ind]][,par],ensemble.rcp26.yearly.parcelas[[ind]][,par])
for(par in 1:n.parcelas) ensemble.obs.trans.rcp85.yearly.parcelas[,par]<-c(rep(NA,n.years.hist),ensemble.trans85.yearly.parcelas[[ind]][,par],ensemble.rcp85.yearly.parcelas[[ind]][,par])

yrange<-range(c(index.rean.year.full[!is.na(index.rean.year.full)],ensemble.obs.trans.rcp26.yearly.parcelas[!is.na(ensemble.obs.trans.rcp26.yearly.parcelas)],ensemble.obs.trans.rcp85.yearly.parcelas[!is.na(ensemble.obs.trans.rcp85.yearly.parcelas)]))

par(mar=c(5,8,1,2)+0.1,mgp=c(5,1,0))
plot(1985:2050,index.rean.year.full,xlab="Año",ylab=index.name.short[ind],cex.lab=2,cex.axis=1.5,las=1,ylim=yrange,col="black",type="l",xaxp=c(1985,2050,13))

lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,1],type="l",col="red",lty=2)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,2],type="l",col="blue",lty=2)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,3],type="l",col="brown",lty=2)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,4],type="l",col="purple",lty=2)

lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,1],type="l",col="red")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,2],type="l",col="blue")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,3],type="l",col="brown")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,4],type="l",col="purple")

#dev.off()



# the same but without adding the ERA-Interima data (it is replaced by the historical data)
ensemble.all26.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)
ensemble.all85.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)

for(par in 1:n.parcelas) ensemble.all26.yearly.parcelas[,par]<-c(ensemble.hist26.yearly.parcelas[[ind]][,par],ensemble.trans26.yearly.parcelas[[ind]][,par],ensemble.rcp26.yearly.parcelas[[ind]][,par])
for(par in 1:n.parcelas) ensemble.all85.yearly.parcelas[,par]<-c(ensemble.hist85.yearly.parcelas[[ind]][,par],ensemble.trans85.yearly.parcelas[[ind]][,par],ensemble.rcp85.yearly.parcelas[[ind]][,par])

yrange<-range(c(ensemble.all26.yearly.parcelas,ensemble.all85.yearly.parcelas))

plot(1985:2050,1:66,type="n",xlab="Año",ylab=index.name.short[ind],cex.lab=2,cex.axis=1.5,las=1,xaxp=c(1985,2050,13),ylim=yrange)

lines(1985:2050,ensemble.all26.yearly.parcelas[,1],type="l",col="red",lty=2)
lines(1985:2050,ensemble.all26.yearly.parcelas[,2],type="l",col="blue",lty=2)
lines(1985:2050,ensemble.all26.yearly.parcelas[,3],type="l",col="black",lty=2)
lines(1985:2050,ensemble.all26.yearly.parcelas[,4],type="l",col="purple",lty=2)

lines(1985:2050,ensemble.all85.yearly.parcelas[,1],type="l",col="red")
lines(1985:2050,ensemble.all85.yearly.parcelas[,2],type="l",col="blue")
lines(1985:2050,ensemble.all85.yearly.parcelas[,3],type="l",col="black")
lines(1985:2050,ensemble.all85.yearly.parcelas[,4],type="l",col="purple")


# plot yearly time serie of each index with the delta rcp - hist after the observed data:

for (ind in 1:6){

ensemble.obs.trans.rcp26.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)
ensemble.obs.trans.rcp85.yearly.parcelas<-matrix(NA,n.years.tot,n.parcelas)

index.rean.year.full<-as.numeric(c(index.rean.year[ind,,],rep(NA,n.years.trans+n.years.rcp)))

for(par in 1:n.parcelas) ensemble.obs.trans.rcp26.yearly.parcelas[,par]<-c(rep(NA,n.years.hist),c(ensemble.trans26.yearly.parcelas[[ind]][,par],ensemble.rcp26.yearly.parcelas[[ind]][,par]) - ensemble.hist26.parcelas[[ind]][par] + parcelas.indices.rean[par,ind])

for(par in 1:n.parcelas) ensemble.obs.trans.rcp85.yearly.parcelas[,par]<-c(rep(NA,n.years.hist),c(ensemble.trans85.yearly.parcelas[[ind]][,par],ensemble.rcp85.yearly.parcelas[[ind]][,par]) - ensemble.hist85.parcelas[[ind]][par] + parcelas.indices.rean[par,ind])

yrange<-range(c(index.rean.year.full[!is.na(index.rean.year.full)],ensemble.obs.trans.rcp26.yearly.parcelas[!is.na(ensemble.obs.trans.rcp26.yearly.parcelas)],ensemble.obs.trans.rcp85.yearly.parcelas[!is.na(ensemble.obs.trans.rcp85.yearly.parcelas)]))

if(ind<5) {my.legend='bottomright'} else {my.legend='topright'}

png(filename=paste0(path.data,"/Ensemble/Time_series_RCP26_",ind,"_",index.name0[ind],".png"),width=1000,height=400)

par(mar=c(6,8,1,2)+0.1,mgp=c(5,1,0))
plot(1985:2050,1:66,xlab="Año",ylab=index.name.short[ind],cex.lab=2,cex.axis=1.5,las=1,ylim=yrange,type="n",xaxp=c(1985,2050,13))

lines(1985:2050,as.numeric(c(index.rean.year[ind,,1],rep(NA,n.years.trans+n.years.rcp))),type="l",col="red",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,2],rep(NA,n.years.trans+n.years.rcp))),type="l",col="blue",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,3],rep(NA,n.years.trans+n.years.rcp))),type="l",col="darkgreen",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,4],rep(NA,n.years.trans+n.years.rcp))),type="l",col="black",lty=1)

lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,1],type="l",col="red",lty=1)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,2],type="l",col="blue",lty=1)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,3],type="l",col="darkgreen",lty=1)
lines(1985:2050,ensemble.obs.trans.rcp26.yearly.parcelas[,4],type="l",col="black",lty=1)

legend(my.legend, parcelas.names, lty=1, col=c('red', 'blue', 'darkgreen',' black'), bty='n', cex=1)

dev.off()

# the same, but for the RCP 8.5

png(filename=paste0(path.data,"/Ensemble/Time_series_RCP85_",ind,"_",index.name0[ind],".png"),width=1000,height=400)

par(mar=c(6,8,1,2)+0.1,mgp=c(5,1,0))
plot(1985:2050,1:66,xlab="Año",ylab=index.name.short[ind],cex.lab=2,cex.axis=1.5,las=1,ylim=yrange,type="n",xaxp=c(1985,2050,13))

lines(1985:2050,as.numeric(c(index.rean.year[ind,,1],rep(NA,n.years.trans+n.years.rcp))),type="l",col="red",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,2],rep(NA,n.years.trans+n.years.rcp))),type="l",col="blue",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,3],rep(NA,n.years.trans+n.years.rcp))),type="l",col="darkgreen",lty=1)
lines(1985:2050,as.numeric(c(index.rean.year[ind,,4],rep(NA,n.years.trans+n.years.rcp))),type="l",col="black",lty=1)

lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,1],type="l",col="red")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,2],type="l",col="blue")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,3],type="l",col="darkgreen")
lines(1985:2050,ensemble.obs.trans.rcp85.yearly.parcelas[,4],type="l",col="black")
legend(my.legend, parcelas.names, lty=1, col=c('red', 'blue', 'darkgreen',' black'), bty='n', cex=1)

dev.off()

} # cloose loop on ind


save.image(file=paste0(path.data,"/Ensemble/Bodega_base_ensemble.RData"))

} # close if on ensemble

