
# Creation: 6/2016
# Author: Nicola Cortesi
#
# Aim: to visualize the regime anomalies of the weather regimes, their interannual frequencies and their impact on a chosen cliamte variable (i.e: wind speed or temperature)
#
# I/O: the only input file needed is the output of the weather_regimes.R script, which ends with the suffix "_mapdata.RData".
#      Output files are the maps, with the user can generate as .png or as .pdf
#
# Assumptions: If your regimes derive from a reanalysis, this script must be run twice: once, with the option 'ordering = F' and 'save.names = T' to create a .pdf or .png
#              file that the user must open to find visually the order by which the four regimes are stored inside the four clusters. For example, he can find that the
#              sequence of the images in the file (from top to down) corresponds to: Blocking / NAO- / Atl.Ridge / NAO+ regime. Subsequently, he has to change 'ordering'
#              from F to T and set the four variables 'clusterX.name' (X=1..4) to follow the same order found inside that file.
#              The second time, you have to run this script only to get the maps in the right order, which by default is, from top to down:
#              "NAO+","NAO-","Blocking" and "Atl.Ridge" (you can change it with the variable 'orden'). You also have to set 'save.names' to TRUE, so an .RData file
#              is written to store the order of the four regimes, in case in future a user needs to visualize these maps again. In this case, the user must set
#              'ordering = TRUE' and 'save.names = FALSE' to be able to visualize the maps in the correct order.
#
#              If your regimes derive from a forecast system, you have to compute before the regimes derived from a reanalysis. Then, you can associate the reanalysis
#              to the forecast system, to employ it to automatically associate to each simulated cluster one of the
#              observed regimes, the one with the highest spatial correlation. Beware that the two maps of regime anomalies must have the same spatial resolution!
#
# Branch: weather_regimes

library(s2dverification)  # for the function Load()
library(Kendall) # for the MannKendall test

source('/home/Earth/ncortesi/Downloads/scripts/Rfunctions.R') # for the calendar functions

# working dir with the input files with '_psl.RData' suffix:

workdir <- "/scratch/Earth/ncortesi/RESILIENCE/Regimes/42_ECMWF_S4_monthly_1981-2015_LOESS_filter"  

rean.name <- "ERA-Interim"       # reanalysis name (if input data comes from a reanalysis)
forecast.name <- "ECMWF-S4"      # forecast system name (if input data comes from a forecast system)

fields.name <- forecast.name         # Choose between loading reanalysis ('rean.name') or forecasts ('forecast.name')

var.num <- 1                     # if fields.name ='rean.name', Choose a variable for the impact maps 1: sfcWind  2: tas

period <- 1:12                      # Choose one or more periods to plot from 1 to 17 (1-12: Jan - Dec, 13-16: Winter, Spring, Summer, Autumn, 17: Year).
                                    # You need to have created before the '_mapdata.RData' file with the output of 'weather_regimes'.R for that period. 
lead.months <- 0:6                  # in case you selected 'fields.name = forecast.name', specify a leadtime (0 = same month of the start month) to plot
                                    # (and variable 'period' becomes the start month)

# run it twice: once, with 'ordering <- FALSE' and 'save.names <- TRUE' to look only at the cartography and find visually the right regime names of the four clusters; then,
# insert the regime names in the correct order below and run this script a the second time with 'ordering = TRUE' and 'save.names = TRUE', to save the ordered cartography.
# after that, any time you need to run this script, run it with 'ordering = TRUE and 'save.names = FALSE', not to overwrite the file which stores the cluster order:
ordering <- T    # If TRUE, order the clusters following the regimes listed in the 'orden' vector (set it to TRUE only after you manually inserted the names below).
save.names <- F  # if TRUE, also save the cluster names (i.e: the association between clusters and weather regimes); if FALSE, the cluster names are loaded from a file

as.pdf <- F # FALSE: save results as one .png file for each season/month, TRUE: save only one .pdf file with all seasons/months

composition <- "psl" # "psl" # choose which kind of composition you want to plot: 'simple' for monthly graphs, 'psl' for the regime anomalies for a fixed forecast month
forecast.month <- 12 # in case composition = 'psl', choose a forecast month to plot its composition

# if fields.name='forecast.name', set the subdir of 'workdir' where the weather regimes computed with a reanalysis are stored:
rean.dir <- "/scratch/Earth/ncortesi/RESILIENCE/Regimes/41_ERA-Interim_monthly_1981-2015_LOESS_filter"
    
# Associates the regimes to the four cluster:
cluster1.name <- "NAO+"  
cluster2.name <- "NAO-"
cluster4.name <- "Blocking"
cluster3.name <- "Atl.Ridge"

# choose an order to give to the cartograpy, from top to bottom:
orden <- c("NAO+","NAO-","Blocking","Atl.Ridge")

###################################################################################################################################################################

if(fields.name != rean.name && fields.name != forecast.name) stop("variable 'fields.name' is not properly set")
regime1.name <- orden[1]
regime2.name <- orden[2]
regime3.name <- orden[3]
regime4.name <- orden[4]
    
var.name <- c("sfcWind","tas")
var.name.full <- c("Wind Speed","Temperature")   # full name of the 'predictand' variable to put in the title of the graphs
var.unit <- c("m/s", "ºC")                       # unit of measure of var (for drawing color scales)
var.num.orig <- var.num  # loading _psl files, this value can change!
fields.name.orig <- fields.name
period.orig <- period
workdir.orig <- workdir
pdf.suffix <- ifelse(length(period)==1, my.period[period], "all_periods")

if(composition == "psl") {
    if(as.pdf && fields.name == forecast.name && composition == "psl") pdf(file=paste0(workdir,"/",fields.name,"_",pdf.suffix,"_forecast_month_",forecast.month,".pdf"),width=40,height=60)
    if(!as.pdf && fields.name == forecast.name && composition == "psl") png(filename=paste0(workdir,"/",fields.name,"_forecast_month_",forecast.month,"_psl",".png"),width=6000,height=2300)
    
    lead.months <- c(6:0,0)
    n.map <- 0
    plot.new()
    
    # Sheet title:
    par(fig=c(0, 1, 0.94, 0.98), new=TRUE)
    mtext(paste0(fields.name, " simulated Weather Regimes for ", month.name[forecast.month]," (",year.start,"-",year.end,")"), cex=5.5, font=2)
}


for(lead.month in lead.months){
#lead.month=0 # for the debug
    
if(as.pdf && fields.name == rean.name && composition == "simple") pdf(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",pdf.suffix,".pdf"),width=40, height=60)
if(as.pdf && fields.name == forecast.name && composition == "simple") pdf(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",pdf.suffix,"_leadmonth_",lead.month,".pdf"),width=40,height=60)
    
if(composition == 'psl') { period <- forecast.month - lead.month }

for(p in period){
    #p <- 1 # for the debug
    p.orig <- p

    # load regime data (for forecasts, it load only the data corresponding to the chosen start month p and lead month 'lead.month'::
    if(fields.name == rean.name || (fields.name == forecast.name && lead.month == 0 || n.map == 7)) {
        load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_","psl",".RData"))
        if(var.num != var.num.orig) var.num <- var.num.orig  # ripristinate original values of this script (necessary after loading regime data)
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        if(workdir != workdir.orig) workdir <- workdir.orig # ripristinate original values of this script

        load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_",var.name[var.num],".RData"))
    }
    
    if(fields.name == forecast.name){
        load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",lead.month,"_","psl",".RData"))  # load cluster time series and mean psl data
        #load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",lead.month,"_",var.name[var.num],".RData")) # load mean var data

        if(var.num != var.num.orig) var.num <- var.num.orig  # ripristinate original values of this script (necessary after loading regime data)
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        if(workdir != workdir.orig) workdir <- workdir.orig # ripristinate original values of this script

    }

    if(var.num != var.num.orig) var.num <- var.num.orig  # ripristinate original values of this script (necessary after loading regime data)
    if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
    if(p != p.orig) p <- p.orig
    
    if(fields.name == forecast.name){    
        # compute cluster persistence:
        my.cluster.vector <- as.vector(my.cluster.array[[p]])  # reduce it to a vector with the order: day1month1member1 , day2month1member1, ... , day1month2member1, day2month2member1, ,,,

        sequ1 <- sequ2 <- sequ3 <- sequ4 <- rep(0,10000)
        i1 <- i2 <- i3 <- i4 <- 1

        if(my.cluster.vector[1] != 1) i1 <- 0
        if(my.cluster.vector[1] == 1) sequ1[i1] <- sequ1[i1]+1
        if(my.cluster.vector[1] != 2) i2 <- 0
        if(my.cluster.vector[1] == 2) sequ2[i2] <- sequ2[i2]+1
        if(my.cluster.vector[1] != 3) i3 <- 0
        if(my.cluster.vector[1] == 3) sequ3[i3] <- sequ3[i3]+1
        if(my.cluster.vector[1] != 4) i4 <- 0
        if(my.cluster.vector[1] == 4) sequ4[i4] <- sequ4[i4]+1
        n.dd <- length(my.cluster.vector)
        for(d in 1:(n.dd-1)){
            if(my.cluster.vector[d] != 1 && my.cluster.vector[d+1] == 1)  i1 <- i1+1
            if(my.cluster.vector[d] == 1) sequ1[i1] <- sequ1[i1]+1
            
            if(my.cluster.vector[d] != 2 && my.cluster.vector[d+1] == 2)  i2 <- i2+1
            if(my.cluster.vector[d] == 2) sequ2[i2] <- sequ2[i2]+1
            
            if(my.cluster.vector[d] != 3 && my.cluster.vector[d+1] == 3)  i3 <- i3+1
            if(my.cluster.vector[d] == 3) sequ3[i3] <- sequ3[i3]+1
            
            if(my.cluster.vector[d] != 4 && my.cluster.vector[d+1] == 4)  i4 <- i4+1
            if(my.cluster.vector[d] == 4) sequ4[i4] <- sequ4[i4]+1
        }

        if(my.cluster.vector[n.dd] == 1) sequ1[i1] <- sequ1[i1]+1
        if(my.cluster.vector[n.dd] == 2) sequ2[i2] <- sequ2[i2]+1
        if(my.cluster.vector[n.dd] == 3) sequ3[i3] <- sequ3[i3]+1
        if(my.cluster.vector[n.dd] == 4) sequ4[i4] <- sequ4[i4]+1

        pers1 <- mean(sequ1[which(sequ1 != 0)])
        pers2 <- mean(sequ2[which(sequ2 != 0)])
        pers3 <- mean(sequ3[which(sequ3 != 0)])
        pers4 <- mean(sequ4[which(sequ4 != 0)])
        
        # compute correlations between simulated clusters and observed regime's anomalies:
        cluster1.sim <- pslwr1mean; cluster2.sim <- pslwr2mean; cluster3.sim <- pslwr3mean; cluster4.sim <- pslwr4mean
        lat.forecast <- lat; lon.forecast <- lon
        
        if((p + lead.month) > 12) { load.month <- p + lead.month - 12 } else { load.month <- p + lead.month }  # reanalysis forecast month to load
        load(file=paste0(rean.dir,"/",rean.name,"_",my.period[load.month],"_","psl",".RData")) # load reanalysis data, which overwrities the pslwrXmean variables
        load(paste0(rean.dir,"/",rean.name,"_", my.period[load.month],"_","ClusterNames",".RData")) # load also reanalysis regime names

        wr1y.obs <- wr1y;   wr2y.obs <- wr2y;   wr3y.obs <- wr3y;   wr4y.obs <- wr4y # observed frecuencies of the regimes
        
        regimes.obs <- c(cluster1.name, cluster2.name, cluster3.name, cluster4.name)
        
        if(length(unique(regimes.obs)) < 4) stop("Two or more names of the weather types in the reanalsyis input file are repeated!")

        if(identical(rev(lat),lat.forecast)) {lat.forecast <- rev(lat.forecast); print("Warning: forecast latitudes are in the opposite order than renalysis's")}
        if(!identical(lat, lat.forecast)) stop("forecast latitudes are different from reanalysis latitudes!")
        if(!identical(lon, lon.forecast)) stop("forecast longitude are different from reanalysis longitudes!")
        
        cluster.corr <- array(NA, c(4,4), dimnames=list(c("cluster1.sim","cluster2.sim","cluster3.sim","cluster4.sim"), regimes.obs))
        cluster.corr[1,1] <- cor(as.vector(cluster1.sim), as.vector(pslwr1mean))
        cluster.corr[1,2] <- cor(as.vector(cluster1.sim), as.vector(pslwr2mean))
        cluster.corr[1,3] <- cor(as.vector(cluster1.sim), as.vector(pslwr3mean))
        cluster.corr[1,4] <- cor(as.vector(cluster1.sim), as.vector(pslwr4mean))
        cluster.corr[2,1] <- cor(as.vector(cluster2.sim), as.vector(pslwr1mean))
        cluster.corr[2,2] <- cor(as.vector(cluster2.sim), as.vector(pslwr2mean))
        cluster.corr[2,3] <- cor(as.vector(cluster2.sim), as.vector(pslwr3mean))
        cluster.corr[2,4] <- cor(as.vector(cluster2.sim), as.vector(pslwr4mean))
        cluster.corr[3,1] <- cor(as.vector(cluster3.sim), as.vector(pslwr1mean))
        cluster.corr[3,2] <- cor(as.vector(cluster3.sim), as.vector(pslwr2mean))
        cluster.corr[3,3] <- cor(as.vector(cluster3.sim), as.vector(pslwr3mean))
        cluster.corr[3,4] <- cor(as.vector(cluster3.sim), as.vector(pslwr4mean))
        cluster.corr[4,1] <- cor(as.vector(cluster4.sim), as.vector(pslwr1mean))
        cluster.corr[4,2] <- cor(as.vector(cluster4.sim), as.vector(pslwr2mean))
        cluster.corr[4,3] <- cor(as.vector(cluster4.sim), as.vector(pslwr3mean))
        cluster.corr[4,4] <- cor(as.vector(cluster4.sim), as.vector(pslwr4mean))

        # associate each simulated cluster to one observed regime:
        max1 <- which(cluster.corr == max(cluster.corr), arr.ind=T)
        cluster.corr2 <- cluster.corr
        cluster.corr2[max1[1],] <- -999 # set this row to negative values so it won't be found as a maximum anymore
        cluster.corr2[,max1[2]] <- -999 # set this column to negative values so it won't be found as a maximum anymore
        max2 <- which(cluster.corr2 == max(cluster.corr2), arr.ind=T)
        cluster.corr3 <- cluster.corr2
        cluster.corr3[max2[1],] <- -999
        cluster.corr3[,max2[2]] <- -999 
        max3 <- which(cluster.corr3 == max(cluster.corr3), arr.ind=T)
        cluster.corr4 <- cluster.corr3
        cluster.corr4[max3[1],] <- -999
        cluster.corr4[,max3[2]] <- -999 
        max4 <- which(cluster.corr4 == max(cluster.corr4), arr.ind=T)
       
        seq.max1 <- c(max1[1],max2[1],max3[1],max4[1])
        seq.max2 <- c(max1[2],max2[2],max3[2],max4[2])

        cluster1.regime <- seq.max2[which(seq.max1 == 1)]
        cluster2.regime <- seq.max2[which(seq.max1 == 2)]
        cluster3.regime <- seq.max2[which(seq.max1 == 3)]
        cluster4.regime <- seq.max2[which(seq.max1 == 4)]
        
        cluster1.name <- regimes.obs[cluster1.regime]
        cluster2.name <- regimes.obs[cluster2.regime]
        cluster3.name <- regimes.obs[cluster3.regime]
        cluster4.name <- regimes.obs[cluster4.regime]

        spat.cor1 <- cluster.corr[1,seq.max2[which(seq.max1 == 1)]]
        spat.cor2 <- cluster.corr[2,seq.max2[which(seq.max1 == 2)]]
        spat.cor3 <- cluster.corr[3,seq.max2[which(seq.max1 == 3)]]
        spat.cor4 <- cluster.corr[4,seq.max2[which(seq.max1 == 4)]]

        # measure persistence for the reanalysis dataset:
        
        # compute cluster persistence:
        my.cluster.vector <- my.cluster[[load.month]][[1]]

        sequ1 <- sequ2 <- sequ3 <- sequ4 <- rep(0,10000)
        i1 <- i2 <- i3 <- i4 <- 1

        if(my.cluster.vector[1] != 1) i1 <- 0
        if(my.cluster.vector[1] == 1) sequ1[i1] <- sequ1[i1]+1
        if(my.cluster.vector[1] != 2) i2 <- 0
        if(my.cluster.vector[1] == 2) sequ2[i2] <- sequ2[i2]+1
        if(my.cluster.vector[1] != 3) i3 <- 0
        if(my.cluster.vector[1] == 3) sequ3[i3] <- sequ3[i3]+1
        if(my.cluster.vector[1] != 4) i4 <- 0
        if(my.cluster.vector[1] == 4) sequ4[i4] <- sequ4[i4]+1
        
        n.dd <- length(my.cluster.vector)
        for(d in 1:(n.dd-1)){
            if(my.cluster.vector[d] != 1 && my.cluster.vector[d+1] == 1)  i1 <- i1+1
            if(my.cluster.vector[d] == 1) sequ1[i1] <- sequ1[i1]+1
            
            if(my.cluster.vector[d] != 2 && my.cluster.vector[d+1] == 2)  i2 <- i2+1
            if(my.cluster.vector[d] == 2) sequ2[i2] <- sequ2[i2]+1
            
            if(my.cluster.vector[d] != 3 && my.cluster.vector[d+1] == 3)  i3 <- i3+1
            if(my.cluster.vector[d] == 3) sequ3[i3] <- sequ3[i3]+1
            
            if(my.cluster.vector[d] != 4 && my.cluster.vector[d+1] == 4)  i4 <- i4+1
            if(my.cluster.vector[d] == 4) sequ4[i4] <- sequ4[i4]+1
        }

        if(my.cluster.vector[n.dd] == 1) sequ1[i1] <- sequ1[i1]+1
        if(my.cluster.vector[n.dd] == 2) sequ2[i2] <- sequ2[i2]+1
        if(my.cluster.vector[n.dd] == 3) sequ3[i3] <- sequ3[i3]+1
        if(my.cluster.vector[n.dd] == 4) sequ4[i4] <- sequ4[i4]+1

        persObs1 <- mean(sequ1[which(sequ1 != 0)])
        persObs2 <- mean(sequ2[which(sequ2 != 0)])
        persObs3 <- mean(sequ3[which(sequ3 != 0)])
        persObs4 <- mean(sequ4[which(sequ4 != 0)])
        
        # insert here all the manual corrections to the regime assignation due to misasignment in the automatic selection:
        #if(p= && lead.month= ) clusterX.name=...
                
        if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        if(!identical(period.orig,period)) period <- period.orig
        if(workdir != workdir.orig) workdir <- workdir.orig # ripristinate original values of this script
        if(p.orig != p) p <- p.orig
        
        load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",lead.month,"_","psl",".RData")) # reload forecast cluster time series and mean psl data
        #load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",lead.month,"_ClusterData.RData")) # reload forecast cluster data (for my.cluster.array)

        if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        if(!identical(period.orig, period)) period <- period.orig
        if(p.orig != p) p <- p.orig
        if(identical(rev(lat),lat.forecast)) lat <- rev(lat) # ripristinate right lat order
        if(workdir != workdir.orig) workdir <- workdir.orig # ripristinate original values of this script

    } # close for on 'forecast.name'

    if(fields.name == rean.name){
        if(save.names){
            save(cluster1.name, cluster2.name, cluster3.name, cluster4.name, file=paste0(workdir,"/",fields.name,"_", my.period[p],"_","ClusterNames",".RData"))
          
        } else { # in this case, we load the cluster names from the file already saved, if regimes come from a reanalysis:
            load(paste0(workdir,"/",fields.name,"_", my.period[p],"_","ClusterNames",".RData"))
          
            if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
            if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        }
    }
    
    # assign to each cluster its regime:
    if(ordering == FALSE && fields.name == rean.name){
       cluster1 <- 1; cluster2 <- 2; cluster3 <- 3; cluster4 <- 4
    } else {
       cluster1 <- which(orden == cluster1.name)
       cluster2 <- which(orden == cluster2.name)
       cluster3 <- which(orden == cluster3.name)
       cluster4 <- which(orden == cluster4.name)
    }
    
    assign(paste0("map",cluster1), pslwr1mean)
    assign(paste0("map",cluster2), pslwr2mean)
    assign(paste0("map",cluster3), pslwr3mean)
    assign(paste0("map",cluster4), pslwr4mean)

    assign(paste0("fre",cluster1), wr1y)
    assign(paste0("fre",cluster2), wr2y)
    assign(paste0("fre",cluster3), wr3y)
    assign(paste0("fre",cluster4), wr4y)

    if(p == 100){
      assign(paste0("imp",cluster1), varwr1mean)
      assign(paste0("imp",cluster2), varwr2mean)
      assign(paste0("imp",cluster3), varwr3mean)
      assign(paste0("imp",cluster4), varwr4mean)

      assign(paste0("sig",cluster1), pvalue1)
      assign(paste0("sig",cluster2), pvalue2)
      assign(paste0("sig",cluster3), pvalue3)
      assign(paste0("sig",cluster4), pvalue4)
    }
    
    if(fields.name == forecast.name){    
       assign(paste0("freMax",cluster1), wr1yMax)
       assign(paste0("freMax",cluster2), wr2yMax)
       assign(paste0("freMax",cluster3), wr3yMax)
       assign(paste0("freMax",cluster4), wr4yMax)

       assign(paste0("freMin",cluster1), wr1yMin)
       assign(paste0("freMin",cluster2), wr2yMin)
       assign(paste0("freMin",cluster3), wr3yMin)
       assign(paste0("freMin",cluster4), wr4yMin)

       assign(paste0("spatial.cor",cluster1), spat.cor1)
       assign(paste0("spatial.cor",cluster2), spat.cor2)
       assign(paste0("spatial.cor",cluster3), spat.cor3)
       assign(paste0("spatial.cor",cluster4), spat.cor3)

       assign(paste0("persist",cluster1), pers1)
       assign(paste0("persist",cluster2), pers2)
       assign(paste0("persist",cluster3), pers3)
       assign(paste0("persist",cluster4), pers4)

       cluster1.obs <- which(orden == regimes.obs[1])
       cluster2.obs <- which(orden == regimes.obs[2])
       cluster3.obs <- which(orden == regimes.obs[3])
       cluster4.obs <- which(orden == regimes.obs[4])

       assign(paste0("freObs",cluster1.obs), wr1y.obs)
       assign(paste0("freObs",cluster2.obs), wr2y.obs)
       assign(paste0("freObs",cluster3.obs), wr3y.obs)
       assign(paste0("freObs",cluster4.obs), wr4y.obs)

       assign(paste0("persistObs",cluster1.obs), persObs1)
       assign(paste0("persistObs",cluster2.obs), persObs2)
       assign(paste0("persistObs",cluster3.obs), persObs3)
       assign(paste0("persistObs",cluster4.obs), persObs4)

    }
    
    # position of long values of Europe only (without the Atlantic Sea and America):
    #if(fields.name == "ERA-Interim") EU <- c(1:which(lon >= lon.max)[1], (length(lon)-30):length(lon))  # restrict area to continental europe only
    EU <- c(1:which(lon >= lon.max)[1], (which(lon >= 337)[1]:length(lon)))  # restrict area to continental europe only

    # breaks and colors of the geopotential fields:
    if(psl == "g500"){
        #my.brks <- c(-300,-199:200,300) # % Mean anomaly of a WR
        my.brks <- c(-300,seq(-200,200,10),300) # % Mean anomaly of a WR
        my.brks2 <- c(-300,seq(-200,200,10),300) # % Mean anomaly of a WR for the contour lines
        #my.cols <- colorRampPalette((brewer.pal(9,"PuBu")))(length(my.brks)-1)
        values.to.plot <- c(-200, -100, 0, 100, 200)  # values we want to show in the labels
    }

    if(psl == "psl"){
        my.brks <- c(seq(-19,-1,2),0,seq(1,19,2)) # % Mean anomaly of a WR
        #  my.brks <- c(seq(-19,-1,2),0,seq(1,19,2)) # % Mean anomaly of a WR

        my.brks2 <- my.brks #c(seq(-20,20,2)) # % Mean anomaly of a WR for the contour lines
        values.to.plot <- my.brks #c(-17,-15,-13,-11,-9,-7,-5,-3,-1,0,1,3,5,7,9,11,13,15,17)
    }

    my.cols <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks)-1)    # blue--white--red colors
    my.cols[floor(length(my.cols)/2)] <- my.cols[floor(length(my.cols)/2)+1] <- "white"
    
    # breaks and colors of the impact maps (valid both for Wind speed anomalies and Temperature anomalies):
    #my.brks.var <- c(-20,seq(-10,-3,1),seq(-2.9,2.9,0.1),seq(3,10,1),20) # % Mean anomaly of a WR
    #my.brks.var <- c(-20,-2,-1.5,-1,-0.5,-0.2,0.2,0.5,1,1.5,2,20) # % Mean anomaly of a WR
    #my.brks.var <- c(-20,seq(-3,3,0.5),20) # % Mean anomaly of a WR
    if(var.name[var.num] == "sfcWind") {
        my.brks.var <- seq(-3,3,0.5)
        values.to.plot2 <- c(-3,-2,-1,0,1,2,3)
    }
    if(var.name[var.num] == "tas") {
        my.brks.var <- seq(-5,5,1) 
        values.to.plot2 <- my.brks.var #c(-5,-3,-1,0,1,3,5)
    }
    
    #my.cols <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks)-1)  # blue--yellow-red colors
    my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--white--red colors
    #my.cols.var[floor(length(my.cols.var)/2)] <- my.cols.var[floor(length(my.cols.var)/2)+1] <- "white"

    # Visualize the composition with the 3 graphs for all the 4 regimes: its pressure fields, its impact on var and its frequency series:
    if(composition == "simple"){
        if(!as.pdf && fields.name==rean.name) png(filename=paste0(workdir,"/",fields.name,"_",my.period[p],"_",var.name[var.num],".png"),width=3000,height=3700)
        if(!as.pdf && fields.name==forecast.name) png(filename=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",lead.month,"_",var.name[var.num],".png"),width=3000,height=3700)
        
        plot.new()

        # Sheet title:
        par(fig=c(0, 1, 0.94, 0.98), new=TRUE)
        if(fields.name == forecast.name) {forecast.title <- paste0(" startdate and ",lead.month," forecast month ")} else {forecast.title <- ""}
        mtext(paste0(fields.name, " Weather Regimes for ", my.period[p], forecast.title," (",year.start,"-",year.end,")"), cex=5.5, font=2)
        
        # Centroid maps:
        map.xpos <- 0
        map.width <- 0.46
        par(fig=c(map.xpos + 0.003, map.xpos + map.width - 0.003, 0.745, 0.925), new=TRUE)
        PlotEquiMap2(rescale(map1,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map1), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, xlabel.dist=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, 0.51, 0.69), new=TRUE)
        PlotEquiMap2(rescale(map2,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map2), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, 0.275, 0.455), new=TRUE)
        PlotEquiMap2(rescale(map3,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map3), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, 0.04, 0.22), new=TRUE)
        PlotEquiMap2(rescale(map4,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map4), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")

        # Subtitle centroid maps:
        map.title.xpos <- 0.76
        map.title.width <- 0.2
        par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.728, 0.729), new=TRUE)
        mtext("year", cex=3)
        par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.494, 0.495), new=TRUE)
        mtext("year", cex=3)
        par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.260, 0.261), new=TRUE)
        mtext("year", cex=3)
        par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.026, 0.027), new=TRUE)
        mtext("year", cex=3)

        # Title Centroid Maps:
        title1.xpos <- 0.02
        title1.width <- 0.4
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.9305, 0.9355), new=TRUE)
        mtext(paste0(regime1.name,": ", psl.name, " Anomaly"), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.6955, 0.7005), new=TRUE)
        mtext(paste0(regime2.name,": ", psl.name, " Anomaly"), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.4605, 0.4655), new=TRUE)
        mtext(paste0(regime3.name,": ", psl.name, " Anomaly"), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.2255, 0.2305), new=TRUE)
        mtext(paste0(regime4.name,": ", psl.name, " Anomaly"), font=2, cex=4)
        
        # Impact maps:
        if(p == 100){
            impact.xpos <- 0.47
            impact.width <- 0.26    
            par(fig=c(impact.xpos, impact.xpos + impact.width, 0.745, 0.925), new=TRUE)
            PlotEquiMap2(rescale(imp1[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig1[,EU] < 0.05), cex.lab=1.5)
            par(fig=c(impact.xpos, impact.xpos + impact.width, 0.51, 0.69), new=TRUE)
            PlotEquiMap2(rescale(imp2[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig2[,EU] < 0.05), cex.lab=1.5)
            par(fig=c(impact.xpos, impact.xpos + impact.width, 0.275, 0.455), new=TRUE)
            PlotEquiMap2(rescale(imp3[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig3[,EU] < 0.05), cex.lab=1.5)
            par(fig=c(impact.xpos, impact.xpos + impact.width, 0.04, 0.22), new=TRUE)
            PlotEquiMap2(rescale(imp4[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig4[,EU] < 0.05), cex.lab=1.5)

            # Title impact maps:
            title2.xpos <- 0.42
            title2.width <- 0.35
            par(fig=c(title2.xpos, title2.xpos + title2.width, 0.935, 0.940), new=TRUE)
            mtext(paste0(regime1.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
            par(fig=c(title2.xpos, title2.xpos + title2.width, 0.700, 0.705), new=TRUE)
            mtext(paste0(regime2.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
            par(fig=c(title2.xpos, title2.xpos + title2.width, 0.465, 0.470), new=TRUE)
            mtext(paste0(regime3.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
            par(fig=c(title2.xpos, title2.xpos + title2.width, 0.230, 0.235), new=TRUE)
            mtext(paste0(regime4.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
        }
        
        # Frequency plots:
        barplot.xpos <- 0.75
        barplot.width <- 0.25
        freq.max=100

        if(fields.name == forecast.name){
            pos.years.present <- match(year.start:year.end, years)
            years.missing <- which(is.na(pos.years.present))
            fre1.NA <- fre2.NA <- fre3.NA <- fre4.NA <- freMax1.NA <- freMax2.NA <- freMax3.NA <- freMax4.NA <- freMin1.NA <- freMin2.NA <- freMin3.NA <- freMin4.NA <- c()

            k <- 0
            for(y in year.start:year.end) {
                if(y %in% (years.missing + year.start - 1)) {
                    fre1.NA <- c(fre1.NA,NA); fre2.NA <- c(fre2.NA,NA); fre3.NA <- c(fre3.NA,NA); fre4.NA <- c(fre4.NA,NA)
                    freMax1.NA <- c(freMax1.NA,NA); freMax2.NA <- c(freMax2.NA,NA); freMax3.NA <- c(freMax3.NA,NA); freMax4.NA <- c(freMax4.NA,NA)
                    freMin1.NA <- c(freMin1.NA,NA); freMin2.NA <- c(freMin2.NA,NA); freMin3.NA <- c(freMin3.NA,NA); freMin4.NA <- c(freMin4.NA,NA)
                    k=k+1
                } else {
                    fre1.NA <- c(fre1.NA,fre1[y - year.start + 1 - k]); fre2.NA <- c(fre2.NA,fre2[y - year.start + 1 - k])
                    fre3.NA <- c(fre3.NA,fre3[y - year.start + 1 - k]); fre4.NA <- c(fre4.NA,fre4[y - year.start + 1 - k])
                    freMax1.NA <- c(freMax1.NA,freMax1[y - year.start + 1 - k]); freMax2.NA <- c(freMax2.NA,freMax2[y - year.start + 1 - k])
                    freMax3.NA <- c(freMax3.NA,freMax3[y - year.start + 1 - k]); freMax4.NA <- c(freMax4.NA,freMax4[y - year.start + 1 - k])
                    freMin1.NA <- c(freMin1.NA,freMin1[y - year.start + 1 - k]); freMin2.NA <- c(freMin2.NA,freMin2[y - year.start + 1 - k])
                    freMin3.NA <- c(freMin3.NA,freMin3[y - year.start + 1 - k]); freMin4.NA <- c(freMin4.NA,freMin4[y - year.start + 1 - k])            
                }    
            }
        } else { fre1.NA <- fre1; fre2.NA <- fre2; fre3.NA <- fre3; fre4.NA <- fre4 }
        
        par(fig=c(barplot.xpos, barplot.xpos + barplot.width, 0.745, 0.915), new=TRUE)
        if(fields.name == rean.name) barplot.freq(100*fre1.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
        if(fields.name == forecast.name) barplot.freq.sim2(100*fre1.NA, 100*freMax1.NA, 100*freMin1.NA, 100*freObs1, year.start, year.end, cex.y=2, cex.x=2, freq.min=-2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0), col.line="gray20", cex.r=3, cex.mean=2, cex.obs=2)
        
        par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.510,0.680), new=TRUE)
        if(fields.name == rean.name) barplot.freq(100*fre2.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
        if(fields.name == forecast.name) barplot.freq.sim2(100*fre2.NA, 100*freMax2.NA, 100*freMin2.NA, 100*freObs2, year.start, year.end, cex.y=2, cex.x=2, freq.min=-2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0), col.line="gray20", cex.r=3, cex.mean=2, cex.obs=2)
        
        par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.275,0.445), new=TRUE)
        if(fields.name == rean.name) barplot.freq(100*fre3.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
        if(fields.name == forecast.name) barplot.freq.sim2(100*fre3.NA, 100*freMax3.NA, 100*freMin3.NA, 100*freObs3, year.start, year.end, cex.y=2, cex.x=2, freq.min=-2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0), col.line="gray20", cex.r=3, cex.mean=2, cex.obs=2)
        
        par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.040,0.210), new=TRUE)
        if(fields.name == rean.name) barplot.freq(100*fre4.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
        if(fields.name == forecast.name) barplot.freq.sim2(100*fre4.NA, 100*freMax4.NA, 100*freMin4.NA, 100*freObs4, year.start, year.end, cex.y=2, cex.x=2, freq.min=-2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0), col.line="gray20", cex.r=3, cex.mean=2, cex.obs=2)

        # Title Frequency maps:
        title3.xpos <- 0.75
        title3.width <-0.25
        par(fig=c(title3.xpos, title3.xpos + title3.width, 0.935, 0.940), new=TRUE)
        mtext(paste0(regime1.name, " Frequency"), font=2, cex=4) # paste0 doesn't work inside an expression!
        par(fig=c(title3.xpos, title3.xpos + title3.width, 0.700, 0.705), new=TRUE)
        mtext(paste0(regime2.name, " Frequency"), font=2, cex=4)
        par(fig=c(title3.xpos, title3.xpos + title3.width, 0.465, 0.470), new=TRUE)
        mtext(paste0(regime3.name, " Frequency"), font=2, cex=4)
        par(fig=c(title3.xpos, title3.xpos + title3.width, 0.230, 0.235), new=TRUE)
        mtext(paste0(regime4.name, " Frequency"), font=2, cex=4)

        # % on Frequency plots:
        symbol.xpos <- 0.735
        symbol.width <- 0.01
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.82, 0.83), new=TRUE)
        mtext("%", cex=3.3)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.59, 0.60), new=TRUE)
        mtext("%", cex=3.3)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.35, 0.36), new=TRUE)
        mtext("%", cex=3.3)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.12, 0.13), new=TRUE)
        mtext("%", cex=3.3)

        # mean frequency on Frequency plots:
        symbol.xpos <- 0.9
        symbol.width <- 0.1
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.908, 0.918), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre1.NA),1),"%"))),cex=4.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.673, 0.683), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre2.NA),1),"%"))),cex=4.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.44, 0.45), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre3.NA),1),"%"))),cex=4.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.203, 0.213), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre4.NA),1),"%"))),cex=4.5)

        # add corr between obs.time series and ensemble mean time series on Frequency plots:
        if(fields.name == forecast.name){
            symbol.xpos <- 0.76
            symbol.width <- 0.1
            par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.908, 0.918), new=TRUE)
            sp.cor1 <- round(cor(fre1.NA,freObs1, use="complete.obs"),2)
            mtext(paste0("r= ",sp.cor1), cex=4.5)
            par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.673, 0.683), new=TRUE)
            sp.cor2 <- round(cor(fre2.NA,freObs2, use="complete.obs"),2)
            mtext(paste0("r= ",sp.cor2), cex=4.5)
            par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.44, 0.45), new=TRUE)
            sp.cor3 <- round(cor(fre3.NA,freObs3, use="complete.obs"),2)
            mtext(paste0("r= ",sp.cor3), cex=4.5)
            par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.203, 0.213), new=TRUE)
            sp.cor4 <- round(cor(fre4.NA,freObs4, use="complete.obs"),2)
            mtext(paste0("r= ",sp.cor4), cex=4.5)
        }
        
        # Legend 1:
        legend1.xpos <- 0.10
        legend1.width <- 0.80
        legend1.cex <- 2
        my.subset <- match(values.to.plot, my.brks)    
        par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.719, 0.744), new=TRUE)  # syntax fig=c(xmin, xmax, ymin, ymax)
        ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
        if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
        par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.485, 0.508), new=TRUE)
        ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
        if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
        par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.250, 0.273), new=TRUE)
        ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
        if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
        par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.015, 0.038), new=TRUE)
        ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
        if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}

        # Legend 2:
        if(fields.name == rean.name){  
            legend2.xpos <- 0.48
            legend2.width <- 0.25
            legend2.cex <- 1.8
            my.subset2 <- match(values.to.plot2, my.brks.var)
            par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.719 + 0.001, 0.744), new=TRUE)
            ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
            mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)
            par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.485, 0.508), new=TRUE)
            ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
            mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
            par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.250, 0.273), new=TRUE)
            ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
            mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
            par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.015, 0.038), new=TRUE)
            ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
            mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
        }

        if(!as.pdf) dev.off() # for saving 4 png

    } # close if on: composition == 'simple'

    
    # Visualize the composition with the regime anomalies for a selected forecasted month:
    if(composition == "psl"){
        
        # Centroid maps:
        n.map <- n.map + 1  # starts from 0
        map.xpos <- 0.04 + map.width * (n.map - 1)
        map.width <- 0.12
        map.ypos <- 0.08
        map.height <- 0.19
        map.ysep <- 0.015
        
        par(fig=c(map.xpos, map.xpos + map.width, map.ypos + 3*map.height + 3*map.ysep, map.ypos + 4*map.height + 3*map.ysep), new=TRUE)
        PlotEquiMap2(rescale(map1,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map1), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, xlabel.dist=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, map.ypos + 2*map.height + 2*map.ysep, map.ypos + 3*map.height + 2*map.ysep), new=TRUE)
        PlotEquiMap2(rescale(map2,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map2), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, map.ypos + map.height + map.ysep, map.ypos + 2*map.height + map.ysep), new=TRUE)
        PlotEquiMap2(rescale(map3,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map3), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
        par(fig=c(map.xpos, map.xpos + map.width, map.ypos, map.ypos + map.height), new=TRUE)
        PlotEquiMap2(rescale(map4,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map4), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")

        # Sheet subtitles:
        par(fig=c(map.xpos, map.xpos + map.width, 0.86, 0.90), new=TRUE)
        mtext(paste0(my.month.short[p], " -> ", my.month.short[forecast.month]), cex=5.5, font=2)

        # Regime's names:
        title1.xpos <- 0
        title1.width <- 0.04
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.8305, 0.8355), new=TRUE)
        mtext(paste0(regime1.name), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.5955, 0.6005), new=TRUE)
        mtext(paste0(regime2.name), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.3805, 0.3955), new=TRUE)
        mtext(paste0(regime3.name), font=2, cex=4)
        par(fig=c(title1.xpos, title1.xpos + title1.width, 0.1655, 0.1705), new=TRUE)
        mtext(paste0(regime4.name), font=2, cex=4)

        # Color legend:
        legend1.xpos <- 0.10
        legend1.width <- 0.80
        legend1.cex <- 3
       
        par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0, 0.06), new=TRUE)  # syntax fig=c(xmin, xmax, ymin, ymax)
        ColorBar2(brks=my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, my.ticks=-0.5+1:21, my.labels=my.brks)

    } # close if on composition == 'psl'
    
    # fre1, fre2, etc. already refer to the regimes listed in the 'orden' vector:
    if(fields.name == forecast.name && composition == 'simple') save(orden, fre1.NA, fre2.NA, fre3.NA, fre4.NA, freObs1, freObs2, freObs3, freObs4, sp.cor1, sp.cor2, sp.cor3, sp.cor4, persist1, persist2, persist3, persist4, persistObs1, persistObs2, persistObs3, persistObs4, spatial.cor1, spatial.cor2, spatial.cor3, spatial.cor4, file=paste0(workdir,"/",fields.name,"_", my.period[p],"_leadmonth_",lead.month,"_","ClusterNames",".RData"))

} # close 'p' on 'period'

if(as.pdf) dev.off() # for saving a single pdf with all months/seasons

} # close 'lead.month' on 'lead.months'

if(composition == "psl") dev.off()








# Summary graphs:
if(fields.name == forecast.name && p == 100){
   # array storing correlations in the format: [startdate, leadmonth, regime]
   array.cor <- array.sp.cor <- array.freq <- array.diff.freq <- array.rpss <- array.pers <- array.diff.pers <- array(NA,c(12,7,4)) 
    
   for(p in 1:12){
        p.orig <- p

        for(l in 0:6){
        
            load(file=paste0(workdir,"/",fields.name,"_",my.period[p],"_leadmonth_",l,"_","ClusterNames",".RData"))  # load cluster names and summarized data

            if(var.num != var.num.orig) var.num <- var.num.orig  # ripristinate original values of this script (necessary after loading regime data)
            if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
            if(p != p.orig) p <- p.orig

            array.sp.cor[p,1+l, 1] <- spatial.cor1  # associates NAO+ to the first triangle (at left)
            array.sp.cor[p,1+l, 3] <- spatial.cor2  # associates NAO- to the third triangle (at right)
            array.sp.cor[p,1+l, 4] <- spatial.cor3  # associates Blocking to the fourth triangle (top one)
            array.sp.cor[p,1+l, 2] <- spatial.cor4  # associates Atl.Ridge to the second triangle (bottom one)
            
            array.cor[p,1+l, 1] <- sp.cor1  # associates NAO+ to the first triangle (at left)
            array.cor[p,1+l, 3] <- sp.cor2  # associates NAO- to the third triangle (at right)
            array.cor[p,1+l, 4] <- sp.cor3  # associates Blocking to the fourth triangle (top one)
            array.cor[p,1+l, 2] <- sp.cor4  # associates Atl.Ridge to the second triangle (bottom one)

            array.freq[p,1+l, 1] <- 100*(mean(fre1.NA))  # NAO+
            array.freq[p,1+l, 3] <- 100*(mean(fre2.NA))  # NAO-
            array.freq[p,1+l, 4] <- 100*(mean(fre3.NA))  # Blocking
            array.freq[p,1+l, 2] <- 100*(mean(fre4.NA))  # Atl.Ridge
            
            array.diff.freq[p,1+l, 1] <- 100*(mean(fre1.NA) - mean(freObs1))  # NAO+
            array.diff.freq[p,1+l, 3] <- 100*(mean(fre2.NA) - mean(freObs2))  # NAO-
            array.diff.freq[p,1+l, 4] <- 100*(mean(fre3.NA) - mean(freObs3))  # Blocking
            array.diff.freq[p,1+l, 2] <- 100*(mean(fre4.NA) - mean(freObs4))  # Atl.Ridge

            array.pers[p,1+l, 1] <- persist1  # NAO+
            array.pers[p,1+l, 3] <- persist2  # NAO-
            array.pers[p,1+l, 4] <- persist3  # Blocking
            array.pers[p,1+l, 2] <- persist4  # Atl.Ridge

            array.diff.pers[p,1+l, 1] <- persist1 - persistObs1  # NAO+
            array.diff.pers[p,1+l, 3] <- persist2 - persistObs2 # NAO-
            array.diff.pers[p,1+l, 4] <- persist3 - persistObs3  # Blocking
            array.diff.pers[p,1+l, 2] <- persist4 - persistObs4  # Atl.Ridge
            
            #array.rpss[p,1+l, 1] <-   # NAO+
            #array.rpss[p,1+l, 3] <-   # NAO-
            #array.rpss[p,1+l, 4] <-   # Blocking
            #array.rpss[p,1+l, 2] <-   # Atl.Ridge
        }
   }


   # Spatial Corr summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_sp_corr.png"), width=550, height=400)
   
   # create an array similar to array.cor but with colors instead of corr.values:
   sp.corr.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
   my.seq <- c(-1,0,0.4,0.5,0.6,0.7,0.8,0.9,1)
    
   array.sp.cor.colors <- array(sp.corr.cols[8],c(12,7,4))
   array.sp.cor.colors[array.sp.cor < my.seq[8]] <- sp.corr.cols[7]
   array.sp.cor.colors[array.sp.cor < my.seq[7]] <- sp.corr.cols[6]
   array.sp.cor.colors[array.sp.cor < my.seq[6]] <- sp.corr.cols[5]
   array.sp.cor.colors[array.sp.cor < my.seq[5]] <- sp.corr.cols[4]
   array.sp.cor.colors[array.sp.cor < my.seq[4]] <- sp.corr.cols[3]
   array.sp.cor.colors[array.sp.cor < my.seq[3]] <- sp.corr.cols[2]
   array.sp.cor.colors[array.sp.cor < my.seq[2]] <- sp.corr.cols[1]

   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("Spatial correlation between S4 and ERA-Interim frequencies", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.sp.cor.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.sp.cor.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.sp.cor.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.sp.cor.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = my.seq, cols = sp.corr.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(my.seq), my.labels=my.seq)
   dev.off()


    
   # Corr summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_corr.png"), width=550, height=400)
   
   # create an array similar to array.cor but with colors instead of corr.values:
   corr.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
    
   array.cor.colors <- array(corr.cols[8],c(12,7,4))
   array.cor.colors[array.cor < 0.75] <- corr.cols[7]
   array.cor.colors[array.cor < 0.5] <- corr.cols[6]
   array.cor.colors[array.cor < 0.25] <- corr.cols[5]
   array.cor.colors[array.cor < 0] <- corr.cols[4]
   array.cor.colors[array.cor < -0.25] <- corr.cols[3]
   array.cor.colors[array.cor < -0.5] <- corr.cols[2]
   array.cor.colors[array.cor < -0.75] <- corr.cols[1]

   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("Correlation between S4 and ERA-Interim frequencies", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.cor.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.cor.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.cor.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.cor.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = seq(-1,1,0.25), cols = corr.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(seq(-1,1,0.25)), my.labels=seq(-1,1,0.25))
   dev.off()


   
   # Freq. summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_freq.png"), width=550, height=400)
   
   # create an array similar to array.diff.freq but with colors instead of frequencies:
   freq.cols <- rev(c('#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4'))
   my.seq <- c(NA,20,22,24,26,28,30,32,NA)
       
   array.freq.colors <- array(freq.cols[8],c(12,7,4))
   array.freq.colors[array.freq < my.seq[[8]]] <- freq.cols[7]
   array.freq.colors[array.freq < my.seq[[7]]] <- freq.cols[6]
   array.freq.colors[array.freq < my.seq[[6]]] <- freq.cols[5]
   array.freq.colors[array.freq < my.seq[[5]]] <- freq.cols[4]
   array.freq.colors[array.freq < my.seq[[4]]] <- freq.cols[3]
   array.freq.colors[array.freq < my.seq[[3]]] <- freq.cols[2]
   array.freq.colors[array.freq < my.seq[[2]]] <- freq.cols[1]
 
   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("Mean S4 frequency (%)", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.freq.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.freq.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.freq.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.freq.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = my.seq, cols = freq.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(my.seq), my.labels=my.seq)
   dev.off()


   
   # Delta freq. summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_diff_freq.png"), width=550, height=400)
   
   # create an array similar to array.diff.freq but with colors instead of frequencies:
   diff.freq.cols <- rev(c('#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4'))

   array.diff.freq.colors <- array(diff.freq.cols[8],c(12,7,4))
   array.diff.freq.colors[array.diff.freq < 10] <- diff.freq.cols[7]
   array.diff.freq.colors[array.diff.freq < 5] <- diff.freq.cols[6]
   array.diff.freq.colors[array.diff.freq < 2] <- diff.freq.cols[5]
   array.diff.freq.colors[array.diff.freq < 0] <- diff.freq.cols[4]
   array.diff.freq.colors[array.diff.freq < -2] <- diff.freq.cols[3]
   array.diff.freq.colors[array.diff.freq < -5] <- diff.freq.cols[2]
   array.diff.freq.colors[array.diff.freq < -10] <- diff.freq.cols[1]
 
   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("Frequency difference (%) between S4 and ERA-Interim", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.diff.freq.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.diff.freq.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.diff.freq.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.diff.freq.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = c(-20,-10,-5,-2,0,2,5,10,20), cols = diff.freq.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(c(-20,-10,-5,-2,0,2,5,10,20)), my.labels=c(-20,-10,-5,-2,0,2,5,10,20))
   dev.off()

   
   # Persistence summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_pers.png"), width=550, height=400)
   
   # create an array similar to array.pers but with colors instead of frequencies:
   pers.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
   my.seq <- c(NA, 3.25, 3.5, 3.75, 4, 4.25, 4.5, 4.75, NA)
               
   array.pers.colors <- array(pers.cols[8],c(12,7,4))
   array.pers.colors[array.pers < my.seq[8]] <- pers.cols[7]
   array.pers.colors[array.pers < my.seq[7]] <- pers.cols[6]
   array.pers.colors[array.pers < my.seq[6]] <- pers.cols[5]
   array.pers.colors[array.pers < my.seq[5]] <- pers.cols[4]
   array.pers.colors[array.pers < my.seq[4]] <- pers.cols[3]
   array.pers.colors[array.pers < my.seq[3]] <- pers.cols[2]
   array.pers.colors[array.pers < my.seq[2]] <- pers.cols[1]
 
   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("S4 Regime persistence (in days/month)", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.pers.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.pers.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.pers.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.pers.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = my.seq, cols = pers.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(my.seq), my.labels=my.seq)
   dev.off()


    
   # Delta persistence summary:
   png(filename=paste0(workdir,"/",forecast.name,"_summary_diff_pers.png"), width=550, height=400)
   
   # create an array similar to array.pers but with colors instead of frequencies:
   diff.pers.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
   my.seq <- c(NA, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, NA)
               
   array.diff.pers.colors <- array(diff.pers.cols[8],c(12,7,4))
   array.diff.pers.colors[array.diff.pers < my.seq[8]] <- diff.pers.cols[7]
   array.diff.pers.colors[array.diff.pers < my.seq[7]] <- diff.pers.cols[6]
   array.diff.pers.colors[array.diff.pers < my.seq[6]] <- diff.pers.cols[5]
   array.diff.pers.colors[array.diff.pers < my.seq[5]] <- diff.pers.cols[4]
   array.diff.pers.colors[array.diff.pers < my.seq[4]] <- diff.pers.cols[3]
   array.diff.pers.colors[array.diff.pers < my.seq[3]] <- diff.pers.cols[2]
   array.diff.pers.colors[array.diff.pers < my.seq[2]] <- diff.pers.cols[1]
 
   par(mar=c(5,4,4,4.5))
   plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   title("Diff. between S4 and ERA-Interim regime persistence (in days/month)", cex=1.5)
   mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   for(p in 1:12){
        for(l in 0:6){
            polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.diff.pers.colors[p,1+l,1])  # first triangle
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.diff.pers.colors[p,1+l,2])
            polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.diff.pers.colors[p,1+l,3])
            polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.diff.pers.colors[p,1+l,4])
        }
   }

   par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ColorBar2(brks = my.seq, cols = diff.pers.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(my.seq), my.labels=my.seq)
   dev.off()

   ## # FairRPSS summary:
   ## png(filename=paste0(workdir,"/",forecast.name,"_summary_rpss.png"), width=550, height=400)
   
   ## # create an array similar to array.diff.freq but with colors instead of frequencies:
   ## freq.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

   ## array.freq.colors <- array(freq.cols[8],c(12,7,4))
   ## array.freq.colors[array.diff.freq < 10] <- freq.cols[7]
   ## array.freq.colors[array.diff.freq < 5] <- freq.cols[6]
   ## array.freq.colors[array.diff.freq < 2] <- freq.cols[5]
   ## array.freq.colors[array.diff.freq < 0] <- freq.cols[4]
   ## array.freq.colors[array.diff.freq < -2] <- freq.cols[3]
   ## array.freq.colors[array.diff.freq < -5] <- freq.cols[2]
   ## array.freq.colors[array.diff.freq < -10] <- freq.cols[1]
 
   ## par(mar=c(5,4,4,4.5))
   ## plot(1,1, type="n", xaxt="n", yaxt="n",ylab="Forecast time", xlim=c(1,12.04), ylim=c(-0.23,6.2), ann=F)
   ## title("Frequency difference (%) between S4 and ERA-Interim", cex=1.5)
   ## mtext(side = 1, text = "Startdate", line = 4, cex=1.5)
   ## mtext(side = 2, text = "Forecast time", line = 2.5, cex=1.5)
   ## axis(1, at=seq(1,12), las=2, labels=my.month.short, cex.axis=1.5)
   ## axis(2, at=seq(0,6), las=2, cex.axis=1.5)

   ## for(p in 1:12){
   ##      for(l in 0:6){
   ##          polygon(c(0.5+p-1,0.5+p-1,1+p-1),c(-0.5+l,0.5+l,0+l), col=array.freq.colors[p,1+l,1])  # first triangle
   ##          polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(-0.5+l,0+l,-0.5+l), col=array.freq.colors[p,1+l,2])
   ##          polygon(c(1+p-1,1.5+p-1,1.5+p-1),c(l,0.5+l,-0.5+l), col=array.freq.colors[p,1+l,3])
   ##          polygon(c(0.5+p-1,1+p-1,1.5+p-1),c(0.5+l,0+l,0.5+l), col=array.freq.colors[p,1+l,4])
   ##      }
   ## }

   ## par(fig=c(0.875, 1, 0.14, 0.89), new=TRUE)
   ## ColorBar2(brks = c(-20,-10,-5,-2,0,2,5,10,20), cols = freq.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(c(-20,-10,-5,-2,0,2,5,10,20)), my.labels=c(-20,-10,-5,-2,0,2,5,10,20))
   ## dev.off()

}







# impact map of the stronger WR:
if(fields.name == rean.name && p == 100){
    
   var.num <- 1  # choose a variable (1:sfcWind, 2:tas)
   
   png(filename=paste0(workdir,"/",rean.name,"_",var.name[var.num],"_most_influent.png"), width=500, height=600)
    
   plot.new()    
   #par(mfrow=c(4,3))
   col.regimes <- c("indianred1","cyan","khaki","lightpink")
    
   for(p in 13:16){  # or 1:12 for monthly maps
        load(file=paste0(rean.dir,"/",rean.name,"_",var.name[var.num],"_",my.period[p],"_psl.RData"))
        load(paste0(rean.dir,"/",rean.name,"_ClusterNames.RData")) # they should not depend on var.name!!!

        # position of long values of Europe only (without the Atlantic Sea and America):
        #if(fields.name == "ERA-Interim") EU <- c(1:which(lon >= lon.max)[1], (length(lon)-30):length(lon))  # restrict area to continental europe only
        lon.max = 45
        EU <- c(1:which(lon >= lon.max)[1], (which(lon >= 337)[1]:length(lon)))  # restrict area to continental europe only

        
        cluster1 <- which(orden == cluster1.name.period[p]) # in future it will be == cluster1.name
        cluster2 <- which(orden == cluster2.name.period[p])
        cluster3 <- which(orden == cluster3.name.period[p])
        cluster4 <- which(orden == cluster4.name.period[p])

        assign(paste0("imp",cluster1), varPeriodAnom1mean)
        assign(paste0("imp",cluster2), varPeriodAnom2mean)
        assign(paste0("imp",cluster3), varPeriodAnom3mean)
        assign(paste0("imp",cluster4), varPeriodAnom4mean)
        
        imp.all <- imp1
        for(i in 1:dim(imp1)[1]){
            for(j in 1:dim(imp1)[2]){
                if(abs(imp1[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 1.5
                if(abs(imp2[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 2.5
                if(abs(imp3[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 3.5
                if(abs(imp4[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 4.5
            }
        }

        if(p<=3) yMod <- 0.7
        if(p>=4 && p<=6) yMod <- 0.5
        if(p>=7 && p<=9) yMod <- 0.3
        if(p>=10) yMod <- 0.1
        if(p==13 || p==14) yMod <- 0.5
        if(p==15 || p==16) yMod <- 0.1
        
        if(p==1 || p==4 || p==7 || p==10) xMod <- 0.05
        if(p==2 || p==5 || p==8 || p==11) xMod <- 0.35
        if(p==3 || p==6 || p==9 || p==12) xMod <- 0.65
        if(p==13 || p==15) xMod <- 0.05
        if(p==14 || p==16) xMod <- 0.50
        
        # impact map:
        if(p <= 12) par(fig=c(xMod, xMod + 0.3, yMod, yMod + 0.17), new=TRUE)
        if(p > 12) par(fig=c(xMod, xMod + 0.45, yMod, yMod + 0.38), new=TRUE)
        PlotEquiMap(imp.all[,EU], lon[EU], lat, filled.continents = FALSE, brks=1:5, cols=col.regimes, axelab=F, drawleg=F)
        
        # title map:
        if(p <= 12) par(fig=c(xMod, xMod + 0.3, yMod + 0.162, yMod + 0.172), new=TRUE)
        if(p > 12) par(fig=c(xMod + 0.07, xMod + 0.07 + 0.3, yMod +0.21 + 0.162, yMod +0.21 + 0.172), new=TRUE)
        mtext(my.period[p], font=2, cex=.9)
        
    } # close 'p' on 'period'
    
    par(fig=c(0.1,0.9, 0, 0.12), new=TRUE)  
    ColorBar2(1:5, cols=col.regimes, vert=FALSE, my.ticks=1:4, draw.ticks=FALSE, my.labels=orden)
    
    par(fig=c(0.1,0.9, 0.9, 0.95), new=TRUE)
    mtext(paste0("Most influent WR on ",var.name[var.num]), font=2, cex=1.5)
    
    dev.off()    
}  
    

















