  
# Created:  6/2016
# Author: Nicola Cortesi
# Aim: Compute weather regimes from a reanalysis at monthly or seasonal scale with the k-means algorithm applied to a circulation variable 'psl'
# and visualize their anomalies, interannual frequencies and impact on a target variable 'var' (e.g: wind speed or temperature)
#
# I/O: input daily psl variable (SLP, g250, g500, sfcWind, etc) and daily or 6-hourly impact variable (sfcwind, prec, temp, etc)
#      Input dataset must be in a format compatible with Load() function of s2dverification; output data (.RData) and figures (.png) are created in the 'workdir' folder
#
# Assumption: none
#
# Branch: weather_regimes
#
# Note: if it gives the error "invalid multibyte character", the script got corrupted. Open a new script and copy the old script into the new one.

rm(list=ls())
gc()

###############################################################################################
#                        Required Packages and Functions                                      #
###############################################################################################

library(s2dverification)  # for the function Load() and InsertDim()
library(abind) # for function abind()
library(Kendall) # for the MannKendall test
library(RColorBrewer) # for function brewer.pal()
library(reshape2) # for functions acast() and melt(). After each update of s2dverification, it's better to install this package again because sometimes it gets broken.
library(NbClust) # for the NbClust() and Cluster() functions used in the sensitivity test of the opimal number of clusters
library(trend) # for sens.slope() function
library(future) # for availableCores() function
library(plotrix) # for addtable2plot() function
library(multiApply) # for Apply() function

source('/esarchive/scratch/ncortesi/scripts/Rfunctions.R') ## Load external R functions
source('/esarchive/scratch/ncortesi/ESS/general/hatching.R') # for hatching() function
fig2catalog.dir <- '/esarchive/scratch/ncortesi/scripts' ## Directory where the fig2catalog.sh script is located

###############################################################################################
#                                      Header                                                 #
###############################################################################################

# The more important variables are 'year.end', 'period', 'area' and 'report.type'.
# The first two define the year and the month you want to create the data and the images for the report,
# (while variable 'year.start' below is always the year 1981). Variable 'area' set the spatial domain
# and 'report.type' the type of report (first, anexo or second).
# If you run this script from the terminal, you can specify these four variables
# as optional arguments, that overwrite the values set in the script. E.g:
#
# Rscript /shared/earth/Operational/EDPR/weather_regimes_EDPR_USA.R 2017 3 Western_USA first
#
# it will create the images of the first report for March 2017 in Western USA and place them inside the ./Western_USA/2017_March subdir,
# along with three .RData files that store the image values and the daily time series of the four clusters.

## Root EDPR repository where all output files will be stored in subdirectories. It also must store the 'fig2catalog.sh' shell file to change figures to the catalogue format
##rootdir <- "/shared/earth/Operational/EDPR/USA"
##rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor"
rootdir <- "/esarchive/scratch/ncortesi/Regimes/89_optimal_number_of_regimes_for_month"

## only year.end varies because all reports start from 1981
year.start <- 1981
year.end <- 2016

## Study period. 1-12: Jan-Dec; 13-16: Winter-Spring-Summer-Autumn ; 17: year 18: DJFMA [bypassed by the external arguments]
period <- 13 #1:12 ##1:5 ##c(2,1,3:5) ##1:9 ##1:12 ##c(13, 1:12)

## Choose a reanalysis dataset for the cluster variable (the same name will appear in the output figures):
rean.name <- "JRA-55" ##"ERA-Interim" ##"JRA-55" ## "NCEP"

## Select a spatial domain for the clustering (see full list in 'Derived variables' section):   [also set by the external arguments]
area <- "EU" ##"EU_CF" ## "Oliver" ##"EU_wind"  ## "Western_USA", "Central_USA", "Eastern_USA", "Small", "Casola", "Oliver", ... 

## Impact maps:
subdaily <- FALSE          # if TRUE, var data loaded is 6-hourly instead of daily            
var.num <- 1  # Choose a 'predictand' variable to study the impact of the regimes on it.    
              # 1: sfcWind 2: tas 3: prlr 4: slp 5: CF iec 1 6: CF iec 2 7: CF iec 3

report.type <- "none"   # "first"  ## If 'none', every analysis is done (clustering + full visualization, as for EDPR Europe report).
                                   ## if 'first', create the first report for EDPR USA. If "anexo", create the anexo for EDPR USA.
                                   ## (but you need to have already created the first report). If 'second', create the final report for EDPR USA
                                   ## (but you also need to have already created the first report and to have ERA-Interim 'var' data for the last year and month)
                                   ## It will bypass the values of the variables 'two.rean', 'new.classif' and 'impact last' set below.

two.rean <- FALSE  ## Choose an optional second reanalysis dataset only to draw the impact maps (the same name will appear in the output figures): [also set by report.type]
                  ## if FALSE, only one reanalysis is used for all maps ('rean.name' set above) and impact maps will be based from 'rean.impact.name' below instead:
rean.impact.name <- "ERA-Interim" ##"JRA-55" ## "NCEP" [also set by report.type]
new.classif <- FALSE ## If TRUE, classify WRs from scratch; if FALSE, use existing WR classification (_psl.RData and _ClusterData.RData files) [also set by report.type]
impact.last <- FALSE ## if TRUE, also generate impact figure referred to data of the last year ('year.end'), both var data and psl data. [also set by report.type]
figures.last <- TRUE ## if FALSE, it won't generate ANY figure related to the data of the last year

stations <- FALSE  ## if TRUE, load var from an observational dataset instead from a reanalysis

## Choose a variable to cluster from reanalysis 'rean.name', from: 'psl', 'sfcWind', 'g250" o 'g500"
psl <- "psl" 

## Choose a metodology to classify the weather regimes:
lat.weighting <- TRUE      # set it to true to weight psl data for the cosine of the latitude before applying the cluster analysis

detrend.psl <- FALSE       # if TRUE, remove the long-term linear trend to input psl data before any other analysis (recommended)
detrend.var <- FALSE       # if TRUE, remove the long-term linear trend to impact var

LOESS <- TRUE              # To apply the LOESS filter or not to the climatology
my.span <- 0.15            # smooth value for the LOESS filter. In case of a reanalysis, we are loading all yearly data and repeating it thrice to avoid bias at the borders.

sequences <- FALSE         # set it to TRUE if you want to select only days beloning to sequences of at least 5 consecutive days belonging to the same regime.

## PCA parameters:
PCA <- FALSE               # set it to TRUE if you want to apply the PCA before the k-means cluster analysis, FALSE otherwise
variance.explained <- 0.99 # the user can set here the minimum % of variance explained by the PCs (typically 0.8 which is equal to 80%)

## Clustering parameters:
n.cl <- 4           ## Choose the number of clusters to set in the cluster analysis (the weather regimes):
my.iter.max <- 200  ## recommended: 100+
my.nstart <- 50     ## recommended: 25+

## number of cpus to employ:
ncores <- max(1, availableCores()-1)

## save all the txt files for EDPR:
save.txt <- TRUE

## order the clusters for their frequency of occurrence during last year (TRUE) or for their average frequency during all period (FALSE). Default: FALSE
order4lastyear <- FALSE


################################### Graphical parameters ######################################################

box.cluster <- TRUE ## if TRUE, add a rectangle with the spatial domain of the clustering to all psl regime plots
box.impact <- TRUE ## if TRUE, add the same box also to the impact figures
box.col <- "gray50" ## set the color of the rectangle for both box.cluster and box.impact
wind.farms <- TRUE  ## if TRUE, add points with location of EDPR wind farms over each map
wind.color <- "Darkgreen" ## color of the wind farm points. 
farms.style <- 0    ## symbol to plot wind farm points. 0: square, 4: cross, 3: +, 1: circle, 2: triangle, 8:*
farms.size <- 6     ## symbol size of farms. If square, best size is 3

end.map <- 0.45 ##0.3 ## width of the first column of impact figures to show in the last year composition, from 0 (left) to 1 (right)
end.map.clim <- end.map - 0.09 ## same as above but for the climatology composition

rayas <- TRUE ## If TRUE, all impact maps show significant points with diagonal lines instead of black points
pval <- 0.01 ## p-value level to show black points or diagonal lines

## psl maps:
blue2red <- FALSE ## If TRUE, all psl maps goes from blue to red. If false, psl maps goes from red to blue (as for last EDPR format)

my.countries <- FALSE ## add the borders of the countries to all maps
mean.freq <- TRUE   # if TRUE, it also add the mean frequency value over each frequency plot of the regime anomalies maps for all years

# cluster colors to visualize in the strip above the anomaly maps for a single month and year:
cl.col <- c("Firebrick1", "Dodgerblue1", "White", "Darkgoldenrod1", "mediumorchid2", "gray", "darkolivegreen3", "cyan", "brown", "pink", rep("white",100))
my.contours.zero = TRUE  ## to visualize a black line in correspondence of zero values

###############################################################################################
#                                   Derived variables                                         #
###############################################################################################

## in case the script is run with 4 external arguments, the first argument represents the end year, the 2nd the month, the 3rd the study area and the 4th the report type:
script.arg <- commandArgs(TRUE)

year <- as.integer(commandArgs(TRUE))
                   
if(length(script.arg) >= 2){ year.end <- as.integer(script.arg[1]); period <- as.integer(script.arg[2]); area <- script.arg[3]; report.type <- script.arg[4] } 

## To visualize the degree symbol in R, you have to insert "Â" before, in case you run the job from terminal.
## Problem is, from the R interpreter, no additional symbol is required, so if you generate a report from the R interpreter, the symbol "Â" will appear before the degrees.
## The only solution is to generate the report FROM TERMINAL ONLY, or to remove "Â" if you want to create it from the interpreter.
if(length(script.arg) >= 2) deg <- "Â°" else  deg <- "°"


## format data using aperm + array, which is much faster than using melt + acast:
fast.reshape <- TRUE # It is safe to do it, so keep this variable set to TRUE

if(subdaily) rean.freq <- '6hourly/$VAR_NAME$' else rean.freq <- '$STORE_FREQ$_mean/$VAR_NAME$_f6h'
    
## if(rean.name == "JRA-55") rean <- '/esnas/recon/jma/jra55/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
## if(rean.name == "NCEP") rean <- '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
## if(rean.name == "ERA-Interim") rean <- '/esnas/recon/ecmwf/erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc' 

## if(rean.impact.name == "JRA-55") rean.impact <- '/esnas/recon/jma/jra55/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
## if(rean.impact.name == "NCEP") rean.impact <- '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
## if(rean.impact.name == "ERA-Interim") rean.impact <- '/esnas/recon/ecmwf/erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc' 

if(rean.name == "JRA-55") rean <- paste0('/esarchive/recon/jma/jra55/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')
if(rean.name == "NCEP") rean <- paste0('/esarchive/recon/noaa/ncep-reanalysis/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')
if(rean.name == "ERA-Interim") rean <- paste0('/esarchive/recon/ecmwf/erainterim/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')

if(rean.impact.name == "JRA-55") rean.impact <- paste0('/esarchive/recon/jma/jra55/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')
if(rean.impact.name == "NCEP") rean.impact <- paste0('/esarchive/recon/noaa/ncep-reanalysis/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')
if(rean.impact.name == "ERA-Interim") rean.impact <- paste0('/esarchive/recon/ecmwf/erainterim/', rean.freq,'/$VAR_NAME$_$YEAR$$MONTH$.nc')
if(area == "EU_CF") rean.impact <- paste0('/esarchive/scratch/llledo/daily_CF_ERAI')

# name of cluster variable 'psl' to show in the figures:
if(psl == "psl") { psl.name <- "SLP"; psl.name.full <- "Sea Level Pressure"; psl.unit <- "hPa" }
if(psl == "g500") { psl.name <- "g500"; psl.name.full <- "Geopotential at 500 hPa"; psl.unit <- "" }
if(psl == "g250") { psl.name <- "g250"; psl.name.full <- "Geopotential at 250 hPa"; psl.unit <- "" }
if(psl == "sfcWind") { psl.name <- "10m Wind Speed" ; psl.name.full <- "10-meter Wind Speed"; psl.unit <- "m/s" }

# names of the target impact variable:
var.name <- c("sfcWind","tas","prlr", "psl", "iec1", "iec2", "iec3")                                  # name of the 'predictand' variable of the chosen reanalysis
var.name.full <- c("10-m Wind Speed","Temperature", "Precipitation", "Sea Level Pressure", "Iec1", "Iec2", "Iec3")   # full name of the 'predictand' variable to put in the title of the graphs
var.unit <- c("m/s", paste0(deg, "C"), "mm", "hPa", "", "", "")                                       # unit of measure of var (for drawing color scales)

## if you are generating a report for a EDPR, variables below are setted to a value which depend on the type of report to create:
if(report.type == "none") { two.rean <- TRUE; new.classif <- TRUE; impact.last <- TRUE; rean.impact.name <- "ERA-Interim" }
if(report.type == "first") { two.rean <- TRUE; new.classif <- TRUE; impact.last <- FALSE; rean.impact.name <- "ERA-Interim" }
if(report.type == "anexo") { two.rean <- FALSE; new.classif <- FALSE; impact.last <- TRUE }
if(report.type == "second") { two.rean <- TRUE; new.classif <- FALSE; impact.last <- TRUE; rean.impact.name <- "ERA-Interim" }

## Here you can define a spatial domain for the clustering by inserting the coordinates of the box enclosing the study region to cluster:
## in latitude NORTH and longitude EAST (thus, insert a positive number from 0 to 360 as 'lon.min'):
if(area == "EU"){ area.name <- "North Atlantic"; lon.min <- 274.5; lon.max <- 45; lat.min <- 27; lat.max <- 81} ## the Northern Atlantic area used by Meteo-France
if(area == "EU_psl"){ area.name <- "North Atlantic"; lon.min <- 274.5; lon.max <- 45; lat.min <- 27; lat.max <- 81} ## the Northern Atlantic area used by Meteo-France
if(area == "EU_wind"){ area.name <- "North Atlantic"; lon.min <- 274.5; lon.max <- 45;  lat.min <- 27; lat.max <- 81} ## the Northern Atlantic area used by Meteo-France
if(area == "EU_tas"){ area.name <- "North Atlantic";  lon.min <- 274.5; lon.max <- 45; lat.min <- 27; lat.max <- 81 } ## the Northern Atlantic area used by Meteo-France
if(area == "EU_CF"){ area.name <- "North Atlantic"; lon.min <- 274.5; lon.max <- 44; lat.min <- 27; lat.max <- 81 } ## the Northern Atlantic area with American coast
##if(area == "Western_USA"){ area.name <- "Western USA"; lon.min <- 220; lon.max <- 250; lat.min <- 40; lat.max <- 60 } ## Western United states with Javi spatial domain
if(area == "Western_USA"){ area.name <- "Western USA"; lon.min <- 220; lon.max <- 250; lat.min <- 30; lat.max <- 60 } ## Western United states with South California
if(area == "Central_USA"){ area.name <- "Central USA"; lon.min <- 252.5; lon.max <- 282.5; lat.min <- 25; lat.max <- 55  } ## Eastern USA with Coleman domain
if(area == "Eastern_USA"){ area.name <- "Eastern USA"; lon.min <- 270; lon.max <- 300; lat.min <- 30; lat.max <- 50  } ## Eastern USA with Quian spatial domain
if(area == "Garcia"){ area.name <- "North America"; lon.min <- 200; lon.max <- 280; lat.min <- 20; lat.max <- 70 } ## Western United states with Javi spatial domain
if(area == "Garcia_6_regimes"){ area.name <- "North America";  lon.min <- 200; lon.max <- 280; lat.min <- 20; lat.max <- 70 } ## Western USA with Javi spatial domain
if(area == "Garcia_jolly"){ area.name <- "North America";  lon.min <- 200; lon.max <- 280; lat.min <- 20; lat.max <- 70 } ## Western USA with Javi spatial domain
if(area == "Casola"){ area.name <- "North Pacific";  lon.min <- 150; lon.max <- 300; lat.min <- 20; lat.max <- 90 } ## Western United States with Casola spatial Domain
if(area == "Small"){ area.name <- "North America"; lon.min <- 220; lon.max <- 250; lat.min <- 40; lat.max <- 60 } ## Western United states with Javi spatial domain
if(area == "VerySmall"){ area.name <- "North America"; lon.min <- 230; lon.max <- 240; lat.min <- 45; lat.max <- 65 } ## Western United states with Javi spatial domain
if(area == "Eastern_Garcia"){ area.name <- "North America";  lon.min <- 230; lon.max <- 330; lat.min <- 20; lat.max <- 70 } ## Eastern USA with shifted Javi spatial domain
if(area == "Eastern_Casola"){ area.name <- "North Pacific"; lon.min <- 210; lon.max <- 330; lat.min <- 20; lat.max <- 90 } ## Eastern USA with shifted Casola spatial Domain
if(area == "Eastern_Quian"){ area.name <- "Eastern USA"; lon.min <- 270; lon.max <- 300; lat.min <- 30; lat.max <- 50  } ## Eastern USA with Quian spatial domain
if(area == "Eastern_Coleman"){ area.name <- "Eastern USA"; lon.min <- 252.5; lon.max <- 282.5; lat.min <- 25; lat.max <- 55  } ## Eastern USA with Coleman domain
if(area == "Lea"){ area.name <- "South Africa"; lon.min <- 300; lon.max <- 40; lat.max <- 0; lat.min <- -60 } ## South Africa
if(area == "Solman"){ area.name <- "South America"; lon.min <- 260; lon.max <- 320; lat.min <- -60; lat.max <- -10  } ## Chile, big area
if(area == "Oliver"){ area.name <- "South America"; lon.min <- 284; lon.max <- 297; lat.min <- -30; lat.max <- -17 } ## Chile, small area
if(area == "AltaBolivia"){ area.name <- "South America"; lon.min <- 285; lon.max <- 300; lat.min <- -25; lat.max <- -5 } ## Chile, small area towards Bolivia
if(area == "AltaBolivia2"){ area.name <- "South America"; lon.min <- 275; lon.max <- 310; lat.min <- -30; lat.max <- -5 } ## Chile, small area towards Bolivia

## spatial domain used only to visualize 'psl' regime structure maps: (in latitude Norte y longitude Este):
if(area == "EU") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "EU_psl") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "EU_wind") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "EU_tas") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "EU_CF") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "Western_USA") { bigarea.name <- "Pacific and North America"; bigarea.lon.min <- 190; bigarea.lon.max <- 310; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Central_USA") { bigarea.name <- "Pacific and North America"; bigarea.lon.min <- 190; bigarea.lon.max <- 310; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Eastern_USA") { bigarea.name <- "Pacific and North America"; bigarea.lon.min <- 190; bigarea.lon.max <- 310; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Garcia") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Garcia_6_regimes") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Garcia_jolly") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Casola") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Small") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "VerySmall") {  bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Eastern_Garcia") { bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Eastern_Casola") { bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Eastern_Quian") { bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Eastern_Coleman") { bigarea.name <- area.name; bigarea.lon.min <- 160; bigarea.lon.max <- 330; bigarea.lat.min <- 15; bigarea.lat.max <- 75 }
if(area == "Solman") { bigarea.name <- area.name; bigarea.lon.min <- lon.min; bigarea.lon.max <- lon.max; bigarea.lat.min <- lat.min; bigarea.lat.max <- lat.max }
if(area == "Oliver") { bigarea.name <- area.name; bigarea.lon.min <- lon.min - 40; bigarea.lon.max <- lon.max + 50; bigarea.lat.min <- lat.min - 30; bigarea.lat.max <- lat.max + 10 }
if(area == "AltaBolivia") { bigarea.name <- ""; bigarea.lon.min <- lon.min - 40; bigarea.lon.max <- lon.max + 50; bigarea.lat.min <- lat.min - 30; bigarea.lat.max <- lat.max + 10 }
if(area == "AltaBolivia2") { bigarea.name <- ""; bigarea.lon.min <- lon.min - 40; bigarea.lon.max <- lon.max + 50; bigarea.lat.min <- lat.min - 30; bigarea.lat.max <- lat.max + 10 }

## set the area to show in the impact figures:  (in latitude Norte y longitude Este):
if(area == "EU") { imp.area.name <- "Europe"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "EU_psl") { imp.area.name <- "Europe"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "EU_wind") { imp.area.name <- "Europe"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "EU_tas") { imp.area.name <- "Europe"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "EU_CF") { imp.area.name <- "Europe"; imp.area.lon.min <- 342; imp.area.lon.max <- 40; imp.area.lat.min <- 32; imp.area.lat.max <- 72 }
if(area == "Western_USA") { imp.area.name <- "North America"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Central_USA") {  imp.area.name <- "North America"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Eastern_USA") {  imp.area.name <- "North America"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Garcia") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Garcia_6_regimes") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Garcia_jolly") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Casola") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Small") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "VerySmall") { imp.area.name <- "USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Eastern_Garcia") { imp.area.name <- "Eastern USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Eastern_Casola") { imp.area.name <- "Eastern USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Eastern_Quian") {  imp.area.name <- "Eastern USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Eastern_Coleman") {  imp.area.name <- "Eastern USA"; imp.area.lon.min <- 190; imp.area.lon.max <- 310; imp.area.lat.min <- 15; imp.area.lat.max <- 75 }
if(area == "Solman") { imp.area.name <- "South America"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "Oliver") { imp.area.name <- "South America"; imp.area.lon.min <- lon.min; imp.area.lon.max <- lon.max; imp.area.lat.min <- lat.min; imp.area.lat.max <- lat.max }
if(area == "AltaBolivia") { imp.area.name <- "South America"; imp.area.lon.min <- 284; imp.area.lon.max <- 297; imp.area.lat.min <- -30; imp.area.lat.max <- -17 }
if(area == "AltaBolivia2") { imp.area.name <- "South America"; imp.area.lon.min <- 284; imp.area.lon.max <- 297; imp.area.lat.min <- -30; imp.area.lat.max <- -17 }

## for South America, you only need to set the 'psl' variable, all the others are set below:
if(area == "Oliver" || area == "AltaBolivia" || area == "AltaBolivia2"){
    year.start <- 1966; year.end <- 2015; period <- 18; n.cl <- 4
    rootdir <- "/shared/earth/Operational/EDPR/USA/Oliver"; two.rean <- FALSE
    fig2catalog.dir <- "/shared/earth/Operational/EDPR/USA"
    station.data.dir <- paste0(rootdir, "/Oliver")
    rean.name <- "NCEP"; rean <- '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'
    stations <- TRUE; detrend.psl <- TRUE; detrend.var <- TRUE; var.num <- 3; end.map <- 0.37; end.map.clim <- 0.28
    save.txt <- FALSE; order4lastyear <- FALSE; box.impact <- FALSE; my.contours.zero <- FALSE; my.countries <- TRUE
}

## for the Capacity Factor, you only need to set the "var.num" variable to 5,6 or 7, all the others are set below:
if(area == "EU_CF"){
    rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor"
    year.start <- 1981;  year.end <- 2016; period <- 1:12; rean.name <- "ERA-Interim"
    subdaily <- FALSE; report.type <- "none"; two.rean <- FALSE; rean.impact.name <- "CF"
    new.classif <- FALSE; impact.last <- FALSE; stations <- FALSE
    psl <- "psl"; lat.weighting <- TRUE; LOESS <- TRUE
    order4lastyear <- FALSE; box.impact <- FALSE; save.txt <- FALSE
    end.map.clim <- 0.30; figures.last <- FALSE
}

## EDPR wind farm position must be with longitude east and latitude north coordinates:
if(wind.farms){ 
    my.farm <- array(NA, c(100,2)) ## 100 is the max number of points; increase it if it will be greater than it.
    my.farm[1,] <- c(360-98.6169,34.8629); ## my.farm[2,] <- c(360-98.4689,34.8204); my.farm[3,] <- c(360-98.5533,34.9261)
    my.farm[4,] <- c(360-117.8253,45.0908); my.farm[5,] <- c(360-120.7161,47.1444); my.farm[6,] <- c(360-99.5384,32.5858)
    my.farm[7,] <- c(360-99.5078,32.4938); ##my.farm[8,] <- c(360-95.2788,43.3509);
    my.farm[9,] <- c(360-75.4506,42.8958); ##my.farm[10,] <- c(360-75.5592,43.4671); my.farm[11,] <- c(360-75.6119,43.8274);
    my.farm[12,] <- c(360-73.8617,44.6134)
    my.farm[13,] <- c(360-86.8913,40.6888); my.farm[14,] <- c(360-87.0556,40.6357); ##my.farm[15,] <- c(360-87.0893,40.5987)
    ## my.farm[16,] <- c(360-87.0919,40.6836);
    my.farm[17,] <- c(360-97.5625,39.4134); my.farm[18,] <- c(360-97.7758,39.4318)
    my.farm[19,] <- c(360-92.5565,43.4653); ## my.farm[20,] <- c(360-92.706,43.4513);
    my.farm[21,] <- c(360-92.6107,43.6437)
    my.farm[22,] <- c(360-89.4263,40.3316); my.farm[23,] <- c(360-120.2595,45.6896); my.farm[24,] <- c(360-75.3583,44.9425)
    my.farm[25,] <- c(360-84.7958,41.008); ##my.farm[26,] <- c(360-88.638,41.1481);
    my.farm[27,] <- c(360-88.5434,41.1984); ## my.farm[28,] <- c(360-88.7816,40.4832); my.farm[29,] <- c(360-88.5428,40.4607);
    my.farm[30,] <- c(360-120.3336,45.6761); ## my.farm[31,] <- c(360-120.2397306241,45.6878103713);
    my.farm[32,] <- c(360-98.6407152889,34.8754504396); my.farm[33,] <- c(360-75.5735467327,43.7581635836)
    my.farm[34,] <- c(258.56, 25.68); my.farm[35,] <- c(284.6417, 44.9425);
    my.farm[36,] <- c(360-118.2223291667, 35.083595); ## my.farm[37,] <- c(360-118.2067116667, 35.08964166667); my.farm[38,] <- c(360-118.2482683333, 35.0587576667)
}

n.years <- year.end - year.start + 1
year.end.clim <- year.end - 1 # last year for computation of climatology (unless year.end has data available for all months, it's better to set it to the previous year)
n.years.clim <- year.end.clim - year.start + 1

##cat(paste0("Rean: ", rean.name, " Period: ", period, " Year: ", year.end, "\n"))
n.map <- 0

orden <- paste0(1:n.cl," expl.variance")
regime.title <- paste0("Regime ",1:n.cl)

## breaks and color scales for anomaly maps of cluster variable and impact variable:

## for cluster variable in anomalies (slp or geopotential):           
my.brks <- c(-100,seq(-21,-1,2),0,seq(1,21,2),100) ## 23 intervals
if(stations) my.brks <- c(-100,seq(-8,-1,1),0,seq(1,8,1),100) ## 23 intervals

## blue--red colors:
if(blue2red) my.cols <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks)-1) else my.cols <- colorRampPalette(brewer.pal(11,"RdBu"))(length(my.brks)-1)  
my.cols[floor(length(my.cols)/2)] <- my.cols[floor(length(my.cols)/2)+1] <- "white"

## same but for cluster variable NOT in anomalies:
my.brks.no.anom <- c(0, seq(1000, 1034, 2))
if(stations) my.brks.no.anom <- c(0, seq(1030, 1120, 2), 1200) ## values adjuste to represent the Bolivian High (for g250)
if(blue2red) my.cols.no.anom <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.no.anom)-1) else  my.cols.no.anom <- colorRampPalette(brewer.pal(11,"RdBu"))(length(my.brks.no.anom)-1)
##my.cols.no.anom[floor(length(my.cols.no.anom)/2)] <- my.cols.no.anom[floor(length(my.cols.no.anom)/2)+1] <- "white" ## with middle white colour

## same but for sfcWind when used as predictor: 
if(psl == "sfcWind"){
  my.brks <- c(-100, seq(-5,5,0.5), 100) ## tot
  my.cols <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks)-1)    # blue--red colors
  my.cols[floor(length(my.cols)/2)] <- my.cols[floor(length(my.cols)/2)+1] <- "white"
}

## color scale for impact maps: (they are the same for each variable because they are always expressed as a %)
## my.brks.var <- c(-20,seq(-3,3,0.5),20)
my.brks.var <- c(-1000,seq(-0.6,0.6,0.1), 1000) ## 15 intervals
my.brks.cf <- c(-1000,seq(-0.26,0.26,0.04), 1000) ## 15 intervals and for values from 0 to 1 for the CF
my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--white--red colors
my.cols.cf <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.cf)-1)    # blue--white--red colors

if(stations){
  my.brks.var <- c(-1000,seq(-0.3,0.3,0.1),1000) ## 8 colors 
  my.cols.var <- c('#a50026','#d73027','#f46d43','#fdae61','#abd9e9','#74add1','#4575b4','#313695')
}


## load only 1 day of psl data to detect the minimum and maximum lat and lon values which identify only the chosen domain:
cat("Loading lat/lon. Please wait...\n")
domain <- Load(var = psl, exp = NULL, obs = list(list(path=rean)), paste0(year.start,'0101'), storefreq = 'daily', leadtimemax = 1, output = 'lonlat', nprocs=1)

pos.lat.max <- which(lat.max - round(domain$lat, 8) >= 0)[1]           # select the last latitude of the domain below the maximum latitude
pos.lat.min <- tail(which(round(domain$lat, 8) - lat.min >= 0),1)      # select the first latitude of the domain over the minumum latitude
pos.lon.max <- tail(which(lon.max - round(domain$lon, 8) >= 0),1)      # select the last longitude of the domain below the maximum longitude
pos.lon.min <- which(round(domain$lon, 8) - lon.min >= 0)[1]           # select the first longitude of the domain over the minimum longitude

pos.lat <- if(pos.lat.min < pos.lat.max) {pos.lat.min:pos.lat.max} else {pos.lat.max:pos.lat.min}

if(pos.lon.min > pos.lon.max) pos.lon <- c(1:pos.lon.max, pos.lon.min:length(domain$lon)) # in case the study area cross the meridian of Greenwhich
if(pos.lon.min < pos.lon.max) pos.lon <- pos.lon.min:pos.lon.max   # in case the study area doesn't cross the meridian of Greenwhich

n.pos.lat <- length(pos.lat)
n.pos.lon <- length(pos.lon)

if(lat.min >= lat.max) stop("lat.min cannot be greater than lat.max")

lat <- domain$lat[pos.lat] # lat values of cluster spatial domain (it is usually smaller than the whole area loaded for visualizing figures)
#if (lat[2] < lat[1]) lat <- rev(lat) # reverse lat values if they are in decreasing order
lon <- domain$lon[pos.lon] # lon values of cluster spatial domain

n.lon <- length(lon) ## typically lon varies from 0 to 360 degrees east
n.lat <- length(lat) ## typically lat varies from 90 to -90 degrees north

## spatial resolution psl dataset loaded:
res.lon <- abs(lon[2] - lon[1]) 
res.lat <- abs(lat[2] - lat[1]) ## can be slightly different from horizontal resolution (psl.res.lon)

## four corners of the psl cluster domain (remember that coordinates are in degrees latitude North and longitude East):
cl.min.lat <- min(lat) - res.lat/2
cl.max.lat <- max(lat) + res.lat/2
cl.min.lon <- min(lon) - res.lon/2
cl.max.lon <- max(lon) + res.lon/2

## notation for figure captions of regime anomalies:
cl.lat.min.legend.letter <- ifelse(cl.min.lat >= 0, "N", "S")
cl.lat.min.legend <- ifelse(cl.min.lat >= 0, cl.min.lat, -cl.min.lat)
cl.lat.max.legend.letter <- ifelse(cl.max.lat >= 0, "N", "S")
cl.lat.max.legend <- ifelse(cl.max.lat >= 0, cl.max.lat, -cl.max.lat)

cl.lon.min.legend.letter <- ifelse(cl.min.lon <= 180, "E", "W")
cl.lon.min.legend <- ifelse(cl.min.lon <= 180, cl.min.lon, 360 - cl.min.lon)
cl.lon.max.legend.letter <- ifelse(cl.max.lon <= 180, "E", "W")
cl.lon.max.legend <- ifelse(cl.max.lon <= 180, cl.max.lon, 360 - cl.max.lon)

## create root dir, if it doesn't exist yet:
dir.create(file.path(paste0(rootdir,"/", area)))

###############################################################################################
#                                   Start analysis                                            #
###############################################################################################

##################### Compute slp anomalies only for cluster analysis #########################

if(new.classif){   
    ## Load psl data (interpolating it to the same reanalysis grid, if necessary):
    cat(paste0("Loading ", psl.name," data. Please wait...\n"))

    ## Load all months because you need to remove seasonal variability:
    psleuFull366 <-  Load(var = psl, exp = NULL, obs = list(list(path=rean)), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax = 366, output = 'lonlat', latmin = lat.min, latmax = lat.max, lonmin = lon.min, lonmax = lon.max, nprocs=ncores)

    if(length(which(is.na(psleuFull366$obs))) > 0) print("There are missing values in the reanalysis. Revise data. Ignore this message if you are generating a report for EDPR")

    ## remove bisestile days to have all arrays with the same dimensions:
    cat("Removing bisestile days. Please wait...\n")
    psleuFull <-array(NA,c(1, 1, n.years, 365, n.pos.lat, n.pos.lon))
    psleuFull[,,,,,] <- psleuFull366$obs[,,,1:365,,]

    for(y in year.start:year.end){
        y2 <- y - year.start + 1
        if(n.days.in.a.year(y) == 366) psleuFull[,,y2,60:365,,] <- psleuFull366$obs[,,y2,61:366,,] # take the march to december period removing the 29th of February
    }

    psleuFull366$obs <- NULL
    gc()

    ## convert psl in daily anomalies with the LOESS filter:
    cat(paste0("Calculating ", psl.name, " anomalies for ", area," domain. Please wait...\n"))
    psleuFull_no_last_year <- psleuFull[1,1,1:n.years.clim,,,,drop=FALSE] ## remove last year (climatology ends before)
    
    ## pslPeriodClim <- Apply(psleuFull_no_last_year, c(1,2,4,5,6), "mean", parallel=TRUE, ncores=8, na.rm=T) ## old syntax
    pslPeriodClim <- apply(psleuFull_no_last_year, c(1,2,4,5,6), mean, na.rm=T)
    rm(psleuFull_no_last_year)
    gc()

    if(LOESS){
        pslPeriodClimLoess <- array(NA, dim(pslPeriodClim))
        
        for(i in 1:n.pos.lat){
            for(j in 1:n.pos.lon){
                my.data <- data.frame(ens.mean=rep(pslPeriodClim[1,1,,i,j],3), day=1:(365*3))
                my.loess <- loess(ens.mean ~ day, my.data, span=my.span)
                pslPeriodClimLoess[1,1,,i,j] <- predict(my.loess)[366:730]
            }
        }
        
        pslPeriodClim2 <- InsertDim(pslPeriodClimLoess, 3, n.years)
        
    } else { # leave the daily climatology to compute the anomalies:
        pslPeriodClim2  <- InsertDim(pslPeriodClim, 3, n.years)
        
    }

    psleuFull <- psleuFull - pslPeriodClim2    

    rm(pslPeriodClim, pslPeriodClim2)
    gc()

    if(psl == "g500" || psl == "g250") psleuFull <- psleuFull/9.81   # convert geopotential to geopotential height (in m)
    if(psl=="psl") psleuFull <- psleuFull/100   # convert MSLP in Pascal to MSLP in hPa
    gc()


    #################### Clustering analysis #######################################################3

    my.PCA <- list()
    my.cluster <- list()
    my.cluster.array <- list()
    tot.variance <- list()
    n.pcs <- my.cluster <- c()

    for(p in period){
        ## Select only the data of the month/season we want:
        
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        dir.create(file.path(workdir))
        
        pslPeriod <- psleuFull[1,1,, pos.period(1,p),,] # select only days in the chosen period (i.e: winter)
        
        ## weight the pressure fields based on latitude (apply it to anomalies, not to absolute values!):
        if(lat.weighting){
            if(PCA) lat.weighted <- cos(lat*pi/180)^0.5
            if(!PCA) lat.weighted <- cos(lat*pi/180)
            
            lat.weighted.array <- InsertDim(InsertDim(InsertDim(lat.weighted,2,n.pos.lon), 1, length(pos.period(2001,p))), 1, n.years)
            
            pslPeriod.weighted <- pslPeriod * lat.weighted.array
            
            rm(lat.weighted.array)
            gc()
        } else {
            pslPeriod.weighted <- pslPeriod
        }
        
        gc()

        if(fast.reshape){
            cat(paste0("Fast formatting ", psl.name," for clustering ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))
            psl.kmeans <- array(aperm(pslPeriod.weighted[,,,, drop=FALSE], c(2,1,3,4)), c(dim(pslPeriod)[1] * dim(pslPeriod)[2], dim(pslPeriod)[3] * dim(pslPeriod)[4]))
        } else {
            cat(paste0("Preformatting ", psl.name," for clustering ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))
            psl.melted.weighted <- melt(pslPeriod.weighted[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
            gc()
            cat(paste0("Preformatting ", psl.name," for clustering ", period.name[p]," with ", n.cl," regimes. Please wait......\n"))
            psl.kmeans <- unname(acast(psl.melted.weighted, Year + Day ~ Lat + Lon))        ## this function eats much memory!!!
            gc()
        }
        
        if(detrend.psl){  ##### remove psl trend for the chosen period:
            cat(paste0("Detrending ", period.name[p],". Please wait...\n"))
            
            ##psl.kmeans <- array(1:50, c(50,5,10)) ## test only
            daily.seq <- 1:dim(psl.kmeans)[1] # create a sequence from 1 to the number of years*days
            psl.slope <- apply(psl.kmeans, 2, function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            psl.intercept <- apply(psl.kmeans, c(2), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            psl.kmeans.detrended <- array(NA, c(dim(psl.kmeans)))
            for(t in daily.seq) psl.kmeans.detrended[t,] <- psl.kmeans[t,] - psl.slope*t - psl.intercept
            
            psl.kmeans <- psl.kmeans.detrended
            rm(psl.kmeans.detrended)
            gc()

            ## save trend plot:
            psl.trendpv <- apply(psl.kmeans, c(2), function(x) MannKendall(x)$sl[1])  ## get trend pvalue at each point just to check if and where it is significant
            psl.trendfull <- psl.slope * length(daily.seq) # same trend but expressed as change over the full study period

            psl.trendfull.2plot <- t(array(psl.trendfull, c(n.lon, n.lat)))
            psl.trendpv.2plot <- t(array(psl.trendpv, c(n.lon, n.lat)))

            file.trend.psl <- paste0(workdir,"/",year.end,"_",my.period[p],"_trend_",var.name[var.num],".png")
            png(filename=file.trend.psl,width=1500, height=1000)

            par(fig=c(0.01,0.99,0.10,0.95))
            PlotEquiMap(psl.trendfull.2plot, lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, dots=psl.trendpv.2plot < 0.01, drawleg=FALSE, toptitle=paste0(psl.name," trend (", var.unit[var.num],") during ", period.name[p], " ", year.start, "-", year.end))

            par(fig=c(0,1,0,0.08), new=TRUE)
            ColorBar(brks=my.brks[2:(l(my.brks)-1)], cols=my.cols[2:(l(my.cols)-1)], vert=FALSE, label_scale=2, bar_limits=c(my.brks[2],my.brks[l(my.brks)-1]), col_inf=my.cols[1], col_sup=my.cols[l(my.cols)], subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
            
            dev.off()
            
        }

        ## compute the clustering:
        cat(paste0("Clustering ", psl.name," data for ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))
        my.PCA <- tot.variance <- n.pcs <- c()
        
        if(PCA){ 
            my.seq <- seq(1, n.pos.lat*n.pos.lon, 16) # select only 1 point of 9 because the number of dimensions must be lower than the number of days to run the PCA
            pslcut <- psl.kmeans[,my.seq]
            
            my.PCA <- princomp(pslcut, cor=FALSE)
            tot.variance <- head(cumsum(my.PCA$sdev^2 / sum(my.PCA$sdev^2)),100)  # check how many PCAs to keep basing on the sum of their expl. variance
            n.pcs <- head(as.numeric(which(tot.variance > variance.explained)),1) # select only the pcs that explains at least XX% of variance (typically 80% or 99%)
            
            my.cluster <- kmeans(my.PCA$scores[,1:n.pcs], centers=n.cl, iter.max=my.iter.max, nstart=my.nstart)  # n.cl is the number of clusters
            rm(pslcut)
            
        } else { # n.cl is the number of clusters:
            
            my.cluster <- kmeans(psl.kmeans, centers=n.cl, iter.max=my.iter.max, nstart=my.nstart, trace=FALSE)
            
        }
        
        optimal.num <- TRUE
        if(optimal.num){
        
            ## Neven's function:
            ## my.weights <- psl.kmeans[1,]*0+1
            ## my.cluster <- Cluster(psl.kmeans, nclusters=NULL, my.weights, index='sdindex', posdates=1)
            
            ## Original function with 24 different criteria (+2 graphical criteria):
            ## you have to execute PCA before, to create variables 'my.PCA' and 'n.pcs'
            ncl.min <- 4
            ncl.max <- 20
            
            best.nclusters <- NbClust(data=my.PCA$scores[,1:n.pcs], diss=NULL, distance="euclidean", min.nc=ncl.min, max.nc=ncl.max, method="kmeans", index="all", alphaBeale=0.1)
            
            ##multi.hist(array(best.nclusters$Best.nc[1,], c(26,2)), density=F, freq=T, main=c("t1", "t2"), col="gray", breaks=-0.5:20.5)
            
            ## Original function with 24 different criteria and 2 graphical ones but without PCA (not used because it is too slow):
            ## best.nclusters <- NbClust(data=psl.kmeans, diss=NULL, distance="euclidean", min.nc=3, max.nc=15, method="kmeans", index="all", alphaBeale=0.1)
            
            ## save the clusters for the elbow criteria test:
            ncl.min.elb <- 3
            ncl.max.elb <- 15
            
            for(clu in ncl.min.elb:ncl.max.elb){
                my.cluster <- kmeans(psl.kmeans, centers=clu, iter.max=50, nstart=10, trace=FALSE)  ## short version with less convergence
                save(area, my.cluster, file=paste0(workdir,"/", year.end, "_", my.period[p],"_elbow_",clu,"_clusters.RData"))
            }

            ## save the variable 'best.nclusters' with all the info on the optimal number of clusters:
            save(area, PCA, my.PCA, tot.variance, n.pcs, lon, lon.max, lon.min, lat, lat.max, lat.min, pos.lat, pos.lon, n.pos.lat, n.pos.lon, psl, psl.name, p, workdir, rean.name, year.start, year.end, n.years, period, LOESS, lat.weighting, best.nclusters, ncl.min, ncl.max, file=paste0(workdir,"/", year.end, "_", my.period[p],"_best_nclusters.RData"))
            
        }

        ## After you saved all monthly files, you can also
        ## plot a composition with the frequeny histogram of each month:
        my.main = "Optimal number of K-means clusters"
        par(mfrow=c(3,6))
        for(m in 1:17){
            load(paste0("/esarchive/scratch/ncortesi/Regimes/89_optimal_number_of_regimes_for_month/EU/2016_", my.period[m],"/2016_", my.period[m],"_best_nclusters.RData"))
            
            best.nclusters$Best.nc[1,][which(best.nclusters$Best.nc[1,] == 0)] <- NA ## remove criteria with 0 clusters
            hist(best.nclusters$Best.nc[1,], breaks=-0.5:20.5, col="gray", main=my.period[m], xlab="Number of clusters", ylab="Number of criteria", axes=F, ylim=c(0,10))
            axis(1, at=1:20, labels=c(1,2,3,4,5,6,7,8,9,10,NA,12,NA,14,NA,16,NA,18,NA,20), cex.axis=.7)
            axis(2, at=0:10)
        }

        gc()
        rm(psl.kmeans)
        gc()
        
        cat(paste0("Extracting ", period.name[p]," regimes. Please wait...\n"))
        
        cluster.sequence <- my.cluster$cluster
        
        if(sequences){ # it works only for rean data!!!
            ## for each of the 4 clusters, remove the days not belonging to sequences of at least 5 days:
            ## warning: first 4 days and last 4 days are not take into account y the algorithm and are treated as not belonging to any sequence (sequ=FALSE)    
            wrdiff <- diff(my.cluster$cluster)
            
            sequ <- rep(FALSE, n.days.period[[p]])
            for(i in 5:(n.days.period[[p]]-5)){
                sequ[i] <- TRUE
                if(wrdiff[i] != 0 & wrdiff[i+1] != 0) sequ[i] = FALSE
                if(wrdiff[i] != 0 & wrdiff[i+2] != 0) sequ[i] = FALSE
                if(wrdiff[i] != 0 & wrdiff[i+3] != 0) sequ[i] = FALSE
                if(wrdiff[i] != 0 & wrdiff[i+4] != 0) sequ[i] = FALSE
                if(wrdiff[i-1] != 0 & wrdiff[i] != 0) sequ[i] = FALSE
                if(wrdiff[i-1] != 0 & wrdiff[i+1] != 0) sequ[i] = FALSE
                if(wrdiff[i-1] != 0 & wrdiff[i+2] != 0) sequ[i] = FALSE
                if(wrdiff[i-1] != 0 & wrdiff[i+3] != 0) sequ[i] = FALSE
                if(wrdiff[i-2] != 0 & wrdiff[i] != 0) sequ[i] = FALSE
                if(wrdiff[i-2] != 0 & wrdiff[i+1] != 0) sequ[i] = FALSE
                if(wrdiff[i-2] != 0 & wrdiff[i+2] != 0) sequ[i] = FALSE
                if(wrdiff[i-3] != 0 & wrdiff[i] != 0) sequ[i] = FALSE
                if(wrdiff[i-3] != 0 & wrdiff[i+1] != 0) sequ[i] = FALSE
                if(wrdiff[i-4] != 0 & wrdiff[i] != 0) sequ[i] = FALSE
            } # close for loop on i
            
            ## sequence of daily cluster numbers without the days that doesn't belong to sequences of 5 or more days:
            cluster.sequence <- my.cluster$cluster * sequ
            rm(wrdiff, sequ)
        } # close if on frequencies
        
        
        wr <- list()
        for(cl in 1:n.cl) wr[[cl]] <- which(cluster.sequence == cl)

        ## yearly frequency of each regime:    
        ##wr1y <- wr2y <- wr3y <- wr4y <- c()
        
        np <- n.days.in.a.period(p,1)
        
        wry <- list()
        for(cl in 1:n.cl){
            wry[[cl]] <- rep(NA, year.end - year.start + 1)
            
            for(y in year.start:year.end){
                ## for both reanalysis and S4, the time order is always: year1day1, year1day2, ..., year1day31, year2day1, year2day2, ..., year2day28, etc,
                wry[[cl]][y-year.start+1]  <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == cl))
            }
        }
        
        ## convert to frequencies in %:        
        for(cl in 1:n.cl) wry[[cl]] <- wry[[cl]] / np
        gc()
        
        cat(paste0("Extracting ", period.name[p]," regimes structure. Please wait...\n"))
        
        ## measure regime anomalies:
        if(fast.reshape){
            cat(paste0("Fast formatting ", psl.name," for clustering ", period.name[p]," with ", n.cl," regimes. Please wait......\n"))
            pslmat <- array(aperm(pslPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(pslPeriod)[1] * dim(pslPeriod)[2], dim(pslPeriod)[3], dim(pslPeriod)[4]))
        } else {
            cat(paste0("Preformatting ", psl.name," for clustering ", period.name[p]," with ", n.cl," regimes. Please wait.........\n"))
            pslmat <- unname(acast(psl.melted, Year + Day ~ Lat ~ Lon))
        }
        
        pslwr <- list()
        for(cl in 1:n.cl) pslwr[[cl]] <- pslmat[wr[[cl]],,, drop=F]
        
        ## regime structure:
        pslwrmean <- list()
        for(cl in 1:n.cl) pslwrmean[[cl]] <-  apply(pslwr[[cl]], c(2,3), mean, na.rm=T)
        
        ## spatial mean for each day to save for the measure of the FairRPSS:
        pslwrspmean <- list()
        for(cl in 1:n.cl) pslwrspmean[[cl]] <- apply(pslwr[[cl]], 1, mean, na.rm=T)
        
        cat("Saving clusters. Please wait....\n")
        
        ## save all the data necessary to redraw the graphs when we know the right regime:
        save(area, my.cluster, cluster.sequence, lon, lon.max, lon.min, lat, lat.max, lat.min, pos.lat, pos.lon, n.pos.lat, n.pos.lon, psl, psl.name, p, workdir, rean.name, year.start, year.end, n.years, period, pslwrmean, pslwrspmean, wry, wr, LOESS, lat.weighting, file=paste0(workdir,"/", year.end, "_", my.period[p],"_psl.RData"))    
       
    } # close the for loop on 'p' 

    ##rm(psleuFull, psl.melted, pslmat, pslPeriod, pslPeriodClimLoess)
    gc()

    ## sensitivity test for the optimal number of clusters:
    sens <- FALSE
    if(sens){        
        ## graph with the decrease of the total within sum of squares with the number of clusters:    
        p <- 1 ##13
        my.cl.range <- 2:15 ##2:10 ## vector with the number of clusters in the available classifications
        tot.withinss <- tot.ss <- c()
        year.end <- 2016
        
        area <- "Eastern_Garcia"
        
        for(cl in my.cl.range){
            ##load(file=paste0(rootdir, "/", area, "/", year.end, "_", my.period[p], "_", cl, "_clusters/", year.end,"_", my.period[p], "_psl.RData"))
            load(file=paste0(rootdir, "/", area, "/", year.end, "_", my.period[p], "/", year.end,"_", my.period[p], "_elbow_", cl,"_clusters.RData"))

            tot.withinss[cl] <- my.cluster$tot.withinss
            tot.ss[cl] <- my.cluster$totss
        }
        ss.perc1 <- 100 * tot.withinss / tot.ss
        ss.diff1 <- c(NA, diff(ss.perc1)[-length(ss.perc1)])
        
        plot(x=1:10, xlab="Number of clusters", ylab= "Total SSE in %", y=ss.perc1, col="red", type="b", xaxt="n", pch=19, ylim=c(40,100))
        axis(side=1, at=1:10, labels=1:10)
        
        
        area <- "Casola"
        
        for(cl in my.cl.range){
            load(file=paste0(rootdir, "/", area, "/", year.end, "_", my.period[p], "_", cl, "_clusters/", year.end,"_", my.period[p], "_psl.RData"))
            tot.withinss[cl] <- my.cluster$tot.withinss
            tot.ss[cl] <- my.cluster$totss
        }
        ss.perc2 <- 100 * tot.withinss / tot.ss
        ss.diff2 <- c(NA, diff(ss.perc2)[-length(ss.perc2)])
        
        lines(x=1:10, y=ss.perc2, col="purple", type="b", pch=19)
        
        ## plot difference of the two regions:
        plot(x=1:10, xlab="Number of clusters", ylab= "SSE difference (%)", y=ss.diff1, col="red", type="b", xaxt="n", pch=19) #, ylim=c(40,100))
        lines(x=1:10, y=ss.diff2, col="purple", type="b", pch=19)
        axis(side=1, at=1:10, labels=1:10)
        
        ## area <- "EU"
        
        ## for(cl in my.cl.range){
        ##     load(file=paste0(rootdir, "/", area, "/", year.end, "_", my.period[p], "_", cl, "_clusters/", year.end,"_", my.period[p], "_psl.RData"))
        ##     tot.withinss[cl] <- my.cluster$tot.withinss
        ##     tot.ss[cl] <- my.cluster$totss
        ## }
        ## ss.perc <- tot.withinss / tot.ss        
        ## line(x=1:10, y=ss.perc, col="gray70", type="b", xaxt="n", pch=19)     
                
        ## graph with the number of criterias for number of clusters:
        p <- 13
        my.cl.range <- 3:10 ## vector with the number of clusters in the available classifications
        ## tot.withinss <- tot.ss <- c()
        
        area <- "Eastern_Garcia"
        
        load(file=paste0(rootdir, "/", area, "/", year.end,"_", my.period[p], "_best_nclusters_3to10_99perc.RData")) 
        best <- best.nclusters$Best.nc[1,c(-23,-25)]
        
        ncrit <- c()
        for(cl in my.cl.range) ncrit[cl] <- length(which(best == cl))
        
        plot(x=1:10, xlab="Number of clusters", ylab= "Number of criteria", y=ncrit, col="red", type="b", xaxt="n", pch=19, ylim=c(0,12))
        axis(side=1, at=1:10, labels=1:10)
       
        area <- "Eastern_Casola"
        
        load(file=paste0(rootdir, "/", area, "/", year.end,"_", my.period[p], "_best_nclusters_3to10_99perc.RData")) 
        best <- best.nclusters$Best.nc[1,c(-23,-25)]
        
        ncrit <- c()
        for(cl in my.cl.range) ncrit[cl] <- length(which(best == cl))
        
        lines(x=1:10, y=ncrit, col="purple", type="b", pch=19)
        
        area <- "Eastern_Quian"
        
        load(file=paste0(rootdir, "/", area, "/", year.end,"_", my.period[p], "_best_nclusters_3to10_99perc.RData")) 
        best <- best.nclusters$Best.nc[1,c(-23,-25)]
        
        ncrit <- c()
        for(cl in my.cl.range) ncrit[cl] <- length(which(best == cl))
        
        lines(x=1:10, y=ncrit, col="black", type="b", pch=19)
        
        area <- "Oliver"
        
        load(file=paste0(workdir,"/", year.end, "_", my.period[p],"_best_nclusters_3to10_99perc.RData"))
        best <- best.nclusters$Best.nc[1,c(-23,-25)]
        
        ncrit <- c()
        for(cl in my.cl.range) ncrit[cl] <- length(which(best == cl))
        
        ncrit=c(0,0,8,8,3,0,1,1,0,2)
        plot(x=1:10, xlab="Number of clusters", ylab= "Number of criteria", y=ncrit, col="blue", type="b", xaxt="n", pch=19)
        axis(side=1, at=1:10, labels=1:10)  
    }


    #########################################################################################
    #                                    Order the clusters                                 #
    #########################################################################################

    if(order4lastyear){
        ## Clusters are ordered in decreasing order of frequency of occurrence during last year and period chosen:

        period.orig <- period
        for(p in period){
            cat(paste0("Ordering clusters for year ", year.end," and period ", period.name[p],". Please wait...\n"))

            ## mean wind speed and slp anomaly only during days of the chosen year:
            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # set the workding dir because the previous loop over p changed it
            
            load(paste0(workdir,"/",year.end,"_",my.period[p],"_psl.RData")) # load cluster.sequence
            
            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
            if(!identical(period, period.orig)) period <- period.orig
            
            ## arrange the regime sequence in an array, to separate months from years:
            cluster2D <- array(cluster.sequence, c(n.days.in.a.period(p,1), n.years))
            ##cluster2D <- array(my.cluster$cluster, c(n.days.in.a.period(p,1),n.years)) # only for NCEP

            ## select days only belonging to the test year:
            pos.year.test <- year.end - year.start + 1
            cluster.test <- cluster2D[, pos.year.test]
            
            fre.days <- c(); for(cl in 1:n.cl) fre.days[cl] <- length(which(cluster.test == cl))
            
            ## order cluster images for their frequencies of occurreance for that year and month:
            ## (if they have already been ordered once, they will be ordered again, no prob, they'll be ordered again)
            fre.days2 <- fre.days
            
            max.fre <- c()
            for(cl in 1:n.cl){
                max.fre[cl] <- which(fre.days2 == max(fre.days2, na.rm=TRUE))[1] ## 1 is needed to take only the first of the maximum, if more clusters have the same freq
                fre.days2[max.fre[cl]] <- NA
            }
            
            rm(fre.days2) 
            
            ## associate the cluster with the highest frequency to the first regime to plot and so on:
            cluster.name <- c(); for(cl in 1:n.cl) cluster.name[max.fre[[cl]]] <- orden[cl]

            ## save the regime order:
            save(cluster.name, file=paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData"))       
        }

    } else {  ## order the clusters in decreasing order of average frequency of occurrence during the whole study period:
        
        period.orig <- period
        for(p in period){
            cat(paste0("Ordering clusters for period ", period.name[p],". Please wait...\n"))

            ## mean wind speed and slp anomaly only during days of the chosen year:
            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # set the workding dir because the previous loop over p changed it
            
            load(paste0(workdir,"/",year.end,"_",my.period[p],"_psl.RData")) # load cluster.sequence
            
            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
            if(!identical(period, period.orig)) period <- period.orig
            
            ## arrange the regime sequence in an array, to separate months from years:
            cluster2D <- array(cluster.sequence, c(n.days.in.a.period(p,1), n.years))
            ##cluster2D <- array(my.cluster$cluster, c(n.days.in.a.period(p,1),n.years)) # only for NCEP
            
            fre.days <- c(); for(cl in 1:n.cl) fre.days[cl] <- length(which(cluster2D == cl))
            
            ## order cluster images for their frequencies of occurrence for that period:
            ## (if they have already been ordered once, they will be ordered again)
            fre.days2 <- fre.days
            
            max.fre <- c()
            for(cl in 1:n.cl){
                max.fre[cl] <- which(fre.days2 == max(fre.days2, na.rm=TRUE))[1] ## 1 is needed to take only the first of the maximum, if more clusters have the same freq
                fre.days2[max.fre[cl]] <- NA
            }
            
            rm(fre.days2) 
            
            ## associate the cluster with the highest frequency to the first regime to plot and so on:
            cluster.name <- c(); for(cl in 1:n.cl) cluster.name[max.fre[[cl]]] <- orden[cl]

            ## save the regime order:
            save(cluster.name, file=paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData"))       
        }


    }
    
} ## close if on new.classif

################################################################################
#                         Measure impact maps                                  #
################################################################################
cat(paste0("Measuring impact on ", var.name[var.num],". Please wait...\n"))

if(area != "EU_CF"){
    if(two.rean) rean2load <- rean.impact else rean2load <- rean
    if(two.rean) rean2load.name <- rean.impact.name else rean2load.name <- rean.name  ## name of the reanalysis loaded
} else {
    rean2load.name <- "ERA-Interim"
    if(var.name[var.num] == "sfcWind") rean2load <- rean else rean2load <- rean.impact
}

## there is no sub-daily precipitation for ERA-Interim, so we have to load the daily one which has the _s12-24h suffix:
if(!subdaily && var.name[var.num] == "prlr") rean2load <- paste0('/esnas/recon/ecmwf/erainterim/', '$STORE_FREQ$_mean/$VAR_NAME$_s12-24h','/$VAR_NAME$_$YEAR$$MONTH$.nc') 

if(!subdaily){
    ## Load var data:
    if(rean.impact.name != "CF"){ ## for netcdf files:
        
        ## if var data is not available for all months of year.end it will say that not all files are found, because of the leadtimemax of 366 days.
        vareuFull366 <-  Load(var = var.name[var.num], exp = NULL, obs = list(list(path = rean2load)), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax = 366, output = 'lonlat', latmin = imp.area.lat.min, latmax = imp.area.lat.max, lonmin = imp.area.lon.min, lonmax = imp.area.lon.max, nprocs=ncores)

        imp.area.lon <- vareuFull366$lon
        imp.area.lat <- vareuFull366$lat

        ## remove bisestile days to have all arrays with the same dimensions:
        cat("Removing bisestile days. Please wait...\n")
        vareuFull <- array(NA, c(1, 1, n.years, 365, dim(vareuFull366$obs)[5], dim(vareuFull366$obs)[6]))
        vareuFull[,,,,,] <- vareuFull366$obs[,,,1:365,,]
        
        for(y in year.start:year.end){
            y <- y - year.start + 1
            if(n.days.in.a.year(y) == 366) vareuFull[,, y, 60:365,,] <- vareuFull366$obs[,, y, 61:366,,] # take the march to december period removing the 29th of February
        }

        rm(vareuFull366)
        gc()

    } else {
        ## for RDB files:
        ## note that CF data comes from ERA-Interim, so we can use the same lat and lon values of psl:
        
        ## ## Load lat and lon of ERA-Interim because the CF data cannot be loaded by Load() wih options latmin latmax lonmin lonmax but by readRDS() which load all data:
        domain.var <- Load(var = psl, exp = NULL, obs = list(list(path= paste0('/esarchive/recon/ecmwf/erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc'))), '20000101', storefreq = 'daily', leadtimemax = 1, output = 'lonlat', nprocs=1)
        
        imp.area.lon.full <- domain.var$lon
        imp.area.lat.full <- domain.var$lat
        ## find the lat and lon values of the impact area chosen (because the readRDS function load all data):
        delete1 <- which(imp.area.lat.full < imp.area.lat.min)
        delete2 <- which(imp.area.lat.full > imp.area.lat.max)
        pos.imp.area.lat <- (1:length(imp.area.lat.full))[-c(delete1, delete2)]
        imp.area.lat <- imp.area.lat.full[pos.imp.area.lat]
        
        if(imp.area.lon.min < imp.area.lon.max){
            delete1 <-  which(imp.area.lon.full < imp.area.lon.min)
            delete2 <-  which(imp.area.lon.full > imp.area.lon.max)
            pos.imp.area.lon <- (1:length(imp.area.lon.full))[-c(delete1, delete2)]
            imp.area.lon <- imp.area.lon.full[pos.imp.area.lon]
        } else { ## in this case we have to remove the values in the middle of the sequence, not the external ones:
            include1 <-  which(imp.area.lon.full <= imp.area.lon.max)
            include2 <-  which(imp.area.lon.full >= imp.area.lon.min)
            pos.imp.area.lon <- c(include1,include2)
            imp.area.lon <- imp.area.lon.full[pos.imp.area.lon]
        }

        ## Load CF:
        vareuFull <- array(NA, c(n.years, 365, length(imp.area.lon), length(imp.area.lat)))        
        for(y in year.start:year.end){
            print(paste0("Loading Capacity Factor for year ", y))
            for(m in 1:12){
        
                ## load datos of year y and month m and extract only the impact area chosen:
                m2 <- ifelse(m >= 10, m, paste0(0,m))

                ## load Capacity Factor: ( format [31, 512, 256])
                vareuFull31 <- readRDS(paste0(rean.impact,"/ERAI_CF_", var.name[var.num],"_", y,  m2,".RDS"))

                ## select only data in the study region:
                vareuFull31 <- vareuFull31[, pos.imp.area.lon, pos.imp.area.lat]
                
                ## remove 29th of February:
                if(m == 2 && leap.year(y)) vareuFull31 <- vareuFull31[1:28,,]

                ## vareuFull31 format is: day x lon x lat [ndays, nlon, nlat]. We need to insert it into a bigger array: [nyears, ndays, nlat, nlon]
                ## add the data of the following month over the first dimension: (so new format is [365, nlon, nlat])
                if(m == 1) vareuFull365 <- vareuFull31 else vareuFull365 <- abind(vareuFull365, vareuFull31, along=1) 

                rm(vareuFull31)
            }

            ## add the data of the following year over the first dimension: (so final format is [36, 365, nlon, nlat]
            vareuFull[y - year.start + 1,,,] <- vareuFull365
            
            rm(vareuFull365)
            gc()
            
        } ## close for on y

        ## swap lat with lon so format is [36, 31, nlat, nlon]:
        vareuFull <- aperm(vareuFull, perm=c(1,2,4,3))

        ## insert two empty dims at the beginning to be consisten with the other case:
        vareuFull <- InsertDim(InsertDim(vareuFull, 1, 1), 1, 1)
        
    } ## close if on rean.impact.name

    if(var.name[var.num] == "prlr") vareuFull <- vareuFull * 3600000 * 24 # convert precipitation flow (m/s) to total precipitation (mm/day)
    if(var.name[var.num] == "psl")  vareuFull <- vareuFull / 100  # convert SLP in Pascal to SLP in hPa

    n.pos.imp.lon <- length(imp.area.lon)
    n.pos.imp.lat <- length(imp.area.lat)

    ## spatial resolution var dataset loaded:
    imp.res.lon <- abs(imp.area.lon[2] - imp.area.lon[1]) 
    imp.res.lat <- abs(imp.area.lat[2] - imp.area.lat[1]) ## can be slightly different from horizontal resolution (imp.res.lon)

    ## measure the corners of the impact figures to show the coordinates in the legend of the figure:
    ## (remember that coordinates are in degrees latitude North and longitude East):
    min.imp.lat <- min(imp.area.lat) - imp.res.lat/2
    max.imp.lat <- max(imp.area.lat) + imp.res.lat/2
    min.imp.lon <- min(imp.area.lon) - imp.res.lon/2
    max.imp.lon <- max(imp.area.lon) + imp.res.lon/2
    
    ## decide if the figure legend will be in degrees N o S, W o E:
    imp.area.lat.min.legend.letter <- ifelse(min.imp.lat >= 0, "N", "S")
    imp.area.lat.min.legend <- ifelse(min.imp.lat >= 0, min.imp.lat, -min.imp.lat)
    imp.area.lat.max.legend.letter <- ifelse(max.imp.lat >= 0, "N", "S")
    imp.area.lat.max.legend <- ifelse(max.imp.lat >= 0, max.imp.lat, -max.imp.lat)

    imp.area.lon.min.legend.letter <- ifelse(min.imp.lon <= 180, "E", "W")
    imp.area.lon.min.legend <- ifelse(min.imp.lon <= 180, min.imp.lon, 360 - min.imp.lon)
    imp.area.lon.max.legend.letter <- ifelse(max.imp.lon <= 180, "E", "W")
    imp.area.lon.max.legend <- ifelse(max.imp.lon <= 180, max.imp.lon, 360 - max.imp.lon)
        
    ## convert var in daily anomalies with the LOESS filter:
    cat("Calculating climatology. Please wait...\n")
    vareuFull_no_last_year <- vareuFull[1,1,1:n.years.clim,,,,drop=FALSE]
    varPeriodClim <- apply(vareuFull_no_last_year, c(1,2,4,5,6), mean, na.rm=T)
    rm(vareuFull_no_last_year)
    gc()

    cat("Applying LOESS filter. Please wait...\n")
    varPeriodClimLoess <- varPeriodClim
    for(i in 1:n.pos.imp.lat){
      for(j in 1:n.pos.imp.lon){
        my.data <- data.frame(ens.mean=rep(varPeriodClim[1,1,,i,j],3), day=1:(365*3))
        my.loess <- loess(ens.mean ~ day, my.data, span=my.span)
        varPeriodClimLoess[1,1,,i,j] <- predict(my.loess)[366:730]
      }
    }
    
    rm(varPeriodClim)
    gc()
    
    cat("Measuring anomalies. Please wait...\n")
    vareuFullClim <- InsertDim(varPeriodClimLoess, 3, n.years)

    ## measure anomalies: (notice that the last year is usually full of NA if the data is operational)
    vareuFullAnom <- vareuFull - vareuFullClim
    vareuFullAnomRel <- vareuFullAnom / vareuFullClim
    
    rm(vareuFullClim)
    gc()
    
} else { ## if subdaily == TRUE we work with 6-hourly wind speed instead of daily:

    ##rean <- '/esnas/recon/ecmwf/erainterim/6hourly/$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc'
    ##rean <- '/esnas/recon/jma/jra55/6hourly/$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc'

    vareuFull366 <- list()
    for(m in 1:12){
        if(m < 10) month.string <- paste0('0',m) else month.string <- m

        ## I had to swap 'obs' and 'exp' arguments between them, if not it doesn't recongnize the leadtimemax option:
        ## note that bisestile days are not loaded!!!
        vareuFull366[[m]] <-  Load(var = var.name[var.num], obs = NULL, exp = list(list(path=rean2load)), paste0(year.start:year.end, month.string, '01'), storefreq = 'daily', leadtimemax = n.days.in.a.period(m,2001)*4, output = 'lonlat', latmin = imp.area.lat.min, latmax = imp.area.lat.max, lonmin = imp.area.lon.min, lonmax = imp.area.lon.max, nprocs=ncores)        
    }

    vareuFull <- abind(vareuFull366[[1]]$mod, vareuFull366[[2]]$mod, vareuFull366[[3]]$mod, vareuFull366[[4]]$mod, vareuFull366[[5]]$mod, vareuFull366[[6]]$mod, vareuFull366[[7]]$mod, vareuFull366[[8]]$mod, vareuFull366[[9]]$mod, vareuFull366[[10]]$mod, vareuFull366[[11]]$mod, vareuFull366[[12]]$mod, along=4)
    
    imp.area.lon <- vareuFull366[[1]]$lon
    imp.area.lat <- vareuFull366[[1]]$lat

    if(var.name[var.num] == "prlr") vareuFull <- vareuFull*3600000*24 # convert precipitation flow (m/s) to total precipitation (mm/day)
    if(var.name[var.num] == "psl")  vareuFull <- vareuFull/100  # convert SLP in Pascal to SLP in hPa

    rm(vareuFull366)
    gc()
    
    n.pos.imp.lon <- length(imp.area.lon)
    n.pos.imp.lat <- length(imp.area.lat)
    
    ## spatial resolution var dataset loaded:
    imp.res.lon <- abs(imp.area.lon[2] - imp.area.lon[1]) 
    imp.res.lat <- abs(imp.area.lat[2] - imp.area.lat[1]) ## can be slightly different from horizontal resolution (imp.res.lon)

    ## measure the corners of the impact figures to show the coordinates in the legend of the figure:
    ## (remember that coordinates are in degrees latitude North and longitude East):
    min.imp.lat <- min(imp.area.lat) - imp.res.lat/2
    max.imp.lat <- max(imp.area.lat) + imp.res.lat/2
    min.imp.lon <- min(imp.area.lon) - imp.res.lon/2
    max.imp.lon <- max(imp.area.lon) + imp.res.lon/2
    
    ## decide if the figure legend will be in degrees N o S, W o E:
    imp.area.lat.min.legend.letter <- ifelse(min.imp.lat >= 0, "N", "S")
    imp.area.lat.min.legend <- ifelse(min.imp.lat >= 0, min.imp.lat, -min.imp.lat)
    imp.area.lat.max.legend.letter <- ifelse(max.imp.lat >= 0, "N", "S")
    imp.area.lat.max.legend <- ifelse(max.imp.lat >= 0, max.imp.lat, -max.imp.lat)

    imp.area.lon.min.legend.letter <- ifelse(min.imp.lon <= 180, "E", "W")
    imp.area.lon.min.legend <- ifelse(min.imp.lon <= 180, min.imp.lon, 360 - min.imp.lon)
    imp.area.lon.max.legend.letter <- ifelse(max.imp.lon <= 180, "E", "W")
    imp.area.lon.max.legend <- ifelse(max.imp.lon <= 180, max.imp.lon, 360 - max.imp.lon)
    
    ## convert var in daily anomalies with the LOESS filter:
    cat("Calculating anomalies. Please wait...\n")
    vareuFull_no_last_year <- vareuFull[1, 1, 1:n.years.clim,,,,drop=FALSE]
    varPeriodClim <- apply(vareuFull_no_last_year, c(1,2,4,5,6), mean, na.rm=TRUE) # mean over all years (fixed 6-hourly time step)
    ## command below is faster but it is not working in an interactive session!!!
    ## varPeriodClim <- Apply(vareuFull_no_last_year, margins=c(1,2,4,5,6), "mean", na.rm=TRUE, parallel=TRUE, ncores=availableCores()-1) 
    
    rm(vareuFull_no_last_year)
    gc()
    
    varPeriodClimLoess <- varPeriodClim
    
    for(i in 1:n.pos.imp.lat){
      for(j in 1:n.pos.imp.lon){
        my.seq1 <- seq(1, 365*4, 4)
        my.data1 <- data.frame(ens.mean=rep(varPeriodClim[1,1, my.seq1,i,j],3), hour=1:(365*3))
        my.loess1 <- loess(ens.mean ~ hour, my.data1, span=my.span)
        varPeriodClimLoess[1,1,my.seq1,i,j] <- predict(my.loess1)[366:730]

        my.seq2 <- my.seq1 + 1
        my.data2 <- data.frame(ens.mean=rep(varPeriodClim[1,1, my.seq2,i,j],3), hour=1:(365*3))
        my.loess2 <- loess(ens.mean ~ hour, my.data2, span=my.span)
        varPeriodClimLoess[1,1,my.seq2,i,j] <- predict(my.loess2)[366:730]

        my.seq3 <- my.seq1 + 2
        my.data3 <- data.frame(ens.mean=rep(varPeriodClim[1,1, my.seq3,i,j],3), hour=1:(365*3))
        my.loess3 <- loess(ens.mean ~ hour, my.data3, span=my.span)
        varPeriodClimLoess[1,1,my.seq3,i,j] <- predict(my.loess3)[366:730]

        my.seq4 <- my.seq1 + 3
        my.data4 <- data.frame(ens.mean=rep(varPeriodClim[1,1, my.seq4,i,j],3), hour=1:(365*3))
        my.loess4 <- loess(ens.mean ~ hour, my.data4, span=my.span)
        varPeriodClimLoess[1,1,my.seq4,i,j] <- predict(my.loess4)[366:730]
      }
    }
    
    rm(varPeriodClim, my.data1, my.data2, my.data3, my.data4, my.loess1, my.loess2, my.loess3, my.loess4)
    gc()
    
    vareuFullClim <- InsertDim(varPeriodClimLoess, 3, n.years)
    
    vareuFullAnom <- vareuFull - vareuFullClim
    vareuFullAnomRel <- vareuFullAnom / vareuFullClim
    
    ##rm(vareuFull)
    rm(varPeriodClimLoess, vareuFullClim)
    
    gc()
}

##
## Impact of WRs on var:
##
cat(paste0("Saving ", var.name[var.num]," data for each month and reanalysis. Please wait...\n"))
varwr <- varwrRel <- list()
area.orig <- area
for(p in period){
    ##p=1 # for the debug

    ## load regime data for chosen month:
    my.pos.period <- pos.period(1,p)
    if(subdaily) my.pos.period <- (4*pos.period(1,p)-3)[1]:(4*pos.period(1,p))[length(pos.period(1,p))]

    ## select only var data during the chosen period (month or season):
    varPeriod <- vareuFullAnom[1,1,, my.pos.period,,]
    varPeriodRel <-  vareuFullAnomRel[1,1,, my.pos.period,,] 

    ## re-set the working dir because the previous loop over p might have changed it:
    workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])

    ## load cluster data (my.cluster$cluster):
    if(area != "EU_CF") {
        load(file=paste0(workdir, "/", year.end,"_", my.period[p], "_psl.RData"))
    } else {
        my.cluster <- readRDS(paste0(rootdir,"/wr_erainterim_1981_2016_", my.period[p],".RDS"))[[1]]
        
        ## load lat and lon of Vero's cluster domain just once to check they are identical to lat and lon of my Euro-Atlantic cluster domain:
        ## (both proceed from ERA-Interim)
        lats.vero <-  readRDS(paste0(rootdir,"/lats_reanalysis.RDS"))
        lons.vero <-  readRDS(paste0(rootdir,"/lons_reanalysis.RDS"))
    }
    
    if(area != area.orig) area <- area.orig
          
    ## update the working directory, because the period could have changed after loading the .RData:
    workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])  
    dir.create(file.path(workdir))  # working dir where output files will be generated
    
    cluster.sequence <- as.vector(my.cluster$cluster)  # old syntax: my.cluster[[p]]$cluster
    if(subdaily) cluster.sequence <- rep(my.cluster$cluster, each=4) ## repeat 4 times the daily cluster series to create the 6-hourly cluster series

    wr <- list(); for(cl in 1:n.cl) wr[[cl]] <- which(cluster.sequence == cl)
    gc()

    if(fast.reshape){
        cat(paste0("Fast formatting ",var.name[var.num]," data for ",period.name[p],". Please wait...\n"))
        varmat <- array(aperm(varPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(varPeriod)[1] * dim(varPeriod)[2], dim(varPeriod)[3], dim(varPeriod)[4]))
        varmatRel <- array(aperm(varPeriodRel[,,,, drop=FALSE], c(2,1,3,4)), c(dim(varPeriodRel)[1] * dim(varPeriodRel)[2], dim(varPeriodRel)[3], dim(varPeriodRel)[4]))
    } else {
        cat(paste0("Formatting ",var.name[var.num]," data for ",period.name[p],". Please wait...\n"))
        var.melted <- melt(varPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon")) 
        var.meltedRel <- melt(varPeriodRel[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
        gc()
          
        cat(paste0("Formatting ",var.name[var.num]," data for ",period.name[p],". Please wait......\n"))
        varmat <- unname(acast(var.melted, Year + Day ~ Lat ~ Lon))
        varmatRel <- unname(acast(var.meltedRel, Year + Day ~ Lat ~ Lon))
    }
    
    if(detrend.var){ ##### remove var trend for the chosen period:
        cat(paste0("Detrending ",var.name[var.num]," data for ",period.name[p],". Please wait......\n"))
        
        daily.seq <- 1:dim(varmat)[1] # create a sequence from 1 to the number of years*days
        var.slope <- apply(varmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
        var.intercept <- apply(varmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
        
        varmat.detrended <- array(NA, c(dim(varmat)))
        for(t in daily.seq) varmat.detrended[t,,] <- varmat[t,,] - var.slope*t - var.intercept
        
        varmat <- varmat.detrended
        rm(varmat.detrended)
        gc()
        
        ## remove also the relative var trend for the chosen period:
        var.slopeRel <- apply(varmatRel, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
        var.interceptRel <- apply(varmatRel, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
        var.trendpvRel <- apply(varmatRel, c(2,3), function(x) MannKendall(x)$sl[1])  ## get trend pvalue at each point just to check if and where it is significant
        
        varmatRel.detrended <- array(NA, c(dim(varmatRel)))
        for(t in daily.seq) varmatRel.detrended[t,,] <- varmatRel[t,,] - var.slopeRel*t - var.interceptRel
        
        varmatRel <- varmatRel.detrended
        rm(varmatRel.detrended)
        gc()
        
        var.trendfullRel <- var.slopeRel * length(daily.seq) # same trend but expressed as change over the full study period

        ## save trend plot:
        file.trend.var <- paste0(workdir,"/",year.end,"_",my.period[p],"_trend_",var.name[var.num],".png")
        png(filename=file.trend.var, width=1500, height=1000)
        
        par(fig=c(0.01,0.99,0.10,0.95))
        PlotEquiMap(var.trendfullRel, imp.area.lon, imp.area.lat, filled.continents=FALSE, brks=my.brks.var, cols=my.cols.var, dots=var.trendpvRel < pval, drawleg=FALSE, toptitle=paste0(psl.name," trend (%) during ", period.name[p], " ", year.start, "-", year.end))
        
        par(fig=c(0,1,0,0.08), new=TRUE)
        
        ColorBar(brks=round(100*my.brks.var[2:(l(my.brks.var)-1)],0), cols=my.cols.var[2:(l(my.cols.var)-1)], vert=FALSE, label_scale=3, bar_limits=c(100*my.brks.var[2],100*my.brks.var[l(my.brks.var)-1]), col_inf=my.cols.var[1], col_sup=my.cols.var[l(my.cols.var)], subsample=2)
        
        dev.off()
        
    } ## close if on detrend.var
    
    varwr[[p]] <- list(); for(cl in 1:n.cl) varwr[[p]][[cl]] <- varmat[wr[[cl]],,,drop=F]
    varwrRel[[p]] <- list(); for(cl in 1:n.cl) varwrRel[[p]][[cl]] <- varmatRel[wr[[cl]],,,drop=F]
    
    ## average over all days and years of the chosen month (both days and years are stored in the first variable):
    varwrmean <- list(); for(cl in 1:n.cl) varwrmean[[cl]] <- apply(varwr[[p]][[cl]],c(2,3), mean, na.rm=T)
    varwrmeanRel <- list(); for(cl in 1:n.cl) varwrmeanRel[[cl]] <- apply(varwrRel[[p]][[cl]], c(2,3), mean, na.rm=T)
    
    ## measure p-value:
    mod.subdaily <- ifelse(subdaily, 4, 1)
    
    n.datos <- n.years * n.days.in.a.period(p,2001) * mod.subdaily 
    varwrBoth <- pvalue <- list()
    for(cl in 1:n.cl) {
        varwrBoth[[cl]] <- abind(varmat, varwr[[p]][[cl]], along = 1)
        pvalue[[cl]] <- apply(varwrBoth[[cl]], c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
        gc()
    }
    
    rm(varwrBoth)
    gc()
    
    ## save all the data necessary to redraw the graphs when we know the right regime (overwrite it if already present):
    ## (but you still need 'vareuFullAnom' for later)
    save(varwrmean, varwrmeanRel, pvalue, file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_", rean2load.name,".RData"))
    
    rm(pvalue, varwrmean, varwrmeanRel)
    gc()
    
} # close p on period

rm(var.melted, var.meltedRel, varPeriod, varPeriodClim, varPeriodRel, varPeriodClimLoess)
gc()


## load an observational dataset instead of a reanalysis and measure its impact maps:
if(stations){ ## not adjusted to employ subdaily var data!
    varstatFull <- array(NA, c(1,1, 50, 365, 161, 1)) ## 1x1x n.years x n.days x n.stations x 1
    
    for(st in 1:161){
        st2 <- paste0("00",st)
        st3 <-substr(st2,nchar(st2)-2, nchar(st2))
        
        ##input <- read.table(paste0("C:/Oliver/P_1940-2015/P_1940-2015_s",st3,".csv"), sep=";", stringsAsFactors=FALSE, header=TRUE)
        ##if(length(input$Value) == 0) input <- read.table(paste0("C:/Oliver/P_1940-2015/P_1940-2015_s",st3,".csv"), sep=",", stringsAsFactors=FALSE, header=TRUE)
        
        input <- read.table(paste0(station.data.dir, "/P_1940-2015/P_1940-2015_s",st3,".csv"), sep=";", stringsAsFactors=FALSE, header=TRUE)
        if(length(input$Value) == 0) input <- read.table(paste0(station.data.dir, "/P_1940-2015/P_1940-2015_s",st3,".csv"), sep=",", stringsAsFactors=FALSE, header=TRUE)
        
        if(substr(input$Date[1], 5, 5) == "-"){ # in this case, the year is at the BEGINNING of the string and month in the MIDDLE and the day at the END
            
            ## remove rows with 29th of february
            bisest <- which(substr(input$Date, 6, 10) == "02-29")
            input2 <- input[-bisest,]
            
            ## remove data before 1966:
            before <- which(substr(input2$Date, 1,4) < 1966)
            input3 <- input2[-before,]
            
            ## remove data after 2015:
            after <- which(substr(input3$Date, 1,4) > 2015)
            
            if(length(after) > 0) input3 <- input3[-after,]
            
        } else { ## in this case, the year is at the END of the string, the month in the MIDDLE and the day at the BEGINNING
            
            ## remove rows with 29th of february
            bisest <- which(substr(input$Date, 1, 5) == "29-02")
            input2 <- input[-bisest,]
            
            ## remove data before 1966:
            before <- which(substr(input2$Date, 7,10) < 1966)
            input3 <- input2[-before,]
            
            ## remove data after 2015:
            after <- which(substr(input3$Date, 7,10) > 2015)
            
            if(length(after) > 0) input3 <- input3[-after,]
        }
        
        varstatFull[1,1,,, st,1] <- as.numeric(input3$Value)
        
        ## convert NA on 0's:
        ss <- which(is.na(varstatFull))
        varstatFull[ss] <- 0
        
    } ## close for on st
    
    ## convert var in daily anomalies with the LOESS filter:
    cat("Calculating anomalies. Please wait...\n")
    varstatPeriodClim <- apply(varstatFull, c(1,2,4,5,6), mean, na.rm=T)
    
    varstatPeriodClimLoess <- varstatPeriodClim
    
    for(i in 1:161){
        my.data <- data.frame(ens.mean=rep(varstatPeriodClim[1,1,,i,1],3), day=1:(365*3))
        my.loess <- loess(ens.mean ~ day, my.data, span=my.span)
        varstatPeriodClimLoess[1,1,,i,1] <- predict(my.loess)[366:730]      
    }
    
    rm(varstatPeriodClim)
    gc()
    
    library(s2dverification)
    varstatFullClim <- InsertDim(varstatPeriodClimLoess, 3, 50)
    
    varstatFullAnom <- varstatFull - varstatFullClim
    ##varstatFullAnomRel <- varstatFullAnom / varstatFullClim
    
    rm(varstatFull)
    gc()
    
    ## Load lat & lon stations:    
    my.stations <- read.table(paste0(station.data.dir, "/P_1940-2015.est"), sep=" ", stringsAsFactors=FALSE, header=FALSE)
        
    for(p in period){
        ##p=1 # for the debug
        
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])   # set the workding dir because the previous loop over p changed it
        load(file=paste0(workdir, "/", year.end,"_", my.period[p], "_psl.RData"))
        
        ## update the working directory, because the period could have changed:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        dir.create(file.path(workdir))
        
        cluster.sequence <- my.cluster$cluster  # old syntax: my.cluster[[p]]$cluster
        
        seasonal.data <- ifelse(length(my.cluster$cluster)/n.years > 33, TRUE, FALSE) # if there are more than 33 days, it means that we are loading sequences of 3 months
        
        if(seasonal.data == TRUE && p < 13){ # select only the days of the 3-months cluster series inside the target month p
            n.days.period <- length(pos.month.extended(2001,p))  # total number of days in the three months
            
            days.month <- days.month.new <- days.month.full <- c()
            days.month <- which(pos.month.extended(2001,p) == pos.month(2001,p)[1])-1 + 1:length(pos.month(2001,p))
            
            for(y in 1:n.years){
                days.month.new <- days.month + n.days.period*(y-1)
                days.month.full <- c(days.month.full, days.month.new)
            }
            
            cluster.sequence <- my.cluster$cluster[days.month.full] # select only the days of the cluster series inside the target month p
        }
        
        wr <- list()
        
        for(cl in 1:n.cl) wr[[cl]] <- which(cluster.sequence == cl)
        gc()
        
        ## load regime data for chosen month:
        varstatPeriod <- varstatFullAnom[1,1,, my.pos.period,,,drop=FALSE] # select only var data during the chosen period
        varstatPeriodClim <- varstatFullClim[1,1,, my.pos.period,,,drop=FALSE]
        varstatPeriodRel <- varstatPeriod / varstatPeriodClim  ## some NA area created because some varstatPeriodClim data are 0's
        
        cat(paste0("Formatting ", var.name[var.num]," data. Please wait...\n"))
        varstatPeriod <- InsertDim(varstatPeriod[1,1,,,,],4,1)
        varstatPeriodRel <- InsertDim(varstatPeriodRel[1,1,,,,],4,1)
        
        varstat.melted <- melt(varstatPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon")) 
        varstat.meltedRel <- melt(varstatPeriodRel[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
        gc()
        
        cat(paste0("Formatting ", var.name[var.num]," data. Please wait......\n"))
        varstatmat <- unname(acast(varstat.melted, Year + Day ~ Lat ~ Lon))
        varstatmatRel <- unname(acast(varstat.meltedRel, Year + Day ~ Lat ~ Lon))
        
        if(detrend.var){ ##### remove varstat trend for the chosen period:
            daily.seq <- 1:dim(varstatmat)[1] # create a sequence from 1 to the number of years*days
            varstat.slope <- apply(varstatmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            varstat.intercept <- apply(varstatmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            varstat.trendpv <- apply(varstatmat, c(2,3), function(x) MannKendall(x)$sl[1])  ## get trend pvalue at each point just to check if and where it is significant
            ## (it gives a warning because series number 16 is full of 0s)
            
            varstat.trendfull <- varstat.slope * length(daily.seq) # same trend but expressed as change over the full study period
            
            varstatmat.detrended <- array(NA, c(dim(varstatmat)))
            for(t in daily.seq){
                varstatmat.detrended[t,,] <- varstatmat[t,,] - varstat.slope*t - varstat.intercept
            }
            
            varstatmat <- varstatmat.detrended
            rm(varstatmat.detrended)
            gc()
            
            ## remove also the relative var trend for the chosen period:
            
            varstatmatRel2 <- varstatmatRel  
            varstatmatRel2[which(is.na(varstatmatRel))] <- 0 ## remove NA due to climatology being 0 by setting them to 0 too
            
            varstat.slopeRel <- apply(varstatmatRel2, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            varstat.interceptRel <- apply(varstatmatRel2, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            varstat.trendpvRel <- apply(varstatmatRel2, c(2,3), function(x) MannKendall(x)$sl[1])  ## get trend pvalue at each point just to check if and where it is significant
            varstat.trendfullRel <- varstat.slopeRel * length(daily.seq) # same trend but expressed as change over the full study period
            
            varstatmatRel.detrended <- array(NA, c(dim(varstatmatRel)))
            for(t in daily.seq){
                varstatmatRel.detrended[t,,] <- varstatmatRel[t,,] - varstat.slopeRel*t - varstat.interceptRel
            }
            
            varstatmatRel <- varstatmatRel.detrended
            rm(varstatmatRel.detrended)
            gc()
            
        } 
        
        varstatwr <- list()
        for(cl in 1:n.cl) varstatwr[[cl]] <- varstatmat[wr[[cl]],,,drop=F]
        
        varstatwrRel <- list()
        for(cl in 1:n.cl) varstatwrRel[[cl]] <- varstatmatRel[wr[[cl]],,,drop=F]
        
        varstatwrmean <- list()
        for(cl in 1:n.cl) varstatwrmean[[cl]] <- apply(varstatwr[[cl]],c(2,3), mean, na.rm=T)
        
        varstatwrmeanRel <- list()
        for(cl in 1:n.cl) varstatwrmeanRel[[cl]] <- apply(varstatwrRel[[cl]], c(2,3), mean, na.rm=T)
        
        n.datos <- n.years * n.days.in.a.period(p,2001)
        
        varstatwrBoth <- pstatvalue <- list()
        for(cl in 1:n.cl) {
            varstatwrBoth[[cl]] <- abind(varstatmat, varstatwr[[cl]], along = 1)
            pstatvalue[[cl]] <- apply(varstatwrBoth[[cl]], c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
            gc()
        }
        
        rm(varstatwrBoth, varstatwr)
        rm(varstatmat, varstatmatRel)
        gc()
        
        ## save all the data necessary to redraw the graphs when we know the right regime:
        save(varstatwrmean, pstatvalue, varstatwrmeanRel, file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_stations.RData"))
        
        rm(pstatvalue)
        rm(varstatwrmean)
        gc()
        
    } # close p on period
    
    rm(varstat.melted, varstat.meltedRel, varstatPeriod, varstatPeriodClim, varstatPeriodRel, varstatPeriodClimLoess)
    gc()
    
} ## end if on stations

#########################################################################################
#                      Load slp data and convert it to anomalies                        #
#########################################################################################
cat("Loading slp data. Please wait...\n")
  
## measure climatology and anomalies (with LOESS filter) for psl data for bigarea domain, and draw monthly psl anomalies maps:
data2show <-  Load(var = psl, exp = NULL, obs = list(list(path=rean)), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax = 366, output = 'lonlat', latmin = bigarea.lat.min, latmax = bigarea.lat.max, lonmin = bigarea.lon.min, lonmax = bigarea.lon.max, nprocs=ncores)

slp366 <- data2show$obs

bigarea.lon <- data2show$lon
bigarea.lat <- data2show$lat

## spatial resolution psl dataset loaded:
psl.res.lon <- abs(bigarea.lon[2] - bigarea.lon[1]) 
psl.res.lat <- abs(bigarea.lat[2] - bigarea.lat[1]) ## can be slightly different from horizontal resolution (psl.res.lon)

## four corners of the psl figures (remember that coordinates are in degrees latitude North and longitude East):
min.psl.lat <- min(bigarea.lat) - psl.res.lat/2
max.psl.lat <- max(bigarea.lat) + psl.res.lat/2
min.psl.lon <- min(bigarea.lon) - psl.res.lon/2
max.psl.lon <- max(bigarea.lon) + psl.res.lon/2

## notation for figure captions of regime anomalies:
lat.min.legend.letter <- ifelse(min.psl.lat >= 0, "N", "S")
lat.min.legend <- ifelse(min.psl.lat >= 0, min.psl.lat, -min.psl.lat)
lat.max.legend.letter <- ifelse(max.psl.lat >= 0, "N", "S")
lat.max.legend <- ifelse(max.psl.lat >= 0, max.psl.lat, -max.psl.lat)

lon.min.legend.letter <- ifelse(min.psl.lon <= 180, "E", "W")
lon.min.legend <- ifelse(min.psl.lon <= 180, min.psl.lon, 360 - min.psl.lon)
lon.max.legend.letter <- ifelse(max.psl.lon <= 180, "E", "W")
lon.max.legend <- ifelse(max.psl.lon <= 180, max.psl.lon, 360 - max.psl.lon)

rm(data2show)
gc()

cat("Converting slp into anomalies. Please wait...\n")

slp <- slp366[,,,1:365,,]
for(y in year.start:year.end){
    y2 <- y - year.start + 1
    if(n.days.in.a.year(y) == 366) slp[y2,60:365,,] <- slp366[1,1,y2,61:366,,] # take the march to december period removing the 29th of February
}

rm(slp366)
gc()

slp2 <- slp[1:n.years.clim,,,,drop=FALSE]
slpClimDaily <- apply(slp2, c(2,3,4), mean, na.rm=T)   ## compare it to system.time({slpClimDaily <- Apply(slp, c(2,3,4), "mean", na.rm=T, parallel=TRUE)})
rm(slp2)

## Measure slp climatology with LOESS filter:
slpClimLoess <- slpClimDaily

bigarea.n.pos.lat <- dim(slpClimDaily)[2]
bigarea.n.pos.lon <- dim(slpClimDaily)[3]

for(i in 1:bigarea.n.pos.lat){
    for(j in 1:bigarea.n.pos.lon){
        my.data <- data.frame(ens.mean=rep(slpClimDaily[,i,j],3), day=1:(365*3))
        my.loess <- loess(ens.mean ~ day, my.data, span=my.span)
        slpClimLoess[,i,j] <- predict(my.loess)[366:730]
    }
}

rm(slpClimDaily)
gc()

slpClim2 <- InsertDim(slpClimLoess, 1, n.years)
slpAnom <- slp - slpClim2

rm(slpClimLoess)
rm(slpClim2)
gc()

if(psl == "g500" || psl == "g250") { slpAnom <- slpAnom/9.81; slp <- slp/9.81 }   # convert geopotential to geopotential height (in m)
if(psl == "psl") { slpAnom <- slpAnom/100; slp <- slp/100 }   # convert MSLP in Pascal to MSLP in hPa

#########################################################################################
#          Create anomalies maps for a particular year and month (and regime)           #
#########################################################################################

## save all monthly anomaly maps and regime maps for last year only:
if(figures.last){    
    period.orig <- period
    for(p in period){
        ##year.test <- 2017; p <- 3 # for the debug
        print(paste0("Generating anomaly maps for ", period.name[p],". Please wait..."))

        pos.year.test <- year.end - year.start + 1

        my.pos.period <- pos.period(1,p)
        if(subdaily) my.pos.period <- (4*pos.period(1,p)-3)[1]:(4*pos.period(1,p))[length(pos.period(1,p))]

        varPeriod <- vareuFullAnom[1,1,, my.pos.period,,] # select only var data during the chosen period (for all years)
        varPeriodRel <- vareuFullAnomRel[1,1,, my.pos.period,,] # select only var data during the chosen period (for all years)

        ##varPeriodClim <- vareuFullClim[1,1,, my.pos.period,,]
        ##varPeriodRel <- varPeriod / varPeriodClim

        if(fast.reshape){
            cat(paste0("Fast formatting ", var.name[var.num]," data. Please wait...\n"))
            varmat <- array(aperm(varPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(varPeriod)[1] * dim(varPeriod)[2], dim(varPeriod)[3], dim(varPeriod)[4]))
            varmatRel <- array(aperm(varPeriodRel[,,,, drop=FALSE], c(2,1,3,4)), c(dim(varPeriodRel)[1] * dim(varPeriodRel)[2], dim(varPeriodRel)[3], dim(varPeriodRel)[4]))
        } else {   
            cat(paste0("Formatting ", var.name[var.num]," data. Please wait...\n"))
            var.melted <- melt(varPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon")) 
            var.meltedRel <- melt(varPeriodRel[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
            gc()
            
            cat(paste0("Formatting ", var.name[var.num]," data. Please wait......\n"))
            varmat <- unname(acast(var.melted, Year + Day ~ Lat ~ Lon))
            varmatRel <- unname(acast(var.meltedRel, Year + Day ~ Lat ~ Lon))
        }

        ## get trend pvalue of var anomalies at each point:
        ## var.trendpvRel <- apply(varmatRel, c(2,3), function(x) MannKendall(x)$sl[1])

        if(detrend.var){
            cat(paste0("Detrending ",var.name[var.num]," data for ",period.name[p],". Please wait......\n"))
            
            daily.seq <- 1:dim(varmat)[1] # create a sequence from 1 to the number of years*days
            var.slope <- apply(varmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            var.intercept <- apply(varmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            varmat.detrended <- array(NA, c(dim(varmat)))
            for(t in daily.seq) varmat.detrended[t,,] <- varmat[t,,] - var.slope*t - var.intercept

            varmat <- varmat.detrended
            rm(varmat.detrended)
            gc()
            
            ## remove also the relative var trend for the chosen period:
            var.slopeRel <- apply(varmatRel, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            var.interceptRel <- apply(varmatRel, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            varmatRel.detrended <- array(NA, c(dim(varmatRel)))
            for(t in daily.seq){
                varmatRel.detrended[t,,] <- varmatRel[t,,] - var.slopeRel*t - var.interceptRel
            }
            
            varmatRel <- varmatRel.detrended
            rm(varmatRel.detrended)
            gc()

            ## select only days of the chosen year :
            chosen.daily.seq <- (pos.year.test - 1) * n.days.in.a.period(p,2001) + 1:n.days.in.a.period(p,2001)

            sfcWindAnomPeriod <- varmat[chosen.daily.seq,,]
            sfcWindAnomPeriodRel <- varmatRel[chosen.daily.seq,,]
            
        } else {
            sfcWindAnomPeriod <- vareuFullAnom[1,1,pos.year.test, my.pos.period,,]
            sfcWindAnomPeriodRel <- vareuFullAnomRel[1,1,pos.year.test, my.pos.period,,]
        }
        
        ## wind anomaly to Relative var data only for the chosen year and month:
        if(impact.last) sfcWindAnomPeriodMean <- apply(sfcWindAnomPeriodRel, c(2,3), mean, na.rm=TRUE) ## do not measure it if last year var data is not available
        
        if(detrend.psl){
            slpAnomPeriod <- slpAnom[, my.pos.period,,]
            
            slpAnomPeriod.melted <- melt(slpAnomPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
            slpAnomPeriod.kmeans <- unname(acast(slpAnomPeriod.melted, Year + Day ~ Lat ~ Lon))
            gc()
            
            daily.seq <- 1:dim(slpAnomPeriod.kmeans)[1] # create a sequence from 1 to the number of years*days
            slp.slope <- apply(slpAnomPeriod.kmeans, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
            slp.intercept <- apply(slpAnomPeriod.kmeans, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
            
            slpAnomPeriod.detrended <- array(NA, c(dim(slpAnomPeriod.kmeans)))
            for(t in daily.seq) slpAnomPeriod.detrended[t,,] <- slpAnomPeriod.kmeans[t,,] - slp.slope*t - slp.intercept
            
            slpAnomPeriod <- slpAnomPeriod.detrended
            rm(slpAnomPeriod.detrended)
            gc()
            
            ## re-define slpAnomPeriod to be only the psl anomaly of a chosen month and year:
            chosen.daily.seq <- (pos.year.test-1)*n.days.in.a.period(p,2001) + 1:n.days.in.a.period(p,2001)
            
            slpAnomPeriod <- slpAnomPeriod[chosen.daily.seq,,]

            ## same detrending but for cluster var (i.e: SLP) not in anomalies: (using the same trend coefficients measured above for the anomalies)
            slpPeriod <- slp[, my.pos.period,,]
            
            slpPeriod.melted <- melt(slpPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
            slpPeriod.kmeans <- unname(acast(slpPeriod.melted, Year + Day ~ Lat ~ Lon))
            gc()
            
            slpPeriod.detrended <- array(NA, c(dim(slpPeriod.kmeans)))
            for(t in daily.seq) slpPeriod.detrended[t,,] <- slpPeriod.kmeans[t,,] - slp.slope*t - slp.intercept
            
            slpPeriod <- slpPeriod.detrended
            rm(slpPeriod.detrended)
            gc()
            
            ## re-define slpPeriod to be only the psl anomaly of a chosen month and year:      
            slpPeriod <- slpPeriod[chosen.daily.seq,,]  
            
        } else {
            slpAnomPeriod <- slpAnom[pos.year.test, my.pos.period,,]
            slpPeriod <- slp[pos.year.test, my.pos.period,,]
        }
        
        ## psl anomaly for the chosen year and month:
        slpAnomPeriodMean <- apply(slpAnomPeriod, c(2,3), mean, na.rm=TRUE)
        slpPeriodMean <- apply(slpPeriod, c(2,3), mean, na.rm=TRUE)

        ## update the working directory, because the period could have changed:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        dir.create(file.path(workdir))

        ##
        ## Maps of the observed monthly wind speed and/or SLP anomalies for chosen month and year
        ##

        ## type of different figures to create for the report: wind speed only ("var"), SLP only ("psl") or both: 
        if(impact.last) my.figures <-  c("psl", "var", "both") else my.figures <- "psl" ## you only save psl figure for last year if impact.last == FALSE ('var' is not avilable)
        if(impact.last) my.figures.name <-  c(psl.name, var.name[var.num], paste0(var.name[var.num], "_and_", psl.name)) else my.figures.name <- psl.name
        if(impact.last && report.type == "second"){  ## in this case, we only want to generate the figure with sfcWind + SLP monthly anom. for ERA-Int + JRA-55
            my.figures <- "both"
            my.figures.name <-  paste0(var.name[var.num], "_and_", psl.name,"_second_report")
        }
        
        for(f in my.figures){ ## loop on the needed figures
            
            f.name <- my.figures.name[which(f == my.figures)]
            fileoutput <- paste0(workdir,"/",year.end,"_",my.period[p],"_anomalies_unformatted_", f.name,".png")

            if(f == "both") png(filename=fileoutput,width=1800, height=700)
            if(f == "psl") png(filename=fileoutput,width=2000, height=1000)
            if(f == "var") png(filename=fileoutput,width=1500, height=1000)

            if(p == period[1]) op <- par(no.readonly = TRUE)  ## reset par to its default values, because drawing with PlotEquiMap() alters some par values:

            plot.new()
            
            if(f != "psl"){
                if(f == "both") par(fig=c(0, end.map, 0.11, 0.98), new=TRUE)
                if(f == "var") par(fig=c(0.05, 0.95, 0.08, 0.98), new=TRUE)

                ## impact map:
                PlotEquiMap(sfcWindAnomPeriodMean, imp.area.lon, imp.area.lat, filled.continents=FALSE, brks=my.brks.var, cols=my.cols.var, title_scale=1.2, intxlon=10, intylat=10, drawleg=F) #, cex.lab=1.5)
                
                if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/2, col=wind.color, pch=farms.style, lwd=4)
                
                if(f == "both") par(fig=c(0.01, end.map, 0.00, 0.13), new=TRUE)
                if(f == "var") par(fig=c(0.16, 0.83, 0.00, 0.1), new=TRUE)
                
                ColorBar(brks=round(100*my.brks.var[2:(l(my.brks.var)-1)],0), cols=my.cols.var[2:(l(my.cols.var)-1)], vert=FALSE, label_scale=3, bar_limits=c(100*my.brks.var[2],100*my.brks.var[l(my.brks.var)-1]), col_inf=my.cols.var[1], col_sup=my.cols.var[l(my.cols.var)], subsample=2)
                
                if(f == "both") par(fig=c(end.map - 0.01, end.map, 0, 0.03), new=TRUE)
                if(f == "var") par(fig=c(0.81, 0.82, 0, 0.025), new=TRUE)
                mtext("%", cex=2)
            }
            
            if(f != "var"){    
                ## plot regime anomalies (structures):
                if(f == "both") par(fig=c(end.map + 0.01, 0.99, 0.135, 0.98), new=TRUE)
                if(f == "psl") par(fig=c(0.10, 0.89, 0.1, 0.98), new=TRUE)
                
                PlotEquiMap2(slpAnomPeriodMean, bigarea.lon, bigarea.lat, filled.continents=FALSE, continents.col="black", brks=my.brks, brks2=my.brks, cols=my.cols, intxlon=10, intylat=10, drawleg=F, contours=t(slpAnomPeriodMean), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=0.7)
                if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/2, col=wind.color, pch=farms.style, lwd=4)

                par(op) # reset par parameters
                
                if(f == "both") par(fig=c(end.map + 0.02, 0.99, 0, 0.13), new=TRUE)
                if(f == "psl") par(fig=c(0.13, 0.87, 0, 0.1), new=TRUE)    

                ColorBar(brks=my.brks[2:(l(my.brks)-1)], cols=my.cols[2:(l(my.cols)-1)], vert=FALSE, label_scale=3, bar_limits=c(my.brks[2],my.brks[l(my.brks)-1]), col_inf=my.cols[1], col_sup=my.cols[l(my.cols)], subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
                
                if(f == "both") par(fig=c(0.965, 1, 0, 0.105), new=TRUE)
                if(f == "psl") par(fig=c(0.83, 0.87, 0, 0.075), new=TRUE)

                mtext(psl.unit, cex=2.5)

            } ## close if on f

            dev.off()
            
            ## same image formatted for the catalogue:
            cat("Converting monthly anomaly maps to catalogue format. Please wait...\n")
            
            fileoutput2 <- paste0(workdir,"/",year.end,"_",my.period[p],"_anomalies_",f.name,".png")
            
            if(two.rean && f == "both") { dataset.string <- paste0(rean.impact.name," reanalysis (left); ", rean.name, " reanalysis (right)")}
            if(f == "psl") { dataset.string <- paste0(rean.name," reanalysis")}
            if(f == "var") { dataset.string <- paste0(rean2load.name," reanalysis")}

            region.string.psl <- paste0(bigarea.name," (", round(lat.min.legend,2), deg, lat.min.legend.letter,"-", round(lat.max.legend,2), deg, lat.max.legend.letter,", ", round(lon.min.legend,2), deg, lon.min.legend.letter,"-", round(lon.max.legend,2), deg, lon.max.legend.letter,")")
            
            region.string.var <- paste0(imp.area.name," (",round(imp.area.lat.min.legend,2), deg, imp.area.lat.min.legend.letter,"-", round(imp.area.lat.max.legend,2), deg, imp.area.lat.max.legend.letter,", ", round(imp.area.lon.min.legend,2), deg, imp.area.lon.min.legend.letter,"-", round(imp.area.lon.max.legend,2), deg, imp.area.lon.max.legend.letter,").")
            
            mod.space <- ""
            if(f == "psl") { mod.space <- "            "; my.region.string <- paste0(mod.space, "Region: ",region.string.psl); var.title <- psl.name.full }
            if(f == "var") { mod.space <- "            "; my.region.string <- paste0(mod.space, "Region: ",region.string.var); var.title <- var.name.full[var.num] }
            if(f == "both"){ my.region.string <- paste0(mod.space, "Region. Left: ", region.string.var," Right: ", region.string.psl); var.title <- paste0(var.name.full[var.num]," and ", psl.name.full)}

            mod.size <- 0.74
            if(f == "both") mod.size <- 0.66

            ## format figure for ESS catalogue:
            system(paste0(fig2catalog.dir,"/fig2catalog.sh -s ",mod.size," -t '",rean.name," / ", var.title," / Monthly anomalies \n", period.name[p]," / ",year.end,"' -c '", my.region.string,"\n", mod.space,"Reference dataset: ", dataset.string,"' ", fileoutput, " ", fileoutput2))
            
            system(paste0("rm ", fileoutput))

        } ## close for on f

        ##
        ## Same map as before (with both 'var' and 'psl') but with SLP not in anomalies:
        ## (in future, update to show also wind speed not in anomalies and maybe to run in the previous loop)
        ##
        fileoutput.no.anom <- paste0(workdir,"/",year.end,"_",my.period[p],"_no_anomalies.png")
        png(filename=fileoutput.no.anom,width=2800, height=1000)    
        if(p == period[1]) { op <- par(no.readonly = TRUE) } ## reset par to its default values, because drawing with PlotEquiMap() alters some par values:
        par(fig=c(0, end.map, 0.08, 0.98), new=TRUE)
        if(impact.last) PlotEquiMap2(sfcWindAnomPeriodMean, imp.area.lon, imp.area.lat, filled.continents=FALSE, brks=my.brks.var, cols=my.cols.var, title_scale=1.2, intxlon=10, intylat=10, drawleg=F, countries=my.countries) #, cex.lab=1.5)
        
        par(fig=c(0.01, end.map, 0.00, 0.1), new=TRUE)
        ColorBar(brks=round(100*my.brks.var[2:(l(my.brks.var)-1)],0), cols=my.cols.var[2:(l(my.cols.var)-1)], vert=FALSE, label_scale=3, bar_limits=c(100*my.brks.var[2],100*my.brks.var[l(my.brks.var)-1]), col_inf=my.cols.var[1], col_sup=my.cols.var[l(my.cols.var)], subsample=2)
        par(fig=c(end.map - 0.01, end.map, 0, 0.025), new=TRUE); mtext("%", cex=2)
        par(fig=c(end.map + 0.01, 0.99, 0.1, 0.98), new=TRUE)        
        PlotEquiMap2(slpPeriodMean, bigarea.lon, bigarea.lat, filled.continents=FALSE, continents.col="black", brks=my.brks.no.anom, brks2=my.brks.no.anom, cols=my.cols.no.anom, intxlon=10, intylat=10, drawleg=F, contours=t(slpPeriodMean), cex.lab=1, countries=my.countries)
        
        par(op); par(fig=c(end.map + 0.02, 0.99, 0, 0.1), new=TRUE)    
        ColorBar(brks=my.brks.no.anom[2:(length(my.brks.no.anom)-1)], cols=my.cols.no.anom[2:(length(my.cols.no.anom)-1)], vert=FALSE, label_scale=3, bar_limits=c(my.brks.no.anom[2],my.brks.no.anom[length(my.brks.no.anom)-1]), col_inf=my.cols.no.anom[1], col_sup=my.cols.no.anom[length(my.cols.no.anom)], subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
        par(fig=c(0.965, 1, 0, 0.075), new=TRUE); mtext(psl.unit, cex=2)
        dev.off()

        ##
        ## save values of observed monthly wind speed anomalies and pressure anomalies for last year in a txt file:
        ##
        if(save.txt && impact.last){
            cat(paste0("Saving monthly ", var.name[var.num]," and ", psl.name," anomalies. Please wait...\n"))

            dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos")))          ## create dir, if it doesn't exist yet:
            
            ## save wind anomalies for last year:
            dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figure_1")))  ## create subdir, if it doesn't exist yet:
            dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figure_1/Report")))  ## create subdir, if it doesn't exist yet:
            dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figure_1/Anexo")))  ## create subdir, if it doesn't exist yet:
            
            sfcWindAnomEDPR <- unname(sfcWindAnomPeriodMean)
            
            write.table(round(100*sfcWindAnomEDPR,1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figure_1/Report/", year.end,"_",my.period[p],"_", gsub(" ", "_", var.name.full[var.num]),"_relative_anomalies_", rean2load.name,".txt"), row.names=round(unname(imp.area.lat),2), col.names=c(paste0("Lat/Lon\t", round(imp.area.lon[1],2)), as.numeric(round(imp.area.lon[-1],2))), sep="\t", quote=FALSE)    
            
            ## save psl anomalies for last year:
            slpAnomEDPR <- unname(slpAnomPeriodMean)

            write.table(round(slpAnomEDPR,1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figure_1/Anexo/", year.end,"_",my.period[p],"_", psl.name,"_anomalies_",rean.name,".txt"), row.names=round(bigarea.lat,2), col.names=c(paste0("Lat/Lon\t", round(bigarea.lon[1],2)), as.numeric(round(bigarea.lon[-1],2))), sep="\t", quote=FALSE)

            ## save extra data for EDPR (daily absolute values of SLP and sfcWind for the target month and year):
            ## SLP is in hPa, the same unit uf measure used in the figures, while wind speed is in m/s.
            wind.daily4EDPR <- unname(vareuFull[1,1,pos.year.test, my.pos.period,,])
            slp.daily4EDPR <- unname(slp[pos.year.test, my.pos.period,,])

            ## save original data:
            dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Daily_values_", rean2load.name)))
            
            for(d in 1:n.days.in.a.period(p, 2001)){
                ## wind data:
                write.table(round(wind.daily4EDPR[d,,],1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Daily_values_", rean2load.name, "/", year.end,"_",my.period[p],"_", gsub(" ", "_", var.name.full[var.num]),"_", rean2load.name,"_day_",d,".txt"), row.names=round(imp.area.lat,2), col.names=c(paste0("Lat/Lon\t", round(imp.area.lon[1],2)), as.numeric(round(imp.area.lon[-1],2))), sep="\t", quote=FALSE)
                ## SLP data:
                write.table(round(slp.daily4EDPR[d,,],1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Daily_values_", rean2load.name, "/", year.end,"_",my.period[p],"_", psl.name,"_",rean.name,"_day_",d,".txt"), row.names=round(bigarea.lat,2), col.names=c(paste0("Lat/Lon\t", round(bigarea.lon[1],2)), as.numeric(round(bigarea.lon[-1],2))), sep="\t", quote=FALSE)    

            }
            
            rm(sfcWindAnomEDPR, slpAnomEDPR, wind.daily4EDPR, slp.daily4EDPR)
            
            if(area == "EU"){
                ## All these values still use the old lon lat variables instead of the new imp.area.lon and imp.area.lat variab, so intervals 88:135 and 1:37 must be adjusted:
                ## ## save wind anomalies:
                ## sfcWindAnomEDPR <- unname(abind(sfcWindAnomPeriodMean[,88:105],sfcWindAnomPeriodMean[,1:37], along=2))
                ## lonEDPR <- c(lon[88:105]-360, lon[1:37])
                ## write.table(round(100*sfcWindAnomEDPR,1), file=paste0(workdir, "/",year.end,"_",my.period[p],"_wind_speed_relative_anomalies.txt"), row.names=bigarea.lat, col.names=c(paste0("Lat/Lon\t",lonEDPR[1]), as.numeric(round(lonEDPR[-1],2))), sep="\t", quote=FALSE)    
                
                ## ## save slp anomalies:
                ## slpAnomEDPR <- unname(abind(slpAnomPeriodMean[,38:105],slpAnomPeriodMean[,1:37], along=2))
                ## lonfullEDPR <- c(lon[38:105]-360, lon[1:37])
                ## write.table(round(slpAnomEDPR,1), file=paste0(workdir, "/",year.end,"_",my.period[p],"_slp_anomalies.txt"), row.names=lat, col.names=c(paste0("Lat/Lon\t",lonfullEDPR[1]), as.numeric(round(lonfullEDPR[-1],2))), sep="\t", quote=FALSE)
                
            }

        }

        ##
        ## For each regime, plot the maps with its observed impact on monthly wind speed and SLP anomalies for last month only
        ##
        cat(paste0("Generating regime figures for year ", year.end," and period ", period.name[p],". Please wait...\n"))

        ## mean wind speed and slp anomaly only during days of the chosen year:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # set the workding dir because the previous loop over p changed it
        
        load(paste0(workdir,"/",year.end,"_",my.period[p],"_psl.RData")) # load cluster.sequence
        
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
        if(!identical(period, period.orig)) period <- period.orig
        
        ## arrange the regime sequence in an array, to separate months from years:
        cluster2D <- array(cluster.sequence, c(n.days.in.a.period(p,1), n.years))
        ##cluster2D <- array(my.cluster$cluster, c(n.days.in.a.period(p,1),n.years)) # only for NCEP

        ## select days only belonging to the test year:
        cluster.test <- cluster2D[, pos.year.test]
        
        fre.days <- c(); for(cl in 1:n.cl) fre.days[cl] <- length(which(cluster.test == cl))
        
        ## ## order cluster images for their frequencies of occurreance for that year and month:
        ## ## (if they have already been ordered once, they will be ordered again, no prob, they'll be ordered again)
        ## fre.days2 <- fre.days
        
        ## max.fre <- c()
        ## for(cl in 1:n.cl){
        ##     max.fre[cl] <- which(fre.days2 == max(fre.days2, na.rm=TRUE))[1] ## 1 is needed to take only the first of the maximum, if more clusters have the same freq
        ##     fre.days2[max.fre[cl]] <- NA
        ## }
        
        ## rm(fre.days2) 
        
        ## ## associate the cluster with the highest frequency to the first regime to plot and so on:
        ## cluster.name <- c(); for(cl in 1:n.cl) cluster.name[max.fre[[cl]]] <- orden[cl]

        ## ## save the regime order:
        ## save(cluster.name, file=paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData"))

        ## load the regime order stored inside 'cluster.name' variable:
        load(paste0(workdir,"/",year.end,"_",my.period[p],"_ClusterNames.RData")) # load cluster.name saved before

        cluster.test.var <- cluster.test
        if(subdaily) cluster.test.var <- rep(cluster.test, each=4)
        
        ## wind anomaly for the chosen year and month and cluster:
        sfcWindYear <- list(); for(cl in 1:n.cl) sfcWindYear[[cl]] <- sfcWindAnomPeriodRel[which(cluster.test.var == cl),,,drop=FALSE]
        
        ## in case a regime has NO days in that month, we must set it to NA:
        for(cl in 1:n.cl) { if(length(which(cluster.test.var == cl)) == 0 ) sfcWindYear[[cl]] <- array(NA, c(1,dim(sfcWindAnomPeriod)[2:3])) }

        ## average of wind speed anomalies for a specific month and year:
        sfcWindMean <- list(); for(cl in 1:n.cl) sfcWindMean[[cl]] <- apply(sfcWindYear[[cl]], c(2,3), mean, na.rm=FALSE)
        
        ## load regime names:
        load(paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData"))
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
        if(!identical(period, period.orig)) period <- period.orig
        
        ## add strip with daily sequence of WRs:   
        mod.name <- list(); for(cl in 1:n.cl)  mod.name[[cl]] <- substr(cluster.name[cl], nchar(cluster.name[cl]), nchar(cluster.name[cl]))
        cluster.name.short <- list(); for(cl in 1:n.cl) cluster.name.short[[cl]] <- substr(cluster.name[cl],1,1)
        
        clu <- list(); for(cl in 1:n.cl) clu[[cl]] <- which(cluster.test == cl)    
        cluster.test.letters <- cluster.test

        for(cl in 1:n.cl) cluster.test.letters[clu[[cl]]] <- cluster.name.short[[cl]]
        
        my.strip <- cluster.test.letters
        cluster.test.letters2 <- cluster.test.letters

        for(cl in 1:n.cl) cluster.test.letters2[which(cluster.test.letters == cl)] <- paste0("R",cl)
        
        my.strip <- cluster.test.letters2
        
        cluster.col <- cluster.test.letters    
        for(cl in 1:n.cl) cluster.col[which(cluster.test.letters == cl)] <- cl.col[cl]
        
        cluster <- c(); for(cl in 1:n.cl) cluster[cl] <- which(orden == cluster.name[cl])

        ## order fre.days (number of days for a given regime, month and year) to be in decreasing av.frequency order:
        fre.days.ordered <- c()
        for(cl in 1:n.cl) fre.days.ordered[cluster[cl]] <- fre.days[cl] ##assign(paste0("fre.days",cluster[cl]), fre.days.orig[cl]);

        ## order frequency time series for a given regime and month to be in decreasing average freq.order:
        fre <- list(); for(cl in 1:n.cl) fre[[cluster[cl]]] <- wry[[cl]] ##assign(paste0("fre",cluster[cl]), wry[[cl]])

        ## order also impact maps on psl:
        imp.test <- list(); for(cl in 1:n.cl) imp.test[[cluster[cl]]] <- sfcWindMean[[cl]] ## assign(paste0("imp.test",cluster[cl]), sfcWindMean[[cl]])
        
        ## psl anomaly for the chosen year and month and cluster:
        slpAnomClus <- list();  for(cl in 1:n.cl) slpAnomClus[[cl]] <- slpAnomPeriod[which(cluster.test == cl),,,drop=FALSE]
        
        ## in case a regime has NO days in that month, we must set it to NA:
        for(cl in 1:n.cl)  if(length(which(cluster.test == cl)) == 0 ) slpAnomClus[[cl]] <- array(NA, c(1, dim(slpAnomPeriod)[2:3]))

        ## average SLP:
        slpMean <- list(); for(cl in 1:n.cl)  slpMean[[cl]] <- apply(slpAnomClus[[cl]], c(2,3), mean, na.rm=FALSE)                       
        psl.test <- list();  for(cl in 1:n.cl) psl.test[[cluster[cl]]] <- slpMean[[cl]] ##assign(paste0("psl.test",cluster[cl]), slpMean[[cl]])

        ##  
        ## save strip with the daily regime series for chosen month and year (it will be deleted at the end of the process):
        ##
        fileoutput.strip <- paste0(workdir,"/",year.end,"_",my.period[p],"_strip.png")
        png(filename=fileoutput.strip,width=1500,height=1850)
        
        plot.new()
        sep <- 0.03
        for(day in 1: n.days.in.a.period(p, 2001)){
            sep.cum <- (day-1)*sep
            polygon(c(sep.cum + 0.01, sep.cum + 0.01 + sep, sep.cum + 0.01 + sep, sep.cum + 0.01), c(1.01, 1.01, 1.01+sep, 1.01+sep), border="black", col=cluster.col[day])
            text(sep.cum + 0.01 + sep/2, 0.997 + sep + 0.005, labels=day, cex=1.5)
            text(sep.cum + 0.01 + sep/2, 1.013 + 0.005, labels=my.strip[day], cex=2)
        }
        
        dev.off()

        ##
        ## create and save figure(s) with regime impact on var and regime anomalies for chosen month:
        ##
        
        n.cl.sheet <- 4 ## maximum number of clusters for sheet
        n.sheets <- ceiling(n.cl / n.cl.sheet)  ## four is the maximum number of clusters to show in one sheet

        cl.mod <- c(); for(i in 1:n.sheets) if(n.cl >= n.cl.sheet*i) { cl.mod[i] <- 0 } else { cl.mod[i] <- n.cl.sheet*i - n.cl }

        cl.seq <- list(); for(i in 1:n.sheets) cl.seq[[i]] <- list()
        for(i in 1:n.sheets) cl.seq[[i]][[n.cl]] <- (n.cl.sheet*(i-1) + 1):((n.cl.sheet*i) - cl.mod[i])

        ## type of different figures to create for the report: wind speed only ("var"), SLP only ("psl") or both: 
        if(impact.last) my.figures <-  c("psl", "var", "both") else my.figures <- "psl" ## you only save var figure for last year if impact.last == FALSE ('var' is not avilable)
        if(impact.last) my.figures.name <-  c(psl.name, var.name[var.num], paste0(var.name[var.num], "_and_", psl.name)) else my.figures.name <- psl.name
        if(impact.last && report.type == "second"){  ## in this case, we only want to generate the figure with sfcWind + SLP regime anom. for ERA-Int + JRA-55
            my.figures <- "both"
            my.figures.name <-  paste0(var.name[var.num], "_and_", psl.name,"_second_report")
        }
        
        if(box.cluster) my.box <- c(lon.min, lat.min, lon.max, lat.max) else my.box <- NULL   ## eventual box with cluster spatial domain for psl figures
        if(box.impact) my.box.impact <- c(lon.min, lat.min, lon.max, lat.max) else my.box.impact <- NULL   ## eventual box with cluster spatial domain for impact figures

        for(sheet in 1:n.sheets){

            for(f in my.figures){ ## loop on the different figures for the report: wind speed only ("var"), SLP only ("psl") or both
                f.name <- my.figures.name[which(f == my.figures)]
                fileoutput.test <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_last_month_unformatted_",f.name,".png")
                
                if(f == "both" || f == "psl") png(filename=fileoutput.test, width=1503, height=2000) ## notice that if we put width=1550 a vertical white line appears in the imapct maps!!!
                if(f == "var") png(filename=fileoutput.test, width=800, height=2000)

                plot.new()

                ## plot impact maps:
                if(f != "psl"){
                    pos.y.cl <- rev(c(0.08, 0.31, 0.54, 0.77))

                    i <- 1
                    for(cl in cl.seq[[sheet]][[n.cl]]){
                        if(f == "both") par(fig=c(0, end.map, pos.y.cl[i], pos.y.cl[i] + 0.20), new=TRUE)
                        if(f == "var") par(fig=c(0.10, 0.90, pos.y.cl[i], pos.y.cl[i] + 0.20), new=TRUE)

                        PlotEquiMap2(imp.test[[cl]], imp.area.lon, imp.area.lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var, cols=my.cols.var, cex.lab=1, intxlon=10, intylat=10, drawleg=F, xlabel.dist=.5, boxx=my.box.impact, boxx.col=box.col, boxx.lwd=4, countries=my.countries)
                        if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/3, col=wind.color, pch=farms.style, lwd=2)
                        i <- i + 1
                    }
                    
                    regime.title <- paste0("Regime ", 1:n.cl)
                    pos.y.titles.cl <- rev(c(0.265, 0.495, 0.725, 0.955))
                    
                    ## plot title impact maps:
                    i <- 1
                    for(cl in cl.seq[[sheet]][[n.cl]]){
                        if(f == "both") par(fig=c(0, end.map, pos.y.titles.cl[i], pos.y.titles.cl[i] + 0.020), new=TRUE)
                        if(f == "var") par(fig=c(0.10, 0.90, pos.y.titles.cl[i], pos.y.titles.cl[i] + 0.020), new=TRUE)

                        mtext(paste0(regime.title[cl], " ", var.name.full[var.num]," anomaly "), font=2, cex=2)
                        i <- i + 1
                    }
                    
                    ## color legend impact maps:
                    if(f == "both") par(fig=c(0.03, end.map, 0.015, 0.060), new=TRUE)
                    if(f == "var") par(fig=c(0.13, 0.87, 0.015, 0.060), new=TRUE)

                    ##ColorBar(my.brks.var, cols=my.cols.var, vert=FALSE, label_scale=1.8, triangle_ends=c(FALSE,FALSE)) #, subset=my.subset2)
                    ColorBar(brks=round(100*my.brks.var[2:(l(my.brks.var)-1)]), cols=my.cols.var[2:(l(my.cols.var)-1)], vert=FALSE, label_scale=2, bar_limits=c(100*my.brks.var[2],100*my.brks.var[l(my.brks.var)-1]), col_inf=my.cols.var[1], col_sup=my.cols.var[l(my.cols.var)], subsample=2) #triangle_ends=c(T,T)) #, subset=my.subset2)

                    ## % symbol to the right of the color legend of the impact maps:
                    if(f == "both") par(fig=c(end.map, end.map + 0.01, 0.01, 0.044), new=TRUE)
                    if(f == "var") par(fig=c(0.87, 0.87 + 0.01, 0.01, 0.044), new=TRUE)
                    mtext("%", cex=1.6)

                } # close if on f

                
                ## Plot anomalies maps (right figures):
                if(f != "var"){                
                    pos.y.cl <- rev(c(0.08, 0.31, 0.54, 0.77))
                    
                    i <- 1
                    for(cl in cl.seq[[sheet]][[n.cl]]){
                        if(f == "both") { mod.xlab.dist <- .5; par(fig=c(end.map, 0.92, pos.y.cl[i], pos.y.cl[i] + 0.20), new=TRUE)}
                        if(f == "psl" && i == 1) { mod.xlab.dist <- 1; par(fig=c(0.28 + 0.006, 0.72 - 0.006, pos.y.cl[i], pos.y.cl[i] + 0.20), new=TRUE) } ## quirks of R
                        if(f == "psl" && i != 1) { mod.xlab.dist <- .5 ; par(fig=c(0.28, 0.72, pos.y.cl[i], pos.y.cl[i] + 0.20), new=TRUE) }
                        
                        PlotEquiMap2(psl.test[[cl]], bigarea.lon, bigarea.lat, filled.continents=FALSE, continents.col="black", brks=my.brks, brks2=my.brks, cols=my.cols, intxlon=10, intylat=10, drawleg=F, contours=t(psl.test[[cl]]), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=mod.xlab.dist, boxx=my.box, boxx.lwd=4, boxx.col=box.col, countries=my.countries)
                        
                        if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/3, col=wind.color, pch=farms.style, lwd=2)

                        i <- i + 1
                    }
                    
                    ## color legend right figures:
                    if(f == "both") par(fig=c(end.map + 0.01, 0.93, 0.015, 0.06), new=TRUE)
                    if(f == "psl") par(fig=c(0.28 + 0.01, 0.72 - 0.02, 0.015, 0.06), new=TRUE)

                    ColorBar(my.brks[2:(length(my.brks)-1)], cols=my.cols[2:(length(my.cols)-1)], vert=FALSE, label_scale=2, bar_limits=c(my.brks[2],my.brks[l(my.brks)-1]), col_inf=my.cols[1], col_sup=my.cols[l(my.cols)], subsample=1)

                    ## plot symbol unit of measure right figure:
                    if(f == "both") par(fig=c(0.924, 0.930, 0.01, 0.044), new=TRUE)
                    if(f == "psl") par(fig=c(0.70, 0.72, 0.01, 0.044), new=TRUE)
                    mtext(psl.unit, cex=1.8)
                    
                    n.days <- floor(n.days.in.a.period(p,1)) ## number of days in period p

                    ## plot number of days of each regime to the right:
                    pos.y.days.cl <- rev(c(0.08, 0.31, 0.54, 0.77))

                    i <- 1
                    for(cl in cl.seq[[sheet]][[n.cl]]){
                        if(f == "both") par(fig=c(0.93, 0.99, pos.y.days.cl[i], pos.y.days.cl[i] + 0.10), new=TRUE)
                        if(f == "psl") par(fig=c(0.75, 0.81, pos.y.days.cl[i], pos.y.days.cl[i] + 0.10), new=TRUE)

                        mod.plural <- ifelse(fre.days.ordered[cl] == 1, "", "s")
                        mtext(paste0(fre.days.ordered[cl]," day",mod.plural,"\n(", round(100*fre.days.ordered[cl]/n.days, 1),"%)"), cex=2.8)
                        i <- i + 1
                    }

                    ## title right figures (psl):
                    pos.y.titles.cl <- rev(c(0.265, 0.495, 0.725, 0.955))

                    i <- 1
                    for(cl in cl.seq[[sheet]][[n.cl]]){
                        if(f == "both") par(fig=c(end.map, 0.92, pos.y.titles.cl[i], pos.y.titles.cl[i] + 0.020), new=TRUE)
                        if(f == "psl") par(fig=c(0.28, 0.72, pos.y.titles.cl[i], pos.y.titles.cl[i] + 0.020), new=TRUE)

                        mtext(paste0(regime.title[cl], " ", psl.name, " anomaly "), font=2, cex=2, col="black")
                        i <- i + 1
                    }

                } ## close if on f != var
                
                dev.off()        
                
                ## create final figure composition:
                cut.bottom <- c(1536, 1074, 612, 150) ## pixel to cut starting from the bottom for each of the four rows of the images

                fileoutput.maps <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_maps_",f.name,".png")
                system(paste0("convert ",fileoutput.test," -crop +0-",cut.bottom[i-1]," +repage ", fileoutput.maps)) # remove XXXX points from bottom
                
                fileoutput.caption <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_caption_",f.name,".png")
                system(paste0("convert ",fileoutput.test," -crop +0+1870 +repage ",fileoutput.caption)) # cut the lower part of the strip only with the color legends by removing top part
                fileoutput.both <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_maps_and_caption_",f.name,".png")
                system(paste0("montage ",fileoutput.maps," ",fileoutput.caption," -tile 1x2 -geometry +0+0 ",fileoutput.both))
                
                ## add the strip with the regime sequence over the average impact composition:
                fileoutput.strip2 <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_strip2_",f.name,".png")
                fileoutput.all <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_all_",f.name,".png")
                
                system(paste0("convert ",fileoutput.strip," -crop +0-1730 +repage ",fileoutput.strip2)) # cut the lower part of the strip

                if(f != "var") {
                    system(paste0("montage ",fileoutput.strip2," ",fileoutput.both," -tile 1x2 -geometry +0+0 ",fileoutput.all))
                } else {
                    fileoutput.all <- fileoutput.both
                }
                
                ## same figure but formatted for the catalogue:
                fileoutput2.test <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_last_month_",f.name,"_part_", sheet,"-", n.sheets,".png")

                region.string.psl <- paste0(bigarea.name," (", round(lat.min.legend,2), deg, lat.min.legend.letter,"-", round(lat.max.legend,2), deg, lat.max.legend.letter,", ", round(lon.min.legend,2), deg, lon.min.legend.letter,"-", round(lon.max.legend,2), deg, lon.max.legend.letter,")")
                
                region.string.var <- paste0(imp.area.name," (", round(imp.area.lat.min.legend,2), deg, imp.area.lat.min.legend.letter,"-", round(imp.area.lat.max.legend,2), deg, imp.area.lat.max.legend.letter,", ", round(imp.area.lon.min.legend,2), deg, imp.area.lon.min.legend.letter,"-", round(imp.area.lon.max.legend,2), deg,imp.area.lon.max.legend.letter,").")

                cluster.string <- paste0(round(cl.lat.min.legend,2), deg, cl.lat.min.legend.letter,"-", round(cl.lat.max.legend,2), deg, cl.lat.max.legend.letter,", ", round(cl.lon.min.legend,2), deg, cl.lon.min.legend.letter,"-", round(cl.lon.max.legend,2), deg, cl.lon.max.legend.letter)
                
                mod.space <- ""
                
                if(f == "psl") { mod.space <- "                                                        "; my.region.string <- paste0(mod.space, "Region: ",region.string.psl);  var.title <- psl.name.full ; cl.string <- cluster.string ; dataset.string <-  paste0(rean.name," reanalysis")}
                if(f == "var") { mod.space <- "                            "; my.region.string <- paste0(mod.space, "Region: ",region.string.var); var.title <- var.name.full[var.num] ; cl.string <- cluster.string;  dataset.string <- paste0(rean2load.name," reanalysis")}
                if(f == "both") { my.region.string <- paste0("Region. Left: ", region.string.var," Right: ", region.string.psl); var.title <- paste0(var.name.full[var.num]," and ", psl.name.full); cl.string <- cluster.string; dataset.string <- ifelse(two.rean == TRUE, paste0(rean.impact.name," reanalysis (left); ", rean.name, " reanalysis (right)"), paste0(rean.name," reanalysis")) }
                
                system(paste0(fig2catalog.dir,"/fig2catalog.sh -s 0.691 -m 20 -r 20 -t '",rean.name," / ", var.title," / Monthly anomalies \n", period.name[p]," / ",year.end,"' -c '", my.region.string,"\n", mod.space,"Cluster domain: ", cl.string, "\n", mod.space,"Reference dataset: ", dataset.string,"' ", fileoutput.all," ", fileoutput2.test))
                
                ## remove unformatted figure:
                if(f != "var")  system(paste0("rm ", fileoutput.both))
                system(paste0("rm ", fileoutput.strip2))
                system(paste0("rm "," ", fileoutput.test, " ", fileoutput.all, " ", fileoutput.maps))
                system(paste0("rm "," ", fileoutput.caption))

            } ## close for on f
            
        } ## close for on sheet

        ## system(paste0("rm ", fileoutput.strip))

        histogram <- FALSE
        if(histogram){        
            ##
            ## compare observed pdf for a specific month, year and point with the reconstructed pdf for the same month, year and point:
            ##
            
            ## plot the PDF of wind speed anomalies for a specific point and month:
            my.point.lat.pos <- 47  ## 40
            my.point.lon.pos <- 67  ## 70

            ## intervals to use with the hist() functions:
            my.pdf.breaks.width <- 0.05
            my.pdf.breaks <- seq(-100, 100, my.pdf.breaks.width)

            ## smoothness of the LOESS filter for the pdf (the higher, the smoother):
            span <- 0.005

            ## regime line colors:
            col.cl <- c("red","blue","orange","purple","darkolivegreen3","cyan")

            ## number of days in period p:
            n.days <- floor(n.days.in.a.period(p,1))

            ## number of 6-hourly intervals in month p of 1981-2016:
            n.6int <- n.days * 4 * n.years 

            ## number of 6-hourly intervals in month p of last year only:
            n.6int.last <- n.days * 4

            ## vector with the *centers* of all intervals to show in the plot:
            pdf.int <- my.pdf.breaks + my.pdf.breaks.width / 2
            pdf.int <- pdf.int[-length(pdf.int)]  ## remove last center because it won't contain data, because last hist interval defined in my.pdf.breaks ends before of last center
            
            plot.min <- -0.90  ## min value to plot
            plot.max <- 1.90   ## max value to plot
            
            my.pdf.breaks.pos.min <- which(my.pdf.breaks >= plot.min)[1]
            my.pdf.breaks.pos.max <- which(my.pdf.breaks <= plot.max)[length(which(my.pdf.breaks < plot.max))]
            
            pdf.int.pos <- (my.pdf.breaks.pos.min-2):(my.pdf.breaks.pos.max+2)     ##985:1016 ## select only intervals between -1.5 and 1.5 (+-150% of wind speed)

            ## regime pdf:
            my.pdf <- list()
            for(cl in 1:n.cl) my.pdf[[cl]] <- hist(varwrRel[[p]][[cl]][,my.point.lat.pos,my.point.lon.pos], freq=TRUE, col="blue", breaks=my.pdf.breaks, ylim=c(0,25), plot=FALSE)

            ## mean value of each regime PDF:
            my.pdf.mean <- c(); for(cl in 1:n.cl) my.pdf.mean[cl] <- mean(varwrRel[[p]][[cl]][, my.point.lat.pos, my.point.lon.pos])

            ## divide regime pdf for the total number of data:
            my.pdf.norm <- my.pdf; for(cl in 1:n.cl) my.pdf.norm[[cl]]$density <- my.pdf[[cl]]$counts/n.6int

            ## divide regime pdf for the number of its data to normalize area to 1:
            my.pdf.norm2 <- my.pdf; for(cl in 1:n.cl) my.pdf.norm2[[cl]]$density <- my.pdf[[cl]]$counts/sum(my.pdf[[cl]]$counts)
            
            ## regime pdf for last year only:
            my.pdf.year <- list()
            for(cl in 1:n.cl){
                if(length(which(is.na(sfcWindYear[[cl]][,my.point.lat.pos,my.point.lon.pos]))) == 0){             
                    my.pdf.year[[cl]] <- hist(sfcWindYear[[cl]][,my.point.lat.pos,my.point.lon.pos], freq=TRUE, col="blue", breaks=my.pdf.breaks, ylim=c(0,25), plot=FALSE)
                } else {
                    my.pdf.year[[cl]] <- hist(my.pdf.breaks[1], freq=TRUE, breaks=my.pdf.breaks, plot=FALSE)
                }
            }
            
            ## mean value of each regime PDF for last year:
            my.pdf.year.mean <- c(); for(cl in 1:n.cl) my.pdf.year.mean[cl] <- mean(sfcWindYear[[cl]][,my.point.lat.pos, my.point.lon.pos])

            ## divide regime pdf for the total number of data:
            my.pdf.year.norm <- my.pdf.year; for(cl in 1:n.cl) my.pdf.year.norm[[cl]]$density <- my.pdf.year[[cl]]$counts/n.6int.last

            ## divide regime pdf for the number of its data to normalize area to 1:
            my.pdf.year.norm2 <- my.pdf.year; for(cl in 1:n.cl) my.pdf.year.norm2[[cl]]$density <- my.pdf.year[[cl]]$counts/sum(my.pdf.year[[cl]]$counts)
            
            pdf.obs.mean <- mean(sfcWindAnomPeriodRel[, my.point.lat.pos, my.point.lon.pos])      
            
            ##  
            ## pdf climatological (histogram version):
            ##
            
            file.pdf.clim.hist<- paste0(workdir,"/",year.end,"_",my.period[p],"_pdf_clim_hist.png")
            png(filename=file.pdf.clim.hist, width=1500, height=1000)

            par(mar=c(10,5,1,1))

            my.pdf.breaks.hist <- 100*c(seq(-1, 2, 0.1),3)
            
            ## plot observed pdf for chosen month:
            varAllRel <- c(); for(cl in 1:n.cl) varAllRel <- c(varAllRel, 100*varwrRel[[p]][[cl]][, my.point.lat.pos, my.point.lon.pos])

            ## the below line is the same than the previous one, but it relies on 'varmatRel' which depends on the month, so we cannot employ it to replace previous line:
            ## varAllRel2 <- 100*varmatRel[, my.point.lat.pos, my.point.lon.pos]
            
            pdf.obs.month <- hist(varAllRel, freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE, xaxt="n", yaxt="n", ylab="Counts", xlab=paste0(psl.name," relative anomaly (%)"))

            pdf.hist <- list()
            for(cl in 1:n.cl) pdf.hist[[cl]] <- hist(100*varwrRel[[p]][[cl]][, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)

            pdf.hist.conc <- c()
            for(cl in 1:n.cl)  pdf.hist.conc <- c(pdf.hist.conc, pdf.hist[[cl]]$counts)

            barplot(height=t(array(c(pdf.obs.month$counts, pdf.hist.conc), c(length(my.pdf.breaks.hist)-1, 1+n.cl))), beside=TRUE, ylim=c(0,500), offset=0, cex.names=1, cex.axis=1, cex.lab=2, ylab="counts", names.arg=paste0("[",my.pdf.breaks.hist[-length(my.pdf.breaks.hist)],",", my.pdf.breaks.hist[-1],"]"), las=2, col=c("black",col.cl[1:n.cl])) ## xlab="year"

            mtext(side=1, text=paste0(psl.name," relative anomaly (%)"), line=7, cex=2)
            
            ## add legend:
            legend(x="topright", y=NULL, bty="n", legend=c(paste0("Hist Observed ", period.name[p], " ", year.start, "-", year.end, "(Mean=", round(mean(varAllRel), 1), "%)"), paste0("Hist Regime #",1:n.cl, " ",period.name[p]," ", year.start, "-", year.end, " (freq=",round(100*sapply(wry,mean),1),"%, mean=", round(100*my.pdf.mean,1),"%)")), col=c("black", col.cl[1:n.cl]), lwd=3, lty=1, cex=1.5)

            dev.off()          
            
            ##  
            ## pdf of last year only (histogram version):
            ##
            
            file.pdf.hist<- paste0(workdir,"/",year.end,"_",my.period[p],"_pdf_hist.png")
            png(filename=file.pdf.hist, width=1500, height=1000)

            par(mar=c(10,5,1,1))

            my.pdf.breaks.hist <- 100*c(seq(-1, 2, 0.1),3)
            
            ## plot observed pdf for chosen month and year:  
            pdf.obs.month.year <- hist(100*sfcWindAnomPeriodRel[, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)

            pdf.hist.year <- list()
            for(cl in 1:n.cl) pdf.hist.year[[cl]] <- hist(100*sfcWindYear[[cl]][, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)

            pdf.hist.year.conc <- c()
            for(cl in 1:n.cl)  pdf.hist.year.conc <- c(pdf.hist.year.conc, pdf.hist.year[[cl]]$counts)
            
            barplot(height=t(array(c(pdf.obs.month.year$counts, pdf.hist.year.conc), c(length(my.pdf.breaks.hist)-1, 1+n.cl))), beside=TRUE, ylim=c(0,20), offset=0, cex.names=1, cex.axis=1, cex.lab=2, ylab="counts", names.arg=paste0("[",my.pdf.breaks.hist[-length(my.pdf.breaks.hist)],",", my.pdf.breaks.hist[-1],"]"), las=2, col=c("black",col.cl[1:n.cl])) ## xlab="year"

            mtext(side=1, text=paste0(psl.name," relative anomaly (%)"), line=7, cex=2)
            
            ## add legend:
            legend(x="topright", y=NULL, bty="n", legend=c(paste0("Hist Observed ", period.name[p], " ", year.end, "(Mean=", round(100*pdf.obs.mean,1),"%)"), paste0("Hist Regime #",1:n.cl, " ",period.name[p]," ", year.end, " (freq=",round(100*fre.days/n.days,1),"% or ", fre.days," days, mean=", round(100*my.pdf.year.mean,1),"%)")), col=c("black", col.cl[1:n.cl]), lwd=3, lty=1, cex=1.5)

            dev.off()
            
            ##  
            ## pdf observed last year + reconstructed (histogram version):
            ##
            
            file.pdf.recon.hist<- paste0(workdir,"/",year.end,"_",my.period[p],"_pdf_recon_hist.png")
            png(filename=file.pdf.recon.hist, width=1500, height=1000)

            par(mar=c(10,5,1,1))

            my.pdf.breaks.hist <- 100*c(seq(-1, 2, 0.1),3)
            
            ## plot observed pdf for chosen month and year:  
            pdf.obs.month.year <- hist(100*sfcWindAnomPeriodRel[, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)

            pdf.hist <- list()
            for(cl in 1:n.cl) pdf.hist[[cl]] <- hist(100*varwrRel[[p]][[cl]][, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)
            for(cl in 1:n.cl) pdf.hist[[cl]]$density <- pdf.hist[[cl]]$counts / (sum(pdf.hist[[cl]]$counts) / n.6int)
            
            pdf.recon.year <- 0; for(cl in 1:n.cl) pdf.recon.year <- pdf.recon.year + pdf.hist[[cl]]$density * fre.days[cl] / n.days
            pdf.recon.year <- pdf.recon.year / n.years

            barplot(height=t(array(c(pdf.obs.month.year$counts, pdf.recon.year), c(length(my.pdf.breaks.hist)-1, 2))), beside=TRUE, ylim=c(0,20), offset=0, cex.names=1, cex.axis=1, cex.lab=2, ylab="counts", names.arg=paste0("[", my.pdf.breaks.hist[-length(my.pdf.breaks.hist)],",", my.pdf.breaks.hist[-1],"]"), las=2, col=c("black", "gray70")) ## xlab="year"

            mtext(side=1, text=paste0(psl.name, " relative anomaly (%)"), line=7, cex=2)

            pdf.recon.mean.hist <-0; for(cl in 1:n.cl) pdf.recon.mean.hist <- pdf.recon.mean.hist + my.pdf.mean[cl] * fre.days[cl]; pdf.recon.mean.hist <- pdf.recon.mean.hist / n.days
            
            ## add legend:
            legend(x="topright", y=NULL, bty="n", legend=c(paste0("Hist Observed ", period.name[p], " ", year.end, " (mean=", round(100*pdf.obs.mean,1), "%)"), paste0("Hist Reconstructed ", period.name[p], " ", year.end, " (mean=",round(100*pdf.recon.mean.hist,1),"%)")), col=c("black", "gray70"), lwd=3, lty=1, cex=1.5)

            dev.off()

            ##  
            ## pdf reconstructed + partial (histogram version):
            ##
            
            file.pdf.recon.part.hist <- paste0(workdir,"/",year.end,"_",my.period[p],"_pdf_recon_part_hist.png")
            png(filename=file.pdf.recon.part.hist, width=1500, height=1000)

            par(mar=c(10,5,1,1))

            my.pdf.breaks.hist <- 100*c(seq(-1, 2, 0.1),3)
            
            ## plot observed pdf for chosen month and year:  
            pdf.obs.month.year <- hist(100*sfcWindAnomPeriodRel[, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)

            pdf.hist <- list()
            for(cl in 1:n.cl) pdf.hist[[cl]] <- hist(100*varwrRel[[p]][[cl]][, my.point.lat.pos, my.point.lon.pos], freq=TRUE, breaks=my.pdf.breaks.hist, plot=FALSE)
            for(cl in 1:n.cl) pdf.hist[[cl]]$density <- pdf.hist[[cl]]$counts / (sum(pdf.hist[[cl]]$counts) / n.6int)

            pdf.hist.partial <- list()
            for(cl in 1:n.cl) pdf.hist.partial[[cl]] <- pdf.hist[[cl]]$density * fre.days[cl] / n.days
            for(cl in 1:n.cl) pdf.hist.partial[[cl]] <- pdf.hist.partial[[cl]] / n.years
            
            ##pdf.recon.year <- 0; for(cl in 1:n.cl) pdf.recon.year <- pdf.recon.year + pdf.hist[[cl]]$density * fre.days[cl] / n.days
            pdf.recon.year <- 0; for(cl in 1:n.cl) pdf.recon.year <- pdf.recon.year + pdf.hist.partial[[cl]]
            ##pdf.recon.year <- pdf.recon.year / n.years

            pdf.hist.partial.mean <- c()
            for(cl in 1:n.cl) pdf.hist.partial.mean[cl] <- mean((my.pdf.breaks.hist[-length(my.pdf.breaks.hist)]+5)*pdf.hist.partial[[cl]])
            
            pdf.hist.partial.conc <- c()
            for(cl in 1:n.cl)  pdf.hist.partial.conc <- c(pdf.hist.partial.conc, pdf.hist.partial[[cl]])
            
            barplot(height=t(array(c(pdf.recon.year, pdf.hist.partial.conc), c(length(my.pdf.breaks.hist)-1, 1+n.cl))), beside=TRUE, ylim=c(0,20), offset=0, cex.names=1, cex.axis=1, cex.lab=2, ylab="counts", names.arg=paste0("[", my.pdf.breaks.hist[-length(my.pdf.breaks.hist)],",", my.pdf.breaks.hist[-1],"]"), las=2, col=c("gray70",col.cl[1:n.cl])) ## xlab="year"
            
            mtext(side=1, text=paste0(psl.name, " relative anomaly (%)"), line=7, cex=2)

            pdf.recon.mean.hist <-0
            for(cl in 1:n.cl) pdf.recon.mean.hist <- pdf.recon.mean.hist + my.pdf.mean[cl] * fre.days[cl]; pdf.recon.mean.hist <- pdf.recon.mean.hist / n.days
            
            pdf.obs.mean <- mean(sfcWindAnomPeriodRel[, my.point.lat.pos, my.point.lon.pos])
            
            ## add legend:
            legend(x="topright", y=NULL, bty="n", legend=c(paste0("Hist Reconstructed ", period.name[p], " ", year.end, " (Mean=",round(100*pdf.recon.mean.hist,1),"%)"), paste0("Hist Reconstructed Regime #", 1:n.cl, " ", period.name[p], " ", year.end, " (Mean=",round(pdf.hist.partial.mean, 1),"%)")), col=c("gray70", col.cl[1:n.cl]), lwd=3, lty=1, cex=1.5)

            dev.off()
            
        } ## close if on histogram
        
    } # close for on p
} ## close if on figures.last
  ##gc()  
  
#########################################################################################
#       Create anomalies maps for ALL YEARS and for a particular month and regime       #
#########################################################################################

# For each regime, plot the maps with its observed impact on monthly wind speed and SLP anomalies for ALL YEARS in the period #
cat("Generating impact maps for the whole period. Please wait...\n")

period.orig <- period
for(p in period){
    ##print(paste("Period:",period.name[p]))
    
    ## load regime sequence in cluster.sequence (for forecasts, it load only the data corresponding to the chosen start month p and lead month 'lead.month')
    if(area != "EU_CF") {
        ## update the working directory, because the period could have changed:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        dir.create(file.path(workdir))
        load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_","psl",".RData")) 
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
        if(!identical(period, period.orig)) period <- period.orig
    } else {
        my.cluster <- readRDS(paste0(rootdir,"/wr_erainterim_1981_2016_", my.period[p],".RDS"))[[1]]
        my.cluster$cluster <- as.vector(my.cluster$cluster)
        cluster.sequence <- my.cluster$cluster

        ## measure the interannual monthly frequeny of each WR because in the .RDS data is not present:
        wry <- list()
        np <- n.days.in.a.period(p,2001)
        for(cl in 1:n.cl){
            wry[[cl]] <- rep(NA, year.end - year.start + 1)
            for(y in year.start:year.end){
                ## also forVero's clustering, the time order is always: year1day1, year1day2, ..., year1day31, year2day1, year2day2, ..., year2day28, etc,
                wry[[cl]][y-year.start+1]  <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == cl))
            }
        }
        for(cl in 1:n.cl) wry[[cl]] <- wry[[cl]] / np      ## convert frequencies in %
        fre <- wry
        gc()
    }
        
    ## load impact data (varwrmean) for the chosen period only if it is available, if not it will leave an empty space in the composition:
    workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p]) 
    if(file.exists(paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_", rean2load.name,".RData"))){
        impact.data <- TRUE
        print(paste0("Impact data for variable ", var.name[var.num] ," in ",period.name[p]," available for reanalysis ", rean.name))
        load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,".RData"))
        
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
        if(!identical(period, period.orig)) period <- period.orig
        
    } else {
        impact.data <- FALSE
        print(paste0("Impact data for variable ",var.name[var.num] ," in ",period.name[p]," NOT available for reanalysis ", rean.name))
    }

    if(stations){
        ## load impact station data only if it is available, if not it will leave an empty space in the composition:
        if(file.exists(paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_stations.RData"))){
            impact.data <- TRUE
            print(paste0("Impact data for variable ",var.name[var.num] ," available for observational dataset ", rean.name))
            load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_stations.RData"))
            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
            if(!identical(period, period.orig)) period <- period.orig
            
        } else {
            impact.data <- FALSE
            print(paste0("Impact data for variable ",var.name[var.num] ," not available for observational dataset ", rean.name))
        }

    } ## close if on stations

    if(area != "EU_CF") {
         ## load the cluster names from the file already saved, if regimes come from a reanalysis:
         ClusterName.file <- paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData")
         if(!file.exists(ClusterName.file)) stop(paste0("file: ",ClusterName.file," missing"))  # check if file exists or not
         load(ClusterName.file) # load cluster names 
         workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # reprsitinate the working dir because it may have changed because of load()
         if(!identical(period, period.orig)) period <- period.orig
         
         ## assign to each cluster its regime with the same order as in cluster.name (i.e: by decreasing monthly frequency during last year):
         cluster <- c(); for(cl in 1:n.cl) cluster[cl] <- which(orden == cluster.name[cl])
         
         fre <- list(); for(cl in 1:n.cl) fre[[cluster[cl]]] <- wry[[cl]]

         ## order cluster series for the same order of cluster.name:
         my.cluster.ord <- my.cluster$cluster
         for(cl in 1:n.cl){
             ss <- which(my.cluster$cluster == cl)
             my.cluster.ord[ss] <- cluster[cl]
         }

     } else {
         cluster <- 1:4
         my.cluster.ord <- my.cluster$cluster
     }
         
    if(impact.data){   
        if(stations) { ## in this case, we don't want to plot the reanalysis data so we fill varwrmeanRel of NA
            for(cl in 1:n.cl) {
                varwrmeanRel[[cl]] <- array(NA, c(length(imp.area.lat), length(imp.area.lon))) ##array(NA, c(bigarea.n.pos.lat, bigarea.n.pos.lon))
                pvalue[[cl]] <- array(NA, c(length(imp.area.lat), length(imp.area.lon))) ##array(NA, c(bigarea.n.pos.lat, bigarea.n.pos.lon))
            }
        } ## close if on stations

        imp <- list(); for(cl in 1:n.cl) imp[[cluster[cl]]] <- varwrmean[[cl]]                   
        sig <- list(); for(cl in 1:n.cl) sig[[cluster[cl]]] <- pvalue[[cl]]
        impRel <- list(); for(cl in 1:n.cl) impRel[[cluster[cl]]] <- varwrmeanRel[[cl]]    
    }

    if(stations){
        impstat <- list(); for(cl in 1:n.cl) impstat[[cluster[cl]]] <- varstatwrmean[[cl]]        
        sigstat <- list(); for(cl in 1:n.cl) sigstat[[cluster[cl]]] <- pstatvalue[[cl]]
        ##impstatRel <- list(); for(cl in 1:n.cl) impRel[[cluster[cl]]] <- varstatwrmeanRel[[cl]]
    }

    ## measure persistency:
    ##my.cluster.array <- array(my.cluster$cluster, c(length(my.cluster$cluster)/n.years, n.years))  ## array cluster series en formato dias x years
    sequ <- i <- pers <- list()
    for(cl in 1:n.cl) sequ[[cl]] <- rep(0, 10000)
    for(cl in 1:n.cl) i[[cl]] <- 1
    for(cl in 1:n.cl) { if(my.cluster.ord[1] != cl) i[[cl]] <- 0 else sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1 }

    for(d in 1:(length(my.cluster.ord)-1)){
        for(cl in 1:n.cl) {
            if(my.cluster.ord[d] != cl && my.cluster.ord[d + 1] == cl) i[[cl]] <- i[[cl]] + 1
            if(my.cluster.ord[d] == cl) sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1
        }
    }

    for(cl in 1:n.cl)  if(my.cluster.ord[length(my.cluster.ord)] == cl) sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1       
    for(cl in 1:n.cl)  pers[[cl]] <- mean(sequ[[cl]][which(sequ[[cl]] != 0)])
    
    ## measure transition probabilities:
    j <- c()
    transition <- list()   
    for(cl in 1:n.cl) j[cl] <- 1
    for(cl in 1:n.cl) transition[[cl]] <- vector()

    for(d in 1:(length(my.cluster.ord)-1)){
        for(cl in 1:n.cl){
            if(my.cluster.ord[d] == cl && (my.cluster.ord[d + 1] != my.cluster.ord[d])){
                transition[[cl]][j[cl]] <- my.cluster.ord[d+1]
                j[cl] <- j[cl]+1
            }
        }
    }

    trans <- matrix(NA, n.cl, n.cl, dimnames=list(paste0("regime ",1:n.cl),paste0("regime ",1:n.cl)))
    for(cl in 1:n.cl) { for(cl2 in 1:n.cl) trans[cl, cl2] <- length(which(transition[[cl]] == cl2)) }
    for(cl in 1:n.cl) trans[cl,cl] <- NA  ## remove diagonal elements (transitions between the same cluster don't exist)
    trans.tot <- apply(trans, 1, sum, na.rm=TRUE)
    for(cl in 1:n.cl) trans[cl,] <- trans[cl,]/trans.tot[cl]  ## convert transition to a %

    ## save transition matrix and persistence values:
    png(filename = paste0(workdir,"/transition_table_",psl.name,"_",period.name[p],".png"),width=280,height=135)
    plot.new()
    addtable2plot(x=-0.3, y=-15, table=round(100*trans,1), bty="o", hlines=T, vlines=T, display.rownames=T,title=paste0("           Transition probability ",psl.name, " (%)"))
    par(fig=c(0,1,0,0.3))
    text(x=0.5, y=0.1, labels="Persistence (days): ")
    par(fig=c(0,1,0,0.1), oma=c(0,0,0,0), mar=c(0,0,0,0))
    text(x=0.6, y=0, labels=paste0(round(as.numeric(pers),1), collapse="          "))
    dev.off()

    #### measure persistency trend:
    my.cluster.ord.matrix <- array(my.cluster.ord, c(length(my.cluster.ord)/n.years, n.years))  ## matrix days x years

    pers.series <- array(NA, c(n.cl, n.years))
    for(y in 1:n.years){
        sequ <- i <- pers <- list()
        for(cl in 1:n.cl) sequ[[cl]] <- rep(0, 10000)
        for(cl in 1:n.cl) i[[cl]] <- 1
        for(cl in 1:n.cl) { if(my.cluster.ord.matrix[1,1] != cl) i[[cl]] <- 0 else sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1 }

        for(d in 1:(length(my.cluster.ord.matrix[,y])-1)){
            for(cl in 1:n.cl) {
                if(my.cluster.ord.matrix[d, y] != cl && my.cluster.ord.matrix[d + 1, y] == cl) i[[cl]] <- i[[cl]] + 1
                if(my.cluster.ord.matrix[d, y] == cl) sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1
            }
        }

        for(cl in 1:n.cl)  if(my.cluster.ord.matrix[length(my.cluster.ord)/n.years, n.years] == cl) sequ[[cl]][i[[cl]]] <- sequ[[cl]][i[[cl]]] + 1       
        for(cl in 1:n.cl)  { pers[[cl]] <- mean(sequ[[cl]][which(sequ[[cl]] != 0)]); if(is.na(pers[[cl]])) pers[[cl]] <- 0 } 
        pers.series[,y] <- as.numeric(pers)
    }

    pers.p.value <- pers.slope <- pers.intercept <- pers.trend <- c()
    x.data <- 1:n.years
    for(cl in 1:n.cl){
        pers.p.value[cl] <- MannKendall(pers.series[cl,])$sl    
        pers.slope[cl] <- lm(pers.series[cl,] ~ x.data)$coefficients[2]
        pers.intercept[cl] <- lm(pers.series[cl,] ~ x.data)$coefficients[1]
        pers.trend[cl] <- pers.slope[cl] * n.years
    }

    write.table(round(pers.series,2), row.names=paste0("regime",1:n.cl), col.names=year.start:year.end, paste0(workdir,"/Time_series_persistence_", my.period[p],"_data.txt"))

    ## create figures with time series persistence (one for each regime):
    for(cl in 1:n.cl){
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])   # recreate working dir
        fileoutput <- paste0(workdir,"/Trend_persistence_", my.period[p],"_regime_num_",cl,".png")
        png(filename=fileoutput, width=400, height=300) # width=15000, height=3700

        ymax <- ceiling(max(pers.series[cl,])) + 2
        plot(pers.series[cl,], type="o", cex=.3, xaxt="n", ylim=c(0, ymax), xlab="Year", ylab="Persistence", cex.lab=1, cex.axis=1, main=paste0("Regime ", cl))
        axis(1, at=1:n.years, labels=year.start:year.end, cex.axis=1)
        text(n.years-12, ymax-0.5, col="black", labels=paste0("Persistence: ", round(mean(pers.series[cl,]),2), " days"))

        if(pers.p.value[cl] < 0.05) {
            lines(x=1:n.years, y=pers.slope[cl]*(0:(n.years-1)) + pers.intercept[cl], col="red", lty=1)
            text(n.years-12, ymax-1, col="black", labels=paste0("Trend: ", round(pers.trend[cl],2), " days / ", n.years, " yrs"))
        }

        dev.off()
    }
    
    ## psl anomalies for days of the chosen period (i.e: winter) and only for climatological years:
    if(fast.reshape){
        cat(paste0("Fast formatting ", psl.name," climatological data during ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))
        slpAnomPeriod <- slpAnom[1:n.years.clim, pos.period(1,p),,]  # select only days in the chosen period (i.e: winter)
        slpmat <- array(aperm(slpAnomPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(slpAnomPeriod)[1] * dim(slpAnomPeriod)[2], dim(slpAnomPeriod)[3], dim(slpAnomPeriod)[4]))

        ## same as above, but without anomalies:
        slpPeriod <- slp[1:n.years.clim, pos.period(1,p),,] # select only days in the chosen period (i.e: winter)
        slpmat.no.ano <- array(aperm(slpPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(slpPeriod)[1] * dim(slpPeriod)[2], dim(slpPeriod)[3], dim(slpPeriod)[4]))
    } else {
        cat(paste0("Formatting ", psl.name," climatological data during ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))
        
        slpAnomPeriod <- slpAnom[1:n.years.clim, pos.period(1,p),,] 
        slp.melted <- melt(slpAnomPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
        slpmat <- unname(acast(slp.melted, Year + Day ~ Lat ~ Lon))
        
        ## same as above, but without anomalies:
        slpPeriod <- slp[1:n.years.clim, pos.period(1,p),,] # select only days in the chosen period (i.e: winter)
        slp.melted.no.ano <- melt(slpPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
        slpmat.no.ano <- unname(acast(slp.melted.no.ano, Year + Day ~ Lat ~ Lon))
    }
    
    slpAnomPeriod <- slpAnom[1:n.years.clim, pos.period(1,p),,] 
    ##slp.melted <- melt(slpAnomPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
    ##slpmat <- unname(acast(slp.melted, Year + Day ~ Lat ~ Lon))
    slpmat <- array(aperm(slpAnomPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(slpAnomPeriod)[1] * dim(slpAnomPeriod)[2], dim(slpAnomPeriod)[3], dim(slpAnomPeriod)[4]))

    ## same as above, but without anomalies:
    slpPeriod <- slp[1:n.years.clim, pos.period(1,p),,] # select only days in the chosen period (i.e: winter)
    ##slp.melted.no.ano <- melt(slpPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
    ##slpmat.no.ano <- unname(acast(slp.melted.no.ano, Year + Day ~ Lat ~ Lon))
    slpmat.no.ano <- array(aperm(slpPeriod[,,,, drop=FALSE], c(2,1,3,4)), c(dim(slpPeriod)[1] * dim(slpPeriod)[2], dim(slpPeriod)[3], dim(slpPeriod)[4]))

    ## remove psl trend for the chosen period:
    if(detrend.psl){ 
        daily.seq <- 1:dim(slpmat)[1] # create a sequence from 1 to the number of years*days
        slp.slope <- apply(slpmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[2])  ## get trend slope at each point
        slp.intercept <- apply(slpmat, c(2,3), function(x) lm(x ~ daily.seq)$coefficients[1])  ## get trend intercept at each point
        
        slpmat.detrended <- array(NA, c(dim(slpmat)))
        for(t in daily.seq){
            slpmat.detrended[t,,] <- slpmat[t,,] - slp.slope*t - slp.intercept
        }
        
        slpmat <- slpmat.detrended
        rm(slpmat.detrended)
        gc()

        ## same but for psl no in anomalies:
        slpmat.detrended.no.ano <- array(NA, c(dim(slpmat.no.ano)))
        for(t in daily.seq) slpmat.detrended.no.ano[t,,] <- slpmat.no.ano[t,,] - slp.slope*t - slp.intercept
        
        slpmat.no.ano <- slpmat.detrended.no.ano
        rm(slpmat.detrended.no.ano)
        gc()
    }

    ## cluster sequence without the day of last year:
    cluster.sequence.clim <- as.vector(array(cluster.sequence, c(length(cluster.sequence)/n.years, n.years))[,1:n.years.clim])
    
    wr <- list(); for(cl in 1:n.cl) wr[[cl]] <- which(cluster.sequence.clim == cl)

    ## assign to slpwr[[1]] the slp of the topmost cluster to visualize (depending on the criteria chosen, and so on):
    slpwr <- list(); for(cl in 1:n.cl) slpwr[[cl]] <- slpmat[wr[[cl]],,, drop=F]
    slpwr.no.ano <- list(); for(cl in 1:n.cl) slpwr.no.ano[[cl]] <- slpmat.no.ano[wr[[cl]],,, drop=F]

    ## regime structure of psl:
    slpwrmean <- list(); for(cl in 1:n.cl) slpwrmean[[cl]] <-  apply(slpwr[[cl]], c(2,3), mean, na.rm=T)
    slpwrmean.no.ano <- list(); for(cl in 1:n.cl) slpwrmean.no.ano[[cl]] <-  apply(slpwr.no.ano[[cl]], c(2,3), mean, na.rm=T)

    psl.map <- list(); for(cl in 1:n.cl) psl.map[[cluster[cl]]] <- slpwrmean[[cl]]
    psl.map.no.anom <- list(); for(cl in 1:n.cl) psl.map.no.anom[[cluster[cl]]] <- slpwrmean.no.ano[[cl]]

    ## measure p-value of psl:
    mod.subdaily <- ifelse(subdaily, 4, 1)
    
    n.datos <- n.years * n.days.in.a.period(p,2001) * mod.subdaily 
    pslwrBoth <- pvalue.psl <- sig.psl <- list()
    for(cl in 1:n.cl) {
        pslwrBoth[[cl]] <- abind(slpmat, slpwr[[cl]], along = 1)
        pvalue.psl[[cl]] <- apply(pslwrBoth[[cl]], c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
        sig.psl[[cluster[cl]]] <- pvalue.psl[[cl]]
        gc()
    }
    
    ## create and save figure(s) with regime impact on var and regime anomalies for chosen month:      
    n.cl.sheet <- 4 ## maximum number of clusters for sheet
    n.sheets <- ceiling(n.cl / n.cl.sheet)  ## four is the maximum number of clusters to show in one sheet

    cl.mod <- c(); for(i in 1:n.sheets) if(n.cl >= n.cl.sheet*i) { cl.mod[i] <- 0 } else { cl.mod[i] <- n.cl.sheet*i - n.cl }

    cl.seq <- list(); for(i in 1:n.sheets) cl.seq[[i]] <- list()
    for(i in 1:n.sheets) cl.seq[[i]][[n.cl]] <- (n.cl.sheet*(i-1) + 1):((n.cl.sheet*i) - cl.mod[i])          

    cat("Generating regime figures. Please wait...\n")

    no.anom <- TRUE ## if TRUE, draw the psl maps both for anomalies and for the normal values. If FALSE, only draw the psl maps for the anomalies.      
    mod.anom <- ifelse(no.anom, 2, 1)

    if(two.rean) { dataset.string <- paste0(rean.impact.name," reanalysis (left); ", rean.name, " reanalysis (center and right)"); rean.string <- "two_rean" } else { dataset.string <- paste0(rean.name," reanalysis"); rean.string <- "one_rean"}
    
    ## if figures = 1, draw maps in anomalies; if figures = 2, draw maps with normal values
    for(figures in 1:mod.anom){
        print(paste0("Figure ", figures))
        for(sheet in 1:n.sheets){        
            if(figures == 1) fileoutput <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_", rean.string,".png")
            if(figures == 2) fileoutput <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_no_anomalies_", rean.string,".png")

            ## check if boxes with cluster domain have to be added or not:
            if(box.cluster) my.box <- c(lon.min, lat.min, lon.max, lat.max) else my.box <- NULLbb ## eventual box with cluster spatial domain for psl figures
            if(box.impact) my.box.impact <- c(lon.min, lat.min, lon.max, lat.max) else my.box.impact <- NULL  ## eventual box with cluster spatial domain for impact figures

            png(filename=fileoutput, width=3001, height=3700)
            plot.new()
            
            ## regime psl anomaly maps:
            map.xpos <- end.map.clim + 0.01 ##0.27
            map.width <- 0.73 - map.xpos ##0.42
            pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745))        
            y.width=0.18
            
            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){            
                par(fig=c(map.xpos, map.xpos + map.width, pos.y.cl[i], pos.y.cl[i] + y.width), new=TRUE)
                if(i == 1) par(fig=c(map.xpos + 0.003, map.xpos + map.width - 0.003, pos.y.cl[i], pos.y.cl[i] + y.width), new=TRUE) ## strange quirks of R
                if(i == 1) mod.xlab.dist <- 1.5 else mod.xlab.dist <- 1 
               

                if(figures == 1) my.map <- psl.map[[cl]] else my.map <- psl.map.no.anom[[cl]]
                if(figures == 1) my.my.brks <- my.brks else my.my.brks <- my.brks.no.anom
                if(figures == 1) my.my.cols <- my.cols else my.my.cols <- my.cols.no.anom
                if(figures == 1) my.line <- "F1FF1F" else my.line <- 1
                
                PlotEquiMap2(my.map, bigarea.lon, bigarea.lat, filled.continents=FALSE, brks=my.my.brks, cols=my.my.cols, sizetit=1.2, contours=t(my.map), brks2=my.my.brks, intxlon=20, intylat=20, drawleg=F, cex.lab=1.5, contours.lty=my.line, continents.col="black", boxx=my.box, boxx.col=box.col, boxx.lwd=4, countries=my.countries, xlabel.dist=mod.xlab.dist, contours.zero=my.contours.zero)

                if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/2, col=wind.color, pch=farms.style, lwd=4)

                i=i+1
            }
            
            ## Legend anomaly maps:
            legend1.xpos <- map.xpos ##0.4
            legend1.width <- map.width ##0.30
            legend1.cex <- 3
            pos_y1 <- 0.052; pos_y2 <- 0.083 # 0.045; 0.085
            
            par(fig=c(legend1.xpos, legend1.xpos + legend1.width, pos_y1, pos_y2), new=TRUE)
            ##ColorBar3(my.brks, cols=my.cols[2:(length(my.cols)-1)], vert=FALSE, cex=legend1.cex, subset=my.subset)
            my.subsample <- 2
            ColorBar(my.my.brks[2:(l(my.my.brks)-1)], cols=my.my.cols[2:(length(my.my.cols)-1)], vert=FALSE, label_scale=legend1.cex, bar_limits=c(my.my.brks[2], my.my.brks[l(my.my.brks)-1]), col_inf=my.my.cols[1], col_sup=my.my.cols[l(my.my.cols)], subsample=my.subsample)
            
            mtext(side=4, paste0(" ", psl.unit), cex=legend1.cex, las=1) ## las=1 is to display in horizontal instead of vert
            
            ## title anomaly maps:
            title1.xpos <- 0.3
            title1.width <- 0.44
            pos.y.title.cl <- rev(c(0.2855, 0.5005, 0.7155, 0.9305))
            
            ## title anomaly maps:
            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){    
                par(fig=c(map.xpos, map.xpos + map.width, pos.y.title.cl[i], pos.y.title.cl[i] + 0.005), new=TRUE)
                mtext(paste0(regime.title[cl]," ", psl.name, " anomaly"), font=2, cex=4)
                i <- i + 1
            }
            
            ## Impact maps:
            if(impact.data == TRUE ){
                impact.xpos <- 0
                impact.width <- end.map.clim - impact.xpos ##0.26
                my.intx <- 20
                my.inty <- 20
                if(stations) my.intx <- my.inty <- 2
                pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745))

                i <- 1
                impRel.mod <- sig.mod <- list()
                for(cl in cl.seq[[sheet]][[n.cl]]){
                    par(fig=c(impact.xpos, impact.xpos + impact.width, pos.y.cl[i], pos.y.cl[i] + y.width), new=TRUE)
                    
                    if(rayas) my.dots <- NULL else my.dots <- t(sig[[cl]] < pval)

                    if(area != "EU_CF"){
                        my.imp <- impRel[[cl]]
                        my.imp.brks <- my.brks.var
                        my.imp.col <- my.cols.var
                    } else {
                        my.imp <- imp[[cl]]
                        my.imp.brks <- my.brks.cf
                        my.imp.cols <- my.cols.cf
                    }

                    PlotEquiMap2(my.imp, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=my.imp.brks, cols=my.imp.cols, intxlon=my.intx, intylat=my.inty, drawleg=F, dots=my.dots, cex.lab=1.5, continents.col="black", countries=my.countries, boxx=my.box.impact, boxx.col=box.col, boxx.lwd=4, contours.zero=my.contours.zero)
                    
                    ## beware that the hatching() function only works if longitude vales are continuous.
                    ## The discontinuity between 360 degrees and 0 degrees is not considered.
                    ## If your lon values go from 0 to 360, you have to change the lon values and its order inside all variables to plot!!!
                    if(rean.name == "ERA-Interim"){ ## for JRA-55 you need a similar modification but with different numbers (see old file)
                        imp.area.lon.mod <- c(imp.area.lon[66:79] - 360, imp.area.lon[1:65])
                        sig.mod[[cl]] <- sig[[cl]][, c(66:79, 1:65)]

                        if(rayas) hatching(lats=imp.area.lat, lons=imp.area.lon.mod, mask=t(sig.mod[[cl]] < pval), dens = 4, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
                    } else { ## no changes needed:
                        if(rayas) hatching(lats=imp.area.lat, lons=imp.area.lon, mask=t(sig[[cl]] < pval), dens = 4, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)     
                    }

                    if(stations){
                        test <- cbind(varstatwrmeanRel[[cl]], findInterval(varstatwrmeanRel[[cl]], my.brks.var), my.cols.var[findInterval(varstatwrmeanRel[[cl]], my.brks.var)])
                        points(my.stations$V1 + 360, my.stations$V2, cex=1, col=test[,3])
                    }
                    
                    if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size/2, col=wind.color, pch=farms.style, lwd=4)

                    i <- i + 1
                } ## close for on cl
                
                ## Title impact maps:
                title2.xpos <- 0.01
                title2.width <- end.map.clim #0.30
                pos.y.title.cl <- rev(c(0.2855, 0.5005, 0.7155, 0.9305))

                i <- 1
                for(cl in cl.seq[[sheet]][[n.cl]]){
                    par(fig=c(title2.xpos, title2.xpos + title2.width, pos.y.title.cl[i], pos.y.title.cl[i] + 0.005), new=TRUE)
                    mtext(paste0(regime.title[cl], " ", var.name.full[var.num], " anomalies"), font=2, cex=4)
                    i <- i + 1
                }
                
                ## Legend impact maps:
                legend2.xpos <- 0.01
                legend2.width <- end.map.clim - 0.02
                legend2.cex <- 3
                
                ##my.subset2 <- match(values.to.plot2, my.brks.var)
                ##pos_y1 <- 0.045; pos_y2 <- 0.085
                pos_y1 <- 0.052 ; pos_y2 <- 0.083
                if(stations) {pos_y1 <- 0.052; pos_y2 <- 0.083}
                
                par(fig=c(legend2.xpos, legend2.xpos + legend2.width, pos_y1, pos_y2), new=TRUE)
                
                my.subsample <- 2; my_label_scale <- 3
                if(stations) { my.subsample <- 1; my_label_scale <- 3}
                
                if(area != "EU_CF"){
                    ColorBar(brks=round(100*my.imp.brks[2:(l(my.imp.brks)-1)],0), cols=my.imp.cols[2:(length(my.imp.cols)-1)], vert=FALSE, label_scale=my_label_scale, bar_limits=c(100*my.imp.brks[2],100*my.imp.brks[l(my.imp.brks)-1]), col_inf=my.imp.cols[1], col_sup=my.imp.cols[l(my.imp.cols)], subsample=my.subsample)
                    mtext(side=4,"%", cex=legend2.cex, las=1)  
                } else {
                    ColorBar(brks=my.imp.brks[2:(l(my.imp.brks)-1)], cols=my.imp.cols[2:(length(my.imp.cols)-1)], vert=FALSE, label_scale=my_label_scale, bar_limits=c(my.imp.brks[2], my.imp.brks[l(my.imp.brks)-1]), col_inf=my.imp.cols[1], col_sup=my.imp.cols[l(my.imp.cols)], subsample=1)
                }
       
            } ## close if on impact.data
                    
            ## Frequency plots:
            freq.max <- 100
            if(stations) freq.max <- 100
            
            ##fre1.NA <- fre1; fre2.NA <- fre2; fre3.NA <- fre3; fre4.NA <- fre4     
            barplot.xpos <- 0.75
            barplot.width <- 0.25
            pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745))

            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){        
                par(fig=c(barplot.xpos, barplot.xpos + barplot.width, pos.y.cl[i], pos.y.cl[i] + y.width - 0.01), new=TRUE)
                barplot.freq(100*fre[[cl]], year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
                i <- i + 1
            }
            
            ## Title Frequency maps:
            title3.xpos <- 0.75
            title3.width <-0.25
            pos.y.title.cl <- rev(c(0.2855, 0.5005, 0.7155, 0.9305))

            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){
                par(fig=c(title3.xpos, title3.xpos + title3.width, pos.y.title.cl[i], pos.y.title.cl[i] + 0.005), new=TRUE)
                mtext(paste0(regime.title[cl], " Frequency"), font=2, cex=4) # paste0 doesn't work inside an expression!
                i <- i + 1
            }
            
            ## % on Frequency plots:
            symbol.xpos <- 0.74
            symbol.width <- 0.01
            pos.y.cl <- rev(c(0.10, 0.28, 0.315, 0.495) + c(0.17, 0.21, 0.39, 0.425))

            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){
                par(fig=c(symbol.xpos, symbol.xpos + symbol.width, pos.y.cl[i], pos.y.cl[i] + 0.01), new=TRUE)
                mtext("%", cex=3.3)
                i <- i + 1
            }
            
            ## mean frequency on Frequency plots:
            if(mean.freq){
                symbol.xpos.basic <- 0.83 ## to use when there is only the frequency
                symbol.width <- 0.1
                symbol.xpos <- symbol.xpos.basic
                pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745))

                i <- 1
                for(cl in cl.seq[[sheet]][[n.cl]]){
                    if(stations && MannKendall(fre[[cl]])$sl[1] < pval) symbol.xpos=0.78
                    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, pos.y.cl[i] + 0.163, pos.y.cl[i] + 0.163 + 0.01), new=TRUE)
                    mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre[[cl]]),1),"%"))),cex=3.5)
                    symbol.xpos <- symbol.xpos.basic
                    i <- i + 1
                }
                
            }

            ## Sen's slope on Frequency plots:
            if(stations){
                symbol.xpos <- 0.87
                symbol.width <- 0.1
                pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745))

                i <- 1
                for(cl in cl.seq[[sheet]][[n.cl]]){
                    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, pos.y.cl[i] + 0.163, pos.y.cl[i] + 0.163 + 0.01), new=TRUE)
                    if(MannKendall(fre[[cl]])$sl[1] < pval) mtext(paste0("s=",round(10*sens.slope(100*fre[[cl]])$estimates,1),"%/10yrs"),cex=3.5)
                    i <- i + 1
                }
                
            }
            
            ## Subtitle frequency maps:
            map.title.xpos <- 0.96
            map.title.width <- 0.04

            pos.y.cl <- rev(c(0.10, 0.315, 0.53, 0.745)) - 0.023

            i <- 1
            for(cl in cl.seq[[sheet]][[n.cl]]){
                par(fig=c(map.title.xpos, map.title.xpos + map.title.width, pos.y.cl[i], pos.y.cl[i] + 0.01), new=TRUE)
                mtext("year", cex=3)
                i <- i + 1
            }
            
            dev.off() # for saving 4 png

            if(figures == 1){ ## if we are generating the figures in anomalies, it must be formatted with BSC conventions:
                cut.bottom <- c(2680, 1900, 1120, 340) ## pixel to cut starting from the bottom for each of the four rows of the images
                
                fileoutput.maps <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_maps_",rean.string,".png")
                system(paste0("convert ",fileoutput," -crop +0-", cut.bottom[i-1]," +repage ",fileoutput.maps)) # remove XXXX points from bottom
                
                fileoutput.caption <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_caption_",rean.string,".png")
                system(paste0("convert ",fileoutput," -crop +0+3400 +repage ",fileoutput.caption)) # cut the lower part of the strip only with the color legends by removing top part

                fileoutput.both <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_unformatted_both_",rean.string,".png")
                system(paste0("montage ",fileoutput.maps," ",fileoutput.caption," -tile 1x2 -geometry +0+0 ",fileoutput.both))
                
                ## same image formatted for the catalogue:
                fileoutput2 <- paste0(workdir,"/",year.end,"_",my.period[p],"_regime_anomalies_", rean.string,"_part_", sheet,"-",n.sheets,".png")

                cluster.string <- paste0(round(cl.lat.min.legend,2), deg, cl.lat.min.legend.letter,"-", round(cl.lat.max.legend,2), deg, cl.lat.max.legend.letter,", ", round(cl.lon.min.legend,2), deg, cl.lon.min.legend.letter,"-", round(cl.lon.max.legend,2), deg, cl.lon.max.legend.letter)

                my.region.string <- paste0("Region. Left: ", imp.area.name," (", round(imp.area.lat.min.legend,2), deg, imp.area.lat.min.legend.letter,"-", round(imp.area.lat.max.legend,2), deg, imp.area.lat.max.legend.letter,", ", round(imp.area.lon.min.legend,2), deg, imp.area.lon.min.legend.letter,"-", round(imp.area.lon.max.legend,2), deg,imp.area.lon.max.legend.letter,"). Right: ", bigarea.name," (", round(lat.min.legend,2), deg, lat.min.legend.letter,"-", round(lat.max.legend,2), deg,lat.max.legend.letter,", ", round(lon.min.legend,2), deg, lon.min.legend.letter,"-", round(lon.max.legend,2), deg, lon.max.legend.letter, ")")
                
                system(paste0(fig2catalog.dir, "/fig2catalog.sh -s 0.90 -r 150 -m 150 -t '",rean.name," / ",var.name.full[var.num]," and ",psl.name.full," / Monthly anomalies and frequencies \n", period.name[p]," / ",year.start,"-",year.end.clim,"' -c '", my.region.string, "\n","Cluster domain: ", cluster.string, "\n","Reference dataset: ", dataset.string,"' ", fileoutput.both," ", fileoutput2))

                system(paste0("rm ", fileoutput, " ", fileoutput.caption, " ", fileoutput.maps, " ", fileoutput.both))

            } ## close if on 'figures'
            
        } ## close for on 'sheet'
        
    } ## close for on 'figures'

    ##
    ## save WR impact on CF for S2S4E:
    ##
    if(area == "EU_CF"){
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        if(var.name[var.num] != "sfcWind") {
            save(imp, sig, slpwrmean, sig.psl, imp.area.lon, imp.area.lat, bigarea.lon, bigarea.lat, file=paste0(workdir, "/WR_impact_on_CF.RData")) ## save the absolute impact anomalies "imp" for the 4 regimes
        } else {
            save(impRel, sig, slpwrmean, sig.psl, imp.area.lon, imp.area.lat, bigarea.lon, bigarea.lat, file=paste0(workdir, "/WR_impact_on_sfcWind.RData"))
        }
    }
    ##
    ## save climatological regime anomalies of SLP and sfcWind for EDPR:
    ##
    if(save.txt && report.type != "anexo"){  
        cat(paste0("Saving monthly ", var.name[var.num]," and ", psl.name," regime anomalies for ", area,". Please wait...\n"))

        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos")))   ## create subdir /txt, if it doesn't exist yet:
        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6"))) 
        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/10-m_Wind_Speed_regime_anomalies_", rean2load.name)))
        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/10-m_Wind_Speed_regime_anomalies_", rean2load.name, "/", area)))  

        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/Sea_Level_Pressure_regime_anomalies_", rean.name)))  
        dir.create(file.path(paste0(workdir,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/Sea_Level_Pressure_regime_anomalies_", rean.name, "/", area)))  

        for(cl in 1:n.cl){
            ## save var (i.e: wind) anomalies for climatological period:
            ## SLP is in hPa, the same unit of measure used in the figures, while wind speed is in m/s:
            sfcWindAnomRegEDPR <- unname(impRel[[cl]])

            write.table(round(100*sfcWindAnomRegEDPR,1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/10-m_Wind_Speed_regime_anomalies_", rean2load.name, "/", area, "/",  area, "_", year.start, "-", year.end.clim, "_",my.period[p],"_", gsub(" ", "_", var.name.full[var.num]),"_relative_anomalies_",rean2load.name, "_regime_num_", cl,".txt"), row.names=round(imp.area.lat,2), col.names=c(paste0("Lat/Lon\t", round(imp.area.lon[1],2)), as.numeric(round(imp.area.lon[-1],2))), sep="\t", quote=FALSE)    

            ## save also a copy in the /Western_USA subfolder, if it was already created:
            workdir_west <- paste0(rootdir, "/", "Western_USA", "/", year.end, "_", my.period[p])   # working dir where output files will be generated

            if(area != "Western_USA" && dir.exists(workdir_west)){
                dir.create(file.path(paste0(workdir_west,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/10-m_Wind_Speed_regime_anomalies_", rean2load.name, "/", area)))  

                write.table(round(100*sfcWindAnomRegEDPR,1), file=paste0(workdir_west, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/10-m_Wind_Speed_regime_anomalies_", rean2load.name, "/", area, "/",  area, "_", year.start, "-", year.end.clim, "_",my.period[p],"_", gsub(" ", "_", var.name.full[var.num]),"_relative_anomalies_",rean2load.name, "_regime_num_", cl,".txt"), row.names=round(imp.area.lat,2), col.names=c(paste0("Lat/Lon\t", round(imp.area.lon[1],2)), as.numeric(round(imp.area.lon[-1],2))), sep="\t", quote=FALSE)    
            }
            
            ## save slp regime anomalies for climatological period:
            slpAnomRegEDPR <- unname(slpAnomPeriodMean)

            write.table(round(slpAnomRegEDPR,1), file=paste0(workdir, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/Sea_Level_Pressure_regime_anomalies_", rean.name, "/", area, "/", area, "_", year.start, "-", year.end.clim, "_",my.period[p],"_", psl.name,"_anomalies_", rean.name,"_regime_num_", cl, ".txt"), row.names=round(bigarea.lat,2), col.names=c(paste0("Lat/Lon\t", round(bigarea.lon[1],2)), as.numeric(round(bigarea.lon[-1],2))), sep="\t", quote=FALSE)

            ## save also a copy in the /Western_USA subfolder, if it was already created:
            if(area != "Western_USA" && dir.exists(workdir_west)){
                dir.create(file.path(paste0(workdir_west,"/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/Sea_Level_Pressure_regime_anomalies_", rean.name, "/", area)))
                
                write.table(round(slpAnomRegEDPR,1), file=paste0(workdir_west, "/EDPR_USA_weather_regimes_",year.end,"_",my.period[p],"_datos/Figures_2-4-6/Sea_Level_Pressure_regime_anomalies_", rean.name, "/", area, "/", area, "_", year.start, "-", year.end.clim, "_",my.period[p],"_", psl.name,"_anomalies_", rean.name,"_regime_num_", cl, ".txt"), row.names=round(bigarea.lat,2), col.names=c(paste0("Lat/Lon\t", round(bigarea.lon[1],2)), as.numeric(round(bigarea.lon[-1],2))), sep="\t", quote=FALSE)
            }
            
            rm(sfcWindAnomRegEDPR, slpAnomRegEDPR, workdir_west)

        } ## close for on cl
        
     } ## close if on save.txt
    
} # close 'p' on 'period'
      
#####################################################################################
##                        Plot influence maps                                       #
#####################################################################################

validation <- FALSE
if(validation && !stations){
    cat("Generating influence maps. Please wait...\n")

    area.orig <- area
    
    ##mean.lab <-c(0, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 10)/4
    if(box.cluster) my.box <- c(lon.min, lat.min, lon.max, lat.max) else my.box <- NULL   ## eventual gray box with cluster spatial domain

    ## loop for each month:
    period.orig <- period
    i <- 1
    for(p in period){
        print(paste("Period:", period.name[p]))
        
        ## load the cluster names from the file already saved, if regimes come from a reanalysis:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # working dir where output files will be generated
        dir.create(file.path(workdir))
        
        load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_","psl",".RData"))  ## load 'cluster.sequence' variable
        if(area != area.orig) area <- area.orig
    
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
        if(!identical(period, period.orig)) period <- period.orig
        
        ## load impact data only if it is available, if not it will leave an empty space in the composition:
        if(file.exists(paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_", rean2load.name,".RData"))){
            impact.data <- TRUE
            print(paste0("Impact data for variable ",var.name[var.num] ," available for reanalysis ", rean.name))
            load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_", rean2load.name,".RData"))
            if(area != area.orig) area <- area.orig

            workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   # repristinate the working dir because it may have changed because of load()
            if(!identical(period, period.orig)) period <- period.orig
            
        } else {
            impact.data <- FALSE
            print(paste0("Impact data for variable ",var.name[var.num] ," not available for reanalysis ", rean.name))
        }
        
        ## ClusterName.file <- paste0(workdir,"/",year.end,"_", my.period[p],"_","ClusterNames",".RData")
        ##if(!file.exists(ClusterName.file)) stop(paste0("file: ",ClusterName.file," missing"))  # check if file exists or not
        ##load(ClusterName.file) # load cluster names 

        ## repristinate the working dir because it may have changed because of load():
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])   
        if(!identical(period, period.orig)) period <- period.orig
        
        ## assign to each cluster its regime:
        cluster <- c(); for(cl in 1:n.cl) cluster[cl] <- cl  ## not correct but we are only interested in the sum of values, not in the values themselves
        
        impRel <- list(); for(cl in 1:n.cl) impRel[[cluster[cl]]] <- varwrmeanRel[[cl]]
        
        if(box.cluster) my.box <- c(lon.min, lat.min, lon.max, lat.max) else my.box <- NULL   ## eventual gray box with cluster spatial domain

        impRelSum <- impRel[[1]]*0 ## to create a void array of the same dimensions of impRel
        for(cl in 1:n.cl) impRelSum <- impRelSum + abs(impRel[[cl]])

        ## color legends:
        sum.cols <- rev(c('#a50026','#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4','#313695'))
        sum.brks <- c(0, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 10)
        ##sum.lab <-c(0, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 10)

        mean.cols <- rev(c('darkred','#a50026','#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4','#313695'))
        mean.brks <- c(0, 0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16, 0.18, 0.20, 100)
        ##mean.lab <-c(0, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 10)/4

        ##aver.cols <- rev(c('darkred','#a50026','#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4','#313695'))
        ##aver.brks <- c(-1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)


        ## plot Sum impact:
        fileoutput.influence <- paste0(workdir,"/",year.end,"_",my.period[p],"_influence_sum.png")
        png(filename=fileoutput.influence, width=1000, height=750) #550, height=650)
        
        plot.new()
        par(fig=c(0.01,0.99, 0.07, 0.99), new=TRUE)  
        PlotEquiMap(impRelSum, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=sum.brks, cols=sum.cols, axelab=TRUE, toptitle=paste0("Total influence WRs in ",period.name[p]), drawleg=F, boxlim=my.box, boxcol=box.col, boxlwd=1)
        if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size, col=wind.color, pch=farms.style, lwd=2)

        par(fig=c(0.2,0.8, 0.00, 0.06), new=TRUE)  
        ColorBar(brks=round(100*sum.brks[1:(l(sum.brks)-1)],0), cols=sum.cols[1:(length(sum.cols)-1)], vert=FALSE, label_scale=1.6, col_sup=sum.cols[l(sum.cols)])

        par(fig=c(0.7,0.9, 0.055, 0.08), new=TRUE)  
        mtext("%", font=2, cex=1.5)

        ##par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE)
        ##mtext(paste0("Sum of the absolute WR impact on ",var.name[var.num]), font=2, cex=2)
        
        dev.off()
        
        ##
        ## plot Mean impact:
        ##
        
        impRelMean <- impRelSum / n.cl
                
        fileoutput.influence <- paste0(workdir,"/",year.end,"_",my.period[p],"_influence_mean.png")
        png(filename=fileoutput.influence, width=1000, height=750) #550, height=650)
        
        plot.new()
        par(fig=c(0.01,0.99, 0.07, 0.99), new=TRUE)  
        PlotEquiMap(impRelMean, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=mean.brks, cols=mean.cols, axelab=TRUE, toptitle=paste0("Total influence WRs in ",period.name[p]), drawleg=F, boxlim=my.box, boxcol=box.col, boxlwd=1)
        if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size, col=wind.color, pch=farms.style, lwd=2)

        par(fig=c(0.2,0.8, 0.00, 0.06), new=TRUE)  
        ColorBar(brks=round(100*mean.brks[1:(l(mean.brks)-1)],0), cols=mean.cols[1:(length(mean.cols)-1)], vert=FALSE, label_scale=1.6, col_sup=mean.cols[l(mean.cols)])
        par(fig=c(0.7,0.9, 0.055, 0.08), new=TRUE)  
        mtext("%", font=2, cex=1.5)
        
        dev.off()

        ## increase i for plotting yearly maps:
        if(i == 1) impRelMeanAll <- impRelMean
        if(i != 1 && p < 13) impRelMeanAll <- impRelMeanAll + impRelMean
        i <- i + 1
        

    } ## close p on month

    ##
    ## same map but for the mean of all periods available (it is saved in the dir with the LAST month to average, so you know on which months it is based:
    ##
    
    pp <- length(which(period < 13))
    impRelMeanAll <- impRelMeanAll / pp # mean over the months in period (usually January to December, but can be less)

    fileoutput.influence <- paste0(workdir,"/",year.end,"_",my.period[p],"_influence_mean_all_periods.png")
    png(filename=fileoutput.influence, width=1000, height=750) #550, height=650)   
    plot.new()
    par(fig=c(0.01,0.99, 0.07, 0.99), new=TRUE)  
    PlotEquiMap(impRelMeanAll, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=mean.brks, cols=mean.cols, axelab=TRUE, toptitle=paste0("Total influence of WRs on ", var.name[var.num]), drawleg=F, boxlim=my.box, boxcol=box.col, boxlwd=1) #, intxlon=my.intx, intylat=my.inty)
    if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size, col=wind.color, pch=farms.style, lwd=2)

    par(fig=c(0.2,0.8, 0.00, 0.06), new=TRUE)  
    ColorBar(brks=round(100*mean.brks[1:(l(mean.brks)-1)],0), cols=mean.cols[1:(length(mean.cols)-1)], vert=FALSE, label_scale=1.6, col_sup=mean.cols[l(mean.cols)])
    par(fig=c(0.7,0.9, 0.055, 0.08), new=TRUE)  
    mtext("%", font=2, cex=1.5)
    dev.off()


    
    ##
    ## measure and plot the correlation, st.dev. ratio and bias between the reconstructed and the observed MEAN wind speed:
    ##
    
    cross <- TRUE ##TRUE ## choose if to measure the score in cross-validation or not
   
    mod.cross <- ifelse(cross, "cross","no_cross")   ## suffix to add to the file name of the figure
    
    period.orig <- period
    area.orig <- area
    for(p in period){
        print(paste("Period:", period.name[p]))

        my.pos.period <- pos.period(1,p)
        if(subdaily) my.pos.period <- (4*pos.period(1,p)-3)[1]:(4*pos.period(1,p))[length(pos.period(1,p))]
        ndays <- length(my.pos.period) ## = n.days.in.a.period(p,1), *4 if 6-hourly

        ## load cluster data (my.cluster$cluster):
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])  
        load(file=paste0(workdir, "/", year.end,"_", my.period[p], "_psl.RData"))
        if(!identical(period, period.orig)) period <- period.orig
        if(area != area.orig) area <- area.orig

        ## update the working directory, because the period could have changed:
        workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])

        ## working dir where output files will be generated:
        dir.create(file.path(workdir)) 
        
        cluster.sequence <- my.cluster$cluster  ## daily sequence only for period p (the one just loaded)
        if(subdaily) cluster.sequence <- rep(my.cluster$cluster, each=4) ## repeat 4 times the daily cluster series to create the 6-hourly cluster series

        ## select only var daily anomalies of period p; if 6-hourly, select only var 6-hourly anomalies fo period p:
        ## Notice that only wind and prec anomalies are treated as relative anomalies; tas and psl anomalies are treated using 'absolute' anomalies.
        if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr" || var.name[var.num] == "psl") var.mes <- vareuFullAnomRel[1,1,, my.pos.period,,] else var.mes <- vareuFullAnom[1,1,, my.pos.period,,] 

        ## group year and dayly/6-hourly data together in the same dimension (the first one):
        var.mes.vert <- array(aperm(var.mes[,,,, drop=FALSE], c(2,1,3,4)), c(dim(var.mes)[1] * dim(var.mes)[2], dim(var.mes)[3], dim(var.mes)[4]))

        
        ## observed mean for all years:
        ## var.mean.obs <- apply(var.mes, c(3,4), mean)

        ## observed mean for each year:
        var.mean.obs <- var.p95.obs <- var.p5.obs <- array(NA, c(n.years, length(imp.area.lat), length(imp.area.lon)))
        
        print("Measuring observed mean var for each year")
        for(y in year.start:year.end){
            y2 <- y - year.start + 1
            cat(paste0(y, " "))
            
            ## select only days of year y2:    
            var.mes.year <- var.mes[y2,,,]

            ## observed mean for year y2:
            var.mean.obs[y2,,] <- apply(var.mes.year, c(2,3), mean)

            ## observed 95th and 5th percentile for year y2:
            var.p95.obs[y2,,] <- apply(var.mes.year, c(2,3), function(x) { quantile(x, .95) })
            var.p5.obs[y2,,] <- apply(var.mes.year, c(2,3), function(x) { quantile(x, .5) })

            ##cat(paste0("  p95: ", round(var.perc95.obs[y2,1,1],3)), " p95:", round(quantile(var.mes.year[,1,1], .95),3), " ")
        }

        
        if(!cross){
            ## regime sequences:
            wrs <- list(); for(cl in 1:n.cl) wrs[[cl]] <- which(cluster.sequence == cl)

            ## var anomalies only of selected mes and wr for the full period:
            var.wrs <- list(); for(cl in 1:n.cl) var.wrs[[cl]] <- var.mes.vert[wrs[[cl]],,]

            ## var average anomaly of selected mes and wr for the full period:
            var.wrs.mean <- array(NA, c(n.cl, length(imp.area.lat), length(imp.area.lon))) 
            for(cl in 1:n.cl) var.wrs.mean[cl,,] <- apply(var.wrs[[cl]], c(2,3), mean)

            ## var perc95 anomaly of selected mes and wr for the full period:
            var.wrs.p95 <- array(NA, c(n.cl, length(imp.area.lat), length(imp.area.lon))) 
            for(cl in 1:n.cl) var.wrs.p95[cl,,] <- apply(var.wrs[[cl]], c(2,3), function(x){quantile(x,.95)})

            ## var perc5 anomaly of selected mes and wr for the full period:
            var.wrs.p5 <- array(NA, c(n.cl, length(imp.area.lat), length(imp.area.lon))) 
            for(cl in 1:n.cl) var.wrs.p5[cl,,] <- apply(var.wrs[[cl]], c(2,3), function(x){quantile(x,.5)})
            
        } else {
            print("Computing cross-validation. Please wait...")

            ##var.clim.obs.cross <- list()
            var.wrs.mean.cross <- var.wrs.p95.cross <- var.wrs.p5.cross <- array(NA, c(n.years, n.cl, length(imp.area.lat), length(imp.area.lon))) 
            for(y in year.start:year.end){
                y2 <- y - year.start + 1
                cat(paste0(y, " "))

                ## remove the year to validate from var data used for training:
                var.mes.cross <- var.mes[-y2,,,]

                ## sequence with the days/period to remove for cross-validation:
                time.seq <- (y2-1)*ndays + 1:ndays
                
                ## convert dim year and days in one dim only
                ##var.mes.vert.cross <- array(aperm(var.mes.cross[,,,, drop=FALSE], c(2,1,3,4)), c(dim(var.mes.cross)[1] * dim(var.mes.cross)[2], dim(var.mes.cross)[3], dim(var.mes.cross)[4]))
                var.mes.vert.cross <- var.mes.vert[-time.seq,,] ## like row above, but faster

                ## cluster sequence without the days belonging to year y2:
                cluster.sequence.cross <- cluster.sequence[-time.seq]

                ## list with the days belonging to each regime 
                wrs.cross <- list(); for(cl in 1:n.cl) wrs.cross[[cl]] <- which(cluster.sequence.cross == cl)

                ## list with the wind speed anomalies of the days belonging to each regime:
                var.wrs.cross <- list(); for(cl in 1:n.cl) var.wrs.cross[[cl]] <- var.mes.vert.cross[wrs.cross[[cl]],,]

                ## average var observed anomaly of selected mes and wr for the full period:
                for(cl in 1:n.cl) var.wrs.mean.cross[y2, cl,,] <- apply(var.wrs.cross[[cl]], c(2,3), mean)

                ## p95 var observed anomaly of selected mes and wr for the full period:
                for(cl in 1:n.cl) var.wrs.p95.cross[y2, cl,,] <- apply(var.wrs.cross[[cl]], c(2,3), function(x) { quantile(x, .95)})

                ## p5 var observed anomaly of selected mes and wr for the full period:
                for(cl in 1:n.cl) var.wrs.p5.cross[y2, cl,,] <- apply(var.wrs.cross[[cl]], c(2,3), function(x) { quantile(x, .5)})

            } ## close for on y
        } # close if on cross

        ## average var reconstructed anomaly:

        wrs.num.year <- array(NA, c(n.years, n.cl))
        var.mean.recon.year <-  var.p95.recon.year <- var.p5.recon.year <- array(0, c(n.years, length(imp.area.lat), length(imp.area.lon)))
        print(mean(var.mean.recon.year))
        
        print("Reconstructing the mean for each year")
        for(y in year.start:year.end){
            y2 <- y - year.start + 1
            ##print(y)
            
            ## for chosen month and year y2, count the number of days belonging to a particular regime and year y2:
            for(cl in 1:n.cl) wrs.num.year[y2, cl] <- length(which(cluster.sequence[(y2-1)*ndays + (1:ndays)] == cl))
            
            ## for chosen month and year y2, reconstruct each average var for year y2 by multiplying for the WR monthly frequencies during year y2:
            if(!cross) for(cl in 1:n.cl) var.mean.recon.year[y2,,] <- var.mean.recon.year[y2,,] + var.wrs.mean[cl,,] * wrs.num.year[y2, cl] 
            if(cross) for(cl in 1:n.cl) var.mean.recon.year[y2,,] <-  var.mean.recon.year[y2,,] + var.wrs.mean.cross[y2, cl,,] * wrs.num.year[y2, cl]

            ## for chosen month and year y2, reconstruct each p95 var for year y2 by multiplying for the WR monthly frequencies during year y2:
            if(!cross) for(cl in 1:n.cl) var.p95.recon.year[y2,,] <- var.p95.recon.year[y2,,] + var.wrs.p95[cl,,] * wrs.num.year[y2, cl] 
            if(cross) for(cl in 1:n.cl) var.p95.recon.year[y2,,] <-  var.p95.recon.year[y2,,] + var.wrs.p95.cross[y2, cl,,] * wrs.num.year[y2, cl]

            ## for chosen month and year y2, reconstruct each p5 var for year y2 by multiplying for the WR monthly frequencies during year y2:
            if(!cross) for(cl in 1:n.cl) var.p5.recon.year[y2,,] <- var.p5.recon.year[y2,,] + var.wrs.p5[cl,,] * wrs.num.year[y2, cl] 
            if(cross) for(cl in 1:n.cl) var.p5.recon.year[y2,,] <-  var.p5.recon.year[y2,,] + var.wrs.p5.cross[y2, cl,,] * wrs.num.year[y2, cl]
            
        }

        ## divide for the total number of days/6-hourly periods in a month to get the average var reconstructed value:
        var.mean.recon.year <- var.mean.recon.year / ndays
        var.p95.recon.year <- var.p95.recon.year / ndays
        var.p5.recon.year <- var.p5.recon.year / ndays

        print("Correlating. Please wait...")
        cor.mean <- var.ratio <- bias <- bias.pv <- array(NA, c(length(imp.area.lat), length(imp.area.lon)))
        cor.p95 <- var.ratio.p95 <- bias.p95 <- array(NA, c(length(imp.area.lat), length(imp.area.lon)))
        cor.p5 <- var.ratio.p5 <- bias.p5 <- array(NA, c(length(imp.area.lat), length(imp.area.lon)))

        k <- 1
        for(i in 1:length(imp.area.lat)){
            for(j in 1:length(imp.area.lon)){
                cor.mean[i,j] <- cor(var.mean.recon.year[,i,j], var.mean.obs[,i,j])
                var.ratio[i,j] <- var(var.mean.recon.year[,i,j]) / var(var.mean.obs[,i,j])
                ##sd.ratio[i,j] <- sd(var.mean.recon.year[,i,j]) / sd(var.mean.obs[,i,j])
                bias[i,j] <- mean(var.mean.recon.year[,i,j] - var.mean.obs[,i,j])
                ##bias.pv[i,j] <- t.test(var.mean.recon.year[,i,j], var.mean.obs[,i,j], paired=TRUE)$p.value
                
                cor.p95[i,j] <- cor(var.p95.recon.year[,i,j], var.p95.obs[,i,j])
                var.ratio.p95[i,j] <- var(var.p95.recon.year[,i,j]) / var(var.p95.obs[,i,j])
                bias.p95[i,j] <- mean(var.p95.recon.year[,i,j] - var.p95.obs[,i,j])

                cor.p5[i,j] <- cor(var.p5.recon.year[,i,j], var.p5.obs[,i,j])
                var.ratio.p5[i,j] <- var(var.p5.recon.year[,i,j]) / var(var.p5.obs[,i,j])
                bias.p5[i,j] <- mean(var.p5.recon.year[,i,j] - var.p5.obs[,i,j])
                
                ## plot(year.start:year.end, 100*var.mean.obs[,i,j], type="o", col="black", ylim=100*c(-0.6,0.6), cex=.7, xlab="Year", ylab="Mean Wind Speed Anomaly (%)")
                ## lines(year.start:year.end, 100*var.mean.recon.year[,i,j], type="o",col="red", cex=.7)
                ## lines(year.start:year.end, rep(0, n.years), type="l", col="gray")
                ## text(1985, 60, labels=paste0("Point: ", k))
                ## text(2000, 60, labels=paste0("St.Dev.Ratio: ", round(sqrt(var.ratio[i,j]),2)))
                ## text(2012, 60, labels=paste0("Corr: ", round(cor.mean[i,j],2)))

                ## y <- 1981
                ## y2 <- y - year.start + 1
                ## y.tot <- var.wrs.mean[1,i,j] * wrs.num.year[y2,1] + var.wrs.mean[2,i,j ]* wrs.num.year[y2,2] + var.wrs.mean[3,i,j] * wrs.num.year[y2,3] + var.wrs.mean[4,i,j ]* wrs.num.year[y2,4]
                ## text(2000, -45, labels=paste0("Reconstructed mean wind speed anomaly year ", y,": ", paste(round(100*var.wrs.mean[1,i,j],1), "% *", wrs.num.year[y2,1], " + ", round(100*var.wrs.mean[2,i,j],1) , "% *", wrs.num.year[y2,2], " + ", round(100*var.wrs.mean[3,i,j],1) , "% *", wrs.num.year[y2,3], " + ", round(100*var.wrs.mean[4,i,j], 1), "% *", wrs.num.year[y2,4], " = ", round(100*y.tot, 1), " % / 120 = ", round(100*y.tot/120,1), "%")))
                
                ## y <- 1982
                ## y2 <- y - year.start + 1
                ## y.tot <- var.wrs.mean[1,i,j] * wrs.num.year[y2,1] + var.wrs.mean[2,i,j ]* wrs.num.year[y2,2] + var.wrs.mean[3,i,j] * wrs.num.year[y2,3] + var.wrs.mean[4,i,j ]* wrs.num.year[y2,4]
                ## text(2000, -50, labels=paste0("Reconstructed mean wind speed anomaly year ", y,": ", paste(round(100*var.wrs.mean[1,i,j],1), "% *", wrs.num.year[y2,1], " + ", round(100*var.wrs.mean[2,i,j],1) , "% *", wrs.num.year[y2,2], " + ", round(100*var.wrs.mean[3,i,j],1) , "% *", wrs.num.year[y2,3], " + ", round(100*var.wrs.mean[4,i,j], 1), "% *", wrs.num.year[y2,4], " = ", round(100*y.tot, 1), " / 120 = ", round(100*y.tot/120,1), "%")))

                ## y <- 1983
                ## y2 <- y - year.start + 1
                ## y.tot <- var.wrs.mean[1,i,j] * wrs.num.year[y2,1] + var.wrs.mean[2,i,j ]* wrs.num.year[y2,2] + var.wrs.mean[3,i,j] * wrs.num.year[y2,3] + var.wrs.mean[4,i,j ]* wrs.num.year[y2,4]
                ## text(2000, -55, labels=paste0("Reconstructed mean wind speed anomaly year ", y,": ", paste(round(100*var.wrs.mean[1,i,j],1), "% *", wrs.num.year[y2,1], " + ", round(100*var.wrs.mean[2,i,j],1) , "% *", wrs.num.year[y2,2], " + ", round(100*var.wrs.mean[3,i,j],1) , "% *", wrs.num.year[y2,3], " + ", round(100*var.wrs.mean[4,i,j], 1), "% *", wrs.num.year[y2,4], " = ", round(100*y.tot, 1), " / 120 = ", round(100*y.tot/120,1), "%")))

                ## y <- 1984
                ## y2 <- y - year.start + 1
                ## y.tot <- var.wrs.mean[1,i,j] * wrs.num.year[y2,1] + var.wrs.mean[2,i,j ]* wrs.num.year[y2,2] + var.wrs.mean[3,i,j] * wrs.num.year[y2,3] + var.wrs.mean[4,i,j ]* wrs.num.year[y2,4]
                ## text(2000, -60, labels=paste0("Reconstructed mean wind speed anomaly year ", y,": ", paste(round(100*var.wrs.mean[1,i,j],1), "% *", wrs.num.year[y2,1], " + ", round(100*var.wrs.mean[2,i,j],1) , "% *", wrs.num.year[y2,2], " + ", round(100*var.wrs.mean[3,i,j],1) , "% *", wrs.num.year[y2,3], " + ", round(100*var.wrs.mean[4,i,j], 1), "% *", wrs.num.year[y2,4], " = ", round(100*y.tot, 1), " / 120 = ", round(100*y.tot/120,1), "%")))

                k <- k + 1
            }
            
        } ## close for on i

        ## suffix to add to the file name of the figure:
        mod.cross <- ifelse(cross, "cross","no_cross")
        
        save(cor.mean, var.ratio, bias, cor.p95, var.ratio.p95, bias.p95, cor.p5, var.ratio.p5, bias.p5, file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,"_recon_", mod.cross,".RData"))

        
    } ## close p on period

    ##
    ## generate a composition of all months of all error index based on correlation:
    ##

    scores <- 1:9 ## if 1, plot cor.mean; if 2, plot cor.p95; if 3, plot cor.p5: if 4-5-6, plot st.dev.ratio for mean-p95-p5, By default, plot all them

    for(sc in scores){
    
        mod.cross <- ifelse(cross, "cross","no_cross")
        EU <- c(1:which(imp.area.lon >= lon.max)[1], (which(imp.area.lon >= 337)[1]:length(imp.area.lon)))  # restrict area to continental europe only
        
        p=12 ## to create composition during december
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])
        
        ## Two colors:
        corr.cols <- rev(c('#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061'))
        corr.brks <- c(-1, -0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9, 1)
        
        ## One color:
        ## ratio.stdev.cols <- c('#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f','#990000')
        ratio.stdev.cols <- c('white', '#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f')
        ratio.stdev.brks <- c(0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 1)
    

        ## Two colors:
        bias.cols <- rev(c('#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061'))
        bias.brks <- c(-1000, -0.15, -0.12, -0.09, -0.06, -0.03, 0.03, 0.06, 0.09, 0.12, 0.15, 1000)/100 ## for bias of relative wind speed anomalies (1=100%)
             
        if(sc == 1) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_corr_mean_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 2) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_corr_p95_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 3) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_corr_p5_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 4) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_stdev_ratio_mean_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 5) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_stdev_ratio_p95_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 6) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_stdev_ratio_p5_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 7) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_bias_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 8) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_bias_p95_composition.png"), width=780, height=1300) #550, height=650)
        if(sc == 9) png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_bias_p5_composition.png"), width=780, height=1300) #550, height=650)

        plot.new()
        par(xpd=TRUE)
        text(x=-0.1, y=0.58, labels="Autumn                             Summer                              Spring                              Winter", cex=1.8, srt=90)
        par(xpd=FALSE)

        period.orig <- period
        area.orig <- area
        for(p in c(12, 1:11)){

            ## load 'cor.mean' to plot it:
            workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])
            load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,"_recon_", mod.cross,".RData"))
            if(!identical(period, period.orig)) period <- period.orig
            if(area != area.orig) area <- area.orig

            
            if(p == 12 || p == 1 || p == 2) yMod <- 0.77
            if(p >= 3 && p <= 5) yMod <- 0.58
            if(p >= 6 && p <= 8) yMod <- 0.39
            if(p == 9 || p == 10 || p == 11) yMod <- 0.2
            if(p == 13 || p == 14) yMod <- 0.62
            if(p == 15 || p == 16) yMod <- 0.2
            
            if(p == 12 || p == 3 || p == 6 || p == 9) xMod <- 0.05
            if(p == 1 || p == 4 || p == 7 || p == 10) xMod <- 0.35
            if(p == 2 || p == 5 || p == 8 || p == 11) 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)

            if(sc == 1) PlotEquiMap(cor.mean[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=corr.brks, cols=corr.cols, axelab=F, drawleg=F)
            if(sc == 2) PlotEquiMap(cor.p95[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=corr.brks, cols=corr.cols, axelab=F, drawleg=F)
            if(sc == 3) PlotEquiMap(cor.p5[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=corr.brks, cols=corr.cols, axelab=F, drawleg=F)
            if(sc == 4) PlotEquiMap(sqrt(var.ratio[,EU]), imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=ratio.stdev.brks, cols=ratio.stdev.cols, axelab=F, drawleg=F)
            if(sc == 5) PlotEquiMap(sqrt(var.ratio.p95[,EU]), imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=ratio.stdev.brks, cols=ratio.stdev.cols, axelab=F, drawleg=F)
            if(sc == 6) PlotEquiMap(sqrt(var.ratio.p5[,EU]), imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=ratio.stdev.brks, cols=ratio.stdev.cols, axelab=F, drawleg=F)
            if(sc == 7) PlotEquiMap(bias[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=bias.brks, cols=bias.cols, axelab=F, drawleg=F)
            if(sc == 8) PlotEquiMap(bias.p95[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=bias.brks, cols=bias.cols, axelab=F, drawleg=F)
            if(sc == 9) PlotEquiMap(bias.p5[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=bias.brks, cols=bias.cols, axelab=F, drawleg=F)

            if(p <= 12) par(fig=c(xMod, xMod + 0.3, yMod + 0.166, yMod + 0.176), new=TRUE)
            if(p > 12) par(fig=c(xMod + 0.07, xMod + 0.07 + 0.3, yMod +0.21 + 0.166, yMod +0.21 + 0.176), new=TRUE)
            mtext(my.period[p], font=1, cex=1.6)

        } # close 'p' on 'period'

        par(fig=c(0.1,0.9, 0.15, 0.20), new=TRUE)  
        if(sc == 1 || sc == 2 || sc == 3) ColorBar(brks=round(corr.brks[1:(length(corr.brks))],1), cols=corr.cols[1:(length(corr.cols))], vert=FALSE, label_scale=1.4)
        if(sc == 4 || sc == 5 || sc == 6) ColorBar(brks=round(ratio.stdev.brks[1:(length(ratio.stdev.brks))],3), cols=ratio.stdev.cols[1:(length(ratio.stdev.cols))], vert=FALSE, label_scale=1.4)
        if(sc == 7 || sc == 8 || sc == 9) ColorBar(brks=round(100*bias.brks[2:(length(bias.brks)-1)],2), cols=bias.cols[2:(length(bias.cols)-1)], col_inf=bias.cols[1], col_sup= bias.cols[length(bias.cols)], vert=FALSE, label_scale=1.4)

        if(sc == 1 || sc == 2 || sc == 3){ par(fig=c(0.88, 0.91, 0.148, 0.178), new=TRUE); mtext("r", font=2, cex=1.5)}
        if(sc == 4 || sc == 5 || sc == 6){ par(fig=c(0.90, 0.95, 0.148, 0.178), new=TRUE); mtext("Ratio", font=2, cex=1.5)}
        if(sc == 7 || sc == 8 || sc == 9){ par(fig=c(0.90, 0.95, 0.148, 0.178), new=TRUE); mtext("Bias (%)", font=2, cex=1.5)}

        if(sc == 1){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Correlation of mean wind speed", font=2, cex=2)}
        if(sc == 2){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Correlation of p95 of wind speed", font=2, cex=2)}
        if(sc == 3){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Correlation of p5 of wind speed", font=2, cex=2)}
        if(sc == 4){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("St.Dev.Ratio of Mean wind speed", font=2, cex=2)}
        if(sc == 5){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("St.Dev.Ratio of p95 of wind speed", font=2, cex=2)}
        if(sc == 6){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("St.Dev.Ratio of p5 of wind speed", font=2, cex=2)}
        if(sc == 7){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Bias of mean wind speed", font=2, cex=2)}
        if(sc == 8){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Bias of p95 of wind speed", font=2, cex=2)}
        if(sc == 9){ par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE); mtext("Bias of p5 of wind speed", font=2, cex=2)}
        
        dev.off()
        
    } ## close for on sc




    ## figure for the paper:
    
    mod.cross <- ifelse(cross, "cross","no_cross")
    EU <- c(1:which(imp.area.lon >= lon.max)[1], (which(imp.area.lon >= 337)[1]:length(imp.area.lon)))  # restrict area to continental europe only
         
    corr.cols <- rev(c('#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061'))
    corr.brks <- c(-1, -0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9, 1)
    ##ratio.stdev.cols <- c('#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f','#990000')
    ratio.stdev.cols <- c('white', '#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f')
    ratio.stdev.brks <- c(0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 1)
    
    bias.cols <- rev(c('#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061'))
    bias.brks <- c(-1000, -0.15, -0.12, -0.09, -0.06, -0.03, 0.03, 0.06, 0.09, 0.12, 0.15, 1000)/100 ## for bias of relative wind speed anomalies (1=100%)

    p=12 ## to create composition during december
    workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])

    png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_paper_composition.png"), width=2000, height=2000) 
    plot.new()

    i <- 0
    for(p in c(1,4,7,10)){
        mod <- 0.2*i
        workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])
        load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,"_recon_", mod.cross,".RData"))
        if(!identical(period, period.orig)) period <- period.orig; if(area != area.orig) area <- area.orig

        par(fig=c(0.1 + mod, 0.3 + mod, 0.7, 0.9), new=TRUE)
        PlotEquiMap(cor.mean[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=corr.brks, cols=corr.cols, axelab=F, drawleg=F)
        
        par(fig=c(0.1 + mod, 0.3 + mod, 0.5, 0.7), new=TRUE)
        PlotEquiMap(sqrt(var.ratio[,EU]), imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=ratio.stdev.brks, cols=ratio.stdev.cols, axelab=F, drawleg=F)

        par(fig=c(0.1 + mod, 0.3 + mod, 0.3, 0.5), new=TRUE)
        PlotEquiMap(cor.p95[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=corr.brks, cols=corr.cols, axelab=F, drawleg=F)
        
        par(fig=c(0.1 + mod, 0.3 + mod, 0.1, 0.3), new=TRUE)  
        PlotEquiMap(bias[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=bias.brks, cols=bias.cols, axelab=F, drawleg=F)

        ## Titles:
        par(fig=c(0.1 + mod, 0.3 + mod, 0.90, 0.91), new=TRUE)
        mtext(my.period[p], font=1, cex=4)

        if(i == 0){
            ## left titles:
            par(fig=c(0.05, 0.09, 0.7, 0.9), new=TRUE)
            mtext("Mean Wind Corr.", font=1, cex=4, side=4)

            par(fig=c(0.05, 0.09, 0.5, 0.7), new=TRUE)
            mtext("St.Dev.Ratio", font=1, cex=4, side=4)

            par(fig=c(0.05, 0.09, 0.3, 0.5), new=TRUE)
            mtext("p95 Wind Corr.", font=1, cex=4, side=4)

            par(fig=c(0.05, 0.09, 0.1, 0.3), new=TRUE)
            mtext("Mean Wind Bias", font=1, cex=4, side=4)

            ## right legend:
            par(fig=c(0.90, 0.98, 0.7, 0.9), new=TRUE)  
            ColorBar(brks=round(corr.brks[1:(length(corr.brks))],1), cols=corr.cols[1:(length(corr.cols))], vert=TRUE, label_scale=2.3)

            par(fig=c(0.90, 0.98, 0.5, 0.7), new=TRUE)
            ColorBar(brks=round(ratio.stdev.brks[1:(length(ratio.stdev.brks))],3), cols=ratio.stdev.cols[1:(length(ratio.stdev.cols))], vert=TRUE, label_scale=2.3)
            
            par(fig=c(0.90, 0.98, 0.3, 0.5), new=TRUE)
            ColorBar(brks=round(corr.brks[1:(length(corr.brks))],1), cols=corr.cols[1:(length(corr.cols))], vert=TRUE, label_scale=2.3)

            par(fig=c(0.90, 0.98, 0.1, 0.3), new=TRUE)  
            ColorBar(brks=round(100*bias.brks[2:(length(bias.brks)-1)],2), cols=bias.cols[2:(length(bias.cols)-1)], col_inf=bias.cols[1], col_sup= bias.cols[length(bias.cols)], vert=TRUE, label_scale=2.3)
            
            par(fig=c(0.915, 0.94, 0.07, 0.097), new=TRUE)  
            mtext("%", font=1, cex=2.3)

        }

        
        i <- i+1
    }
    
    dev.off()
    
   

    ## ##
    ## ## plot "Distribution Skill" of wind speed:
    ## ##

    ## cross <- TRUE ## choose if to measure the score in cross-validation or not

    ## ## 'bin.wd' is the width of a bin, bin.start (for relative anomalies of sfcWind and prcp they start from -1, equal to -100% win speed rel.anom.)
    ## if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr") { n.bins <- 31; bin.wd <- 0.1 ; bin.start <- -1} 
    ## if(var.name[var.num] == "psl"){ n.bins <- 21  ; bin.wd <- 0.01 ; bin.start <- -0.10 }
    ## if(var.name[var.num] == "tas"){ n.bins <- 31  ; bin.wd <- 2  ; bin.start <- -30 }

    ## ## check one the min/max values to set the range of the anomalies:
    ## ## anom.max <- max(vareuFullAnom[1,1,,,,], na.rm=T)
    ## ## anom.min <- min(vareuFullAnom[1,1,,,,], na.rm=T)
    ## ## anom.max.rel <- max(vareuFullAnomRel[1,1,,,,], na.rm=T)
    ## ## anom.min.rel <- min(vareuFullAnomRel[1,1,,,,], na.rm=T)

    ## ## psl: min -8.6%, max +5.7%
    
    ## ## vector with the center of each bin:
    ## bin.pos <- bin.start + (1:n.bins)*bin.wd - bin.wd/2  

    ## mod.cross <- ifelse(cross, "cross","no_cross")   ## suffix to add to the file name of the figure
    ## period.orig <- period
    ## area.orig <- area
    ## for(p in period){
    ##     print(paste("Period:", period.name[p]))

    ##     my.pos.period <- pos.period(1,p)
    ##     if(subdaily) my.pos.period <- (4*pos.period(1,p)-3)[1]:(4*pos.period(1,p))[length(pos.period(1,p))]
    ##     ndays <- length(my.pos.period) ## = n.days.in.a.period(p,1), *4 if 6-hourly

    ##     ## measure the mean number of days/6-hourly intervals associated to a bin of the observed yearly histogram (for the cumulated histogram, multiply it for n.years)
    ##     ndays.bin <- ndays / n.bins
      
    ##     ## load cluster data (my.cluster$cluster):
    ##     workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])  
    ##     load(file=paste0(workdir, "/", year.end,"_", my.period[p], "_psl.RData"))
    ##     if(!identical(period, period.orig)) period <- period.orig
    ##     if(area != area.orig) area <- area.orig

    ##     ## update the working directory, because the period could have changed:
    ##     workdir <- paste0(rootdir,"/", area, "/", year.end, "_", my.period[p])  
    ##     dir.create(file.path(workdir))  # working dir where output files will be generated
        
    ##     cluster.sequence <- my.cluster$cluster  ## daily sequence only for period p
    ##     if(subdaily) cluster.sequence <- rep(my.cluster$cluster, each=4) ## repeat 4 times the daily cluster series to create the 6-hourly cluster series

    ##     ## select only var daily anomalies of period p; if 6-hourly, select only var 6-hourly anomalies fo period p:
    ##     if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr" || var.name[var.num] == "psl") var.mes <- vareuFullAnomRel[1,1,, my.pos.period,,] else var.mes <- vareuFullAnom[1,1,, my.pos.period,,] 

    ##     ## group year and day/6-houtly data together in the same dimension (the first one):
    ##     var.mes.vert <- array(aperm(var.mes[,,,, drop=FALSE], c(2,1,3,4)), c(dim(var.mes)[1] * dim(var.mes)[2], dim(var.mes)[3], dim(var.mes)[4]))

    ##     ## observed histogram:
    ##     var.clim.obs <- array(NA, c(n.bins, length(imp.area.lat), length(imp.area.lon)))
        
    ##     for(b in 1:(n.bins-1)) { var.clim.obs[b,,] <- apply(var.mes.vert, c(2,3), function(x){ length(which(x >= (bin.start + (b-1)*bin.wd) & x < (bin.start + b*bin.wd)))}) }

    ##     ## same speed than normal apply():
    ##     ## for(b in 1:(n.bins-1)) { var.clim.obs[b,,] <- Apply(data=var.mes.vert, margins=c(2,3), AtomicFun=function(x){ length(which(x >= -1))}, ncores=availableCores())[[1]] }    
    ##     ## introduce the last bin, for wind anom  >= 100%:
    ##     var.clim.obs[n.bins,,] <- apply(var.mes.vert, c(2,3), function(x){ length(which(x >= (bin.start + (n.bins-1)*bin.wd)))})
        
    ##     ## set to 0 instead of NA the eventual bins with no observations:
    ##     var.clim.obs[which(is.na(var.clim.obs))] <- 0

    ##     ## observed histogram for each year:
    ##     var.year.obs <- array(NA, c(n.years, n.bins, length(imp.area.lat), length(imp.area.lon)))
    ##     var.year.var <- array(NA, c(n.years, length(imp.area.lat), length(imp.area.lon)))
        
    ##     print("Measuring observed histogram for each year:")
    ##     for(y in year.start:year.end){
    ##         y2 <- y - year.start + 1
    ##         cat(paste0(y, " "))
            
    ##         ## observed histogram for year y2:
    ##         var.mes.year <- var.mes[y2,,,] ## select only days of year y2
    ##         for(b in 1:(n.bins-1)) { var.year.obs[y2,b,,] <- apply(var.mes.year, c(2,3), function(x){ length(which(x >= (bin.start + (b-1)*bin.wd) & x < (bin.start + b*bin.wd)))}) }

    ##         ##system.time(for(b in 1:(n.bins-1)) { var.year.obs[y2,b,,] <- Apply(var.mes.year, c(2,3), AtomicFun=function(x){ length(which(x >= (-1 + (b-1)*bin.wd) & x < (-1 + b*bin.wd)))})[[1]] })
            
    ##         var.year.obs[y2, n.bins,,] <- apply(var.mes.year, c(2,3), function(x){ length(which(x >= (bin.start + (n.bins-1)*bin.wd)))})
    ##         var.year.obs[which(is.na(var.year.obs))] <- 0 ## set to 0 instead of NA the eventual bins with no observations:
            
    ##         ## convert the obs yearly histogram in an anomaly series and measure its variance for each year:
    ##         ##var.year.var[y2,,] <- apply( var.year.obs[y2,,,], c(2,3), function(x){ var(pdf2series(bin.pos, x)) })
            
    ##     }

    ##     ## ## measure the variance of the observed histograms:
    ##     variance.obs <- apply((var.year.obs - ndays.bin)^2, c(3,4), sum) ##/(n.years*n.bins)             
        
    ##     if(!cross){  ## without cross-validation:
    ##         ## regime sequences:
    ##         wrs <- list(); for(cl in 1:n.cl) wrs[[cl]] <- which(cluster.sequence == cl)

    ##         ## wind speed anomalies only of selected mes and wr for the climatological period:
    ##         var.wrs <- list(); for(cl in 1:n.cl) var.wrs[[cl]] <- var.mes.vert[wrs[[cl]],,]

    ##         ## wind speed anomalies only for selected mes, wr and bin for the climatological period: (to replace hist function with a faster one)
    ##         ## the bins are: [-1, -0.8), [-0.8, -0.6), [-0.6, -0.4), ... [0.8, 1), [2, inf)
    ##         ## notice that while values lower than -100% are not possible (correspond to negative wind speed), values above 100% are possible
    ##         var.recon <- array(NA, c(n.bins, n.cl, length(imp.area.lat), length(imp.area.lon))) 
            
    ##         system.time(for(b in 1:(n.bins-1)) {for(cl in 1:n.cl) var.recon[b,cl,,] <- apply(var.wrs[[cl]], c(2,3), function(x){ length(which(x >= (bin.start +(b-1)*bin.wd) & x < (bin.start +b*bin.wd)))})})

    ##         ## introduce the last bin, for wind anom  >= 100%:
    ##         for(cl in 1:n.cl) var.recon[n.bins, cl,,] <- apply(var.wrs[[cl]], c(2,3), function(x){ length(which(x >= (bin.start + (n.bins-1)*bin.wd)))})

    ##         ## normalize each regime pdf for the total number of days of each regime (wrs[[cl]]), so the area of each regime histogram is 1 and the histogram becomes a pdf:
    ##         for(cl in 1:n.cl) var.recon[, cl,,] <- var.recon[, cl,,] / length(wrs[[cl]])

    ##     } else {  ## cross-validation:
    ##         print("Computing cross-validation. Please wait...")
            
    ##         ##var.clim.obs.cross <- list()
    ##         var.recon.cross <- array(NA, c(n.years, n.bins, n.cl, length(imp.area.lat), length(imp.area.lon))) 
    ##         for(y in year.start:year.end){
    ##             y2 <- y - year.start + 1
    ##             cat(paste0(y, " "))

    ##             ## remove the year to validate from var data used for training:
    ##             var.mes.cross <- var.mes[-y2,,,]

    ##             ## convert dim year and days in one dim only
    ##             var.mes.vert.cross <- array(aperm(var.mes.cross[,,,, drop=FALSE], c(2,1,3,4)), c(dim(var.mes.cross)[1] * dim(var.mes.cross)[2], dim(var.mes.cross)[3], dim(var.mes.cross)[4]))

    ##             ## cluster sequence without the days belonging to year y2:
    ##             cluster.sequence.cross <- cluster.sequence[-((y2-1)*ndays + 1:ndays)]

    ##             ## list with the days belonging to each regime 
    ##             wrs.cross <- list(); for(cl in 1:n.cl) wrs.cross[[cl]] <- which(cluster.sequence.cross == cl)

    ##             ## list with the wind speed anomalies of the days belonging to each regime:
    ##             var.wrs.cross <- list(); for(cl in 1:n.cl) var.wrs.cross[[cl]] <- var.mes.vert.cross[wrs.cross[[cl]],,]

    ##             ## divide data in bins:
    ##             for(b in 1:(n.bins-1)) {for(cl in 1:n.cl) var.recon.cross[y2, b, cl,,] <- apply(var.wrs.cross[[cl]], c(2,3), function(x){ length(which(x >= (bin.start + (b-1)*bin.wd) & x < (bin.start + b*bin.wd)))})}
                
    ##             ## last bin:
    ##             for(cl in 1:n.cl) var.recon.cross[y2, n.bins, cl,,] <- apply(var.wrs.cross[[cl]], c(2,3), function(x){ length(which(x >= (bin.start + (n.bins-1)*bin.wd)))})

    ##             ## normalize for the total number of values for all bins and year (save the year cross-validated), so each histogram has area 1 and becomes a pdf:
    ##             for(cl in 1:n.cl) var.recon.cross[y2,, cl,,] <- var.recon.cross[y2,, cl,,] / length(wrs.cross[[cl]])

    ##         }

    ##         var.recon.cross[which(is.na(var.recon.cross))] <- 0
            
    ##     }

        
    ##     ## reconstruct the pdf for each year:
    ##     ##var.bin.year <- list()
    ##     var.recon.year <- array(NA, c(n.years, n.bins, n.cl, length(imp.area.lat), length(imp.area.lon)))
    ##     wrs.num.year <- array(NA, c(n.years, n.cl))        
    ##     var.recon.year.tot <- array(0, c(n.years, n.bins, length(imp.area.lat), length(imp.area.lon)))
    ##     var.ratio.year <- array(NA,  c(n.years, length(imp.area.lat), length(imp.area.lon)))
        
    ##     print("Reconstructing the pdf for year:")
    ##     for(y in year.start:year.end){
    ##         y2 <- y - year.start + 1
    ##         cat(paste0(y, " "))
            
    ##         ## for chosen month and year y2, count the number of days belonging to a particular regime and year y2:
    ##         ##if(!subdaily) for(cl in 1:n.cl) wrs.num.year[y2, cl] <- length(which(cluster.sequence[(y2-1)*ndays + (1:ndays)] == cl))
    ##         ##if(subdaily) for(cl in 1:n.cl) wrs.num.year[y2, cl] <- length(which(cluster.sequence[(y2-1)*(ndays*4) + (1:(ndays*4))] == cl))
    ##         for(cl in 1:n.cl) wrs.num.year[y2, cl] <- length(which(cluster.sequence[(y2-1)*ndays + (1:ndays)] == cl))
            
    ##         ## for chosen month and year y2, reconstruct each regime histogram for year y2 by multiplying for the WR monthly frequencies during year y2:
    ##         if(!cross) for(b in 1:n.bins) { for(cl in 1:n.cl) var.recon.year[y2, b, cl,,] <- var.recon[b, cl,,] * wrs.num.year[y2,cl] }
    ##         if(cross) for(b in 1:n.bins) { for(cl in 1:n.cl) var.recon.year[y2, b, cl,,] <- var.recon.cross[y2, b, cl,,] * wrs.num.year[y2, cl] }

    ##         ## e.g: var.bin.year[y2,,2,3,4] is the reconstructed histogram for year y2, cluster 2, point (3,4)
    ##         ##      so var.bin.year[y2,,1,,] +  var.bin.year[y2,,2,,] +  var.bin.year[y2,,3,,] +  var.bin.year[y2,,4,,] is the histogram for year y2

    ##         ## total reconstructed histogram for year y2: (adding the histogram of all regimes)
    ##         var.recon.year.tot[y2,,,] <- apply(var.recon.year[y2,,,,], c(1,3,4), sum)
            
    ##         ##for(cl in 1:n.cl) var.recon.year.tot[y2,,,] <- var.recon.year.tot[y2,,,] + var.recon.year[y2,,cl,,]

    ##         ## difference between reconstructed hist year y2 and observed hist year y2:
    ##         ##print(round(var.recon.year.tot[y2,,1,1] - var.year.obs[y2,,1,1],1))

    ##         ## difference plot: (black series is the observed one, red the reconstructed)
    ##         ##plot(var.recon.year.tot[y2,,1,1], type="b", col="red")
    ##         ##lines(var.year.obs[y2,,1,1], type="b",col="black")
            
    ##         ## ## convert the reconstructed yearly histogram in an anomaly series and measure its variance for year y2:
    ##         ## var.recon <- apply(var.recon.year.tot[y2,,,], c(2,3), function(x){ var(pdf2series(bin.pos, x)) })
    ##         ## var.ratio.year[y2,,] <- var.recon / var.year.var[y2,,]
    ##         ## print(var.ratio.year[y2,1,1])   
    ##     }
          
    ##     ## Measure the global MSE by summing all bins and years:
    ##     var.mse <- apply((var.recon.year.tot - var.year.obs)^2, c(3,4), sum) ##/(n.years*n.bins)

    ##     ## measure the ratio between the MSE and the variance:
    ##     var.mse.norm <- var.mse / variance.obs

    ##     ## measure the total skill:
    ##     dist.skill <- 1 - (var.mse.norm)^0.5

    ##     ## save it:
    ##     mod.cross <- ifelse(cross, "cross","no_cross")   ## suffix to add to the file name of the figure
    ##     save(dist.skill, file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,"_dist_skill_",mod.cross,".RData"))

    ##     ## convert the reconstructed yearly histogram in an anomaly series and measure its variance for each year:
    ##     ##var.recon.sd <- apply(var.recon.year.tot, c(1,3,4), function(x){ sd(pdf2series(bin.pos, x)) }) ##rep(perc.bin1, var.clim.recon[1,,]

    ##     ## measure the average reconstructed variance:
    ##     ##var.recon.sd.mean <- apply(var.recon.sd, c(2,3), mean)
        
    ##     ## sum the histograms of all the years to get the climatological reconstructed histogram to confront with the climatolgical observed one:
    ##     ## var.clim.recon <- apply(var.recon.year.tot, c(2,3,4), sum)
        
    ##     ## convert the reconstructed yearly histogrms in reconstructed yearly wind speed anomaly series and measure its variance:        
    ##     ## var.clim.recon.seq <- apply(var.clim.recon, c(2,3), function(x){ sd(pdf2series(bin.pos, x)) }) ##rep(perc.bin1, var.clim.recon[1,,]
        
    ##     ##mean.lab <-c(0, 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 10)/4
    ##     ##if(box.cluster) my.box <- c(lon.min, lat.min, lon.max, lat.max) else my.box <- NULL   ## eventual gray box with cluster spatial domain

    ##     ##
    ##     ## plot composition with reconstructed and observed histograms for each year:
    ##     ##

    ##     ## select point coordinates:
    ##     pnt.latp <- round(length(imp.area.lat)/2) ##37 ##10
    ##     pnt.lonp <- 55 ##91 ##20

    ##     if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr"|| var.name[var.num] == "psl") fig.title <- " rel. anomaly (%)" else fig.title <- paste0(" anomaly (", var.unit[var.num], ")")
        
    ##     y.max <- max(var.year.obs[,, pnt.latp, pnt.lonp], na.rm=T)
    ##     num.file <- ceiling(sqrt((year.end - year.start + 1))) ##number of figures to show in the composition
        
    ##     workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])
    ##     file.crossv <- paste0(workdir,"/",year.end,"_",my.period[p],"_crossv_",var.name[var.num],"_point_lat_",round(imp.area.lat[pnt.latp],1),"_lon_",round(imp.area.lon[pnt.lonp],1),".png")
    ##     png(filename=file.crossv,width=6000, height=5000)
    ##     ##PlotLayout(c("plot","lines"), 2, list(var.recon.year.tot[,,1,1],var.year.obs[,,1,1]), type="b", col=c("red","black"))
    ##     plot.new()
    ##     par(mfrow=c(num.file, num.file), oma=c(4,10,15,4), mar=c(10,10,10,10))          
    ##     for(y in year.start:year.end){
    ##         y2 <- y - year.start + 1
    ##         plot(var.recon.year.tot[y2,, pnt.latp, pnt.lonp], type="b", col="red", ylim=c(0,y.max), lwd=3, cex.main=6, cex.axis=5, mgp=c(3,3,0), ann=FALSE, xaxt="n")
    ##         axis(1, at=1:n.bins, labels=round(bin.pos,1), line=0, cex.axis=2, las=2)
    ##         lines(var.year.obs[y2,, pnt.latp, pnt.lonp], type="b", col="black", lwd=3)
    ##         mtext(side = 1, text = paste0(var.name.full[var.num], fig.title), line = 10, cex=4)
    ##         mtext(side = 2, text = "Num. of 6-hourly int.", line = 10, cex=4)
    ##         mtext(side = 3, text = paste0(var.name[var.num]," histogram for year ", y), line=2, cex=4, font=2)
    ##         ##text(x=25, y=22, labels=paste0("RMSE=",round(var.rmse.year[y2,1,1],1)), cex=5)
        
    ##     }

    ##     ##dist.skill[pnt.latp, pnt.lonp]
        
    ##     ##par(fig=c(0.2,0.8,0.98,1))
    ##     ##title("test")
    ##     dev.off()

    ##     ## Two colors:
    ##     ##RMSE.cols <- rev(c('#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061'))
    ##     ##RMSE.brks <- c(-1000, 0.30, 0.33, 0.36, 0.39, 0.42, 0.45, 0.48, 0.51, 0.54, 0.57, 1)
        
    ##     ##RMSE.cols <- rev(c('darkred','#a50026','#d73027','#f46d43','#fdae61','#fee090','#e0f3f8','#abd9e9','#74add1','#4575b4','#313695'))
    ##     ##RMSE.brks <- c(-1000, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 1)
    ##     ##RMSE.brks <- c(-1000, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.70, 1)

    ##     ## One color:
    ##     RMSE.cols <- c('#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f','#990000')
    ##     RMSE.brks <- c(-1000, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1)
    ##     RMSE.brks <- c(-1000, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 1)
        
    ##     fileoutput.influence <- paste0(workdir,"/",year.end,"_",my.period[p],"_RMSE.png")
    ##     png(filename=fileoutput.influence, width=1000, height=750) #550, height=650)
        
    ##     plot.new()
    ##     par(fig=c(0.01,0.99, 0.07, 0.99), new=TRUE)  
    ##     PlotEquiMap(dist.skill, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=RMSE.brks, cols=RMSE.cols, axelab=TRUE, toptitle=paste0("Distribution Skill in ",period.name[p]), drawleg=F, boxlim=my.box, boxcol=box.col, boxlwd=1)
    ##     if(wind.farms) points(my.farm[,1], my.farm[,2], cex=farms.size, col=wind.color, pch=farms.style, lwd=2)

    ##     par(fig=c(0.2,0.8, 0.00, 0.06), new=TRUE)
    ##     ##ColorBar(brks=round(RMSE.brks[1:(l(RMSE.brks)-1)],1), cols=RMSE.cols[1:(length(RMSE.cols)-1)], vert=FALSE, label_scale=1.6, col_sup=RMSE.cols[l(RMSE.cols)])

    ##     ColorBar(brks=round(RMSE.brks[2:(l(RMSE.brks))],2), cols=RMSE.cols[2:(length(RMSE.cols))], vert=FALSE, label_scale=1.6, col_inf=RMSE.cols[1])
    ##     par(fig=c(0.7,0.9, 0.055, 0.08), new=TRUE)  
    ##     ##mtext("", font=2, cex=1.5)
        
    ##     dev.off()

    ##     ##PlotEquiMap(var.mse, imp.area.lon, imp.area.lat, filled.continents = FALSE, cols=RMSE.cols, axelab=TRUE, toptitle=paste0("Total influence WRs in ",period.name[p]), drawleg=T, boxlim=my.box, boxcol=box.col, boxlwd=1)

        
    ## } # close 'p' on 'period'

    ## ##
    ## ## generate a composition of all months of previous figure:
    ## ##

    ## mod.cross <- ifelse(cross, "cross","no_cross")
    ## EU <- c(1:which(imp.area.lon >= lon.max)[1], (which(imp.area.lon >= 337)[1]:length(imp.area.lon)))  # restrict area to continental europe only
    
    ## p=12 ## to create composition during december
    ## workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])

    ## png(filename=paste0(workdir,"/",year.end,"_",my.period[p],"_", mod.cross, "_dist_skill_composition.png"), width=780, height=1300) #550, height=650)
    
    ## plot.new()
    ## par(xpd=TRUE)
    ## text(x=-0.1, y=0.58, labels="Autumn                             Summer                              Spring                              Winter", cex=1.8, srt=90)
    ## par(xpd=FALSE)

    ## period.orig <- period
    ## for(p in c(12, 1:11)){

    ##     ## load 'wind.skill' to plot it:
    ##     workdir <- paste0(rootdir, "/", area, "/", year.end, "_", my.period[p])
    ##     load(file=paste0(workdir,"/",year.end,"_",my.period[p],"_",var.name[var.num],"_",rean2load.name,"_dist_skill_",mod.cross,".RData"))
    ##     if(!identical(period, period.orig)) period <- period.orig
    ##     if(area != area.orig) area <- area.orig

    ##     if(p == 12 || p == 1 || p == 2) yMod <- 0.77
    ##     if(p >= 3 && p <= 5) yMod <- 0.58
    ##     if(p >= 6 && p <= 8) yMod <- 0.39
    ##     if(p == 9 || p == 10 || p == 11) yMod <- 0.2
    ##     if(p == 13 || p == 14) yMod <- 0.62
    ##     if(p == 15 || p == 16) yMod <- 0.2
        
    ##     if(p == 12 || p == 3 || p == 6 || p == 9) xMod <- 0.05
    ##     if(p == 1 || p == 4 || p == 7 || p == 10) xMod <- 0.35
    ##     if(p == 2 || p == 5 || p == 8 || p == 11) 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(dist.skill[,EU], imp.area.lon[EU], imp.area.lat, filled.continents = FALSE, brks=RMSE.brks, cols=RMSE.cols, axelab=F, drawleg=F)

    ##     if(p <= 12) par(fig=c(xMod, xMod + 0.3, yMod + 0.166, yMod + 0.176), new=TRUE)
    ##     if(p > 12) par(fig=c(xMod + 0.07, xMod + 0.07 + 0.3, yMod +0.21 + 0.166, yMod +0.21 + 0.176), new=TRUE)
    ##     mtext(my.period[p], font=1, cex=1.6)

    ## } # close 'p' on 'period'

    ## par(fig=c(0.1,0.9, 0.15, 0.20), new=TRUE)  
    ## ColorBar(brks=round(RMSE.brks[2:(length(RMSE.brks))],2), cols=RMSE.cols[2:(length(RMSE.cols))], vert=FALSE, label_scale=1.4, col_inf=RMSE.cols[1])

    ## ##par(fig=c(0.88,0.91, 0.148, 0.178), new=TRUE)  
    ## ##mtext("", font=2, cex=1.5)

    ## par(fig=c(0.1,0.9, 0.93, 0.98), new=TRUE)
    ## mtext("Distribution Skill", font=2, cex=2)
    
    ## dev.off()





    
    ##
    ## Automatic sensitivity study of the shape of the cluster domain with the higher overall impact on wind speed:
    ##

    test.domain <- FALSE
    if(test.domain){

        criteria <- 2 ## parameter to maximize/minimize in the choice of the best spatial domain.
                      ## 1: maximize sum of the absolute value of the impact of each regime on wind
                      ## 2: maximize the variance ratio of the reconstructed and observed time series of mean wind speed values 
        
        block.size <- 7 ## odd number of grid points a block is composed, in each direction (for a total of block.size^2 points). Must be odd to place plant in the middle
        ##best.perc <- 0.99 ##1 ##0.90 ## fraction (from 0 to 1) of the best impact measured at EDPR site we want to keep when expanding the domain
       
        ## e.g: for JRA-55, if block.size is 5, the block is a square of 125 km x 5 = 625 km.

        cat(paste0("Optimizing cluster domain during ", period.name[p]," with ", n.cl," regimes. Please wait...\n"))

        my.pos.period <- pos.period(1,p)
        if(subdaily) my.pos.period <- (4*pos.period(1,p)-3)[1]:(4*pos.period(1,p))[length(pos.period(1,p))]
        ndays <- length(my.pos.period) ## = n.days.in.a.period(p,1), *4 if 6-hourly
        
        ## number of EDPR plants:
        farms.seq <- which(!is.na(my.farm[,1]))
        n.farms <- which(!is.na(my.farm[,1]))
        
        ## point size of the impact grid:
        imp.res <- imp.area.lon[2] - imp.area.lon[1]
        psl.res <- bigarea.lon[2] - bigarea.lon[1]
        
        ## create array for lat weighting psl before clustering:
        lat.weighted <- cos(bigarea.lat*pi/180)
        lat.weighted.array <- InsertDim(InsertDim(InsertDim(lat.weighted, 2, length(bigarea.lon)), 1, length(pos.period(1,p))), 1, n.years)

        ## extract psl fields only for years and days of selected month and weight them for lat:
        pslPeriod <- slpAnom[, pos.period(1,p),,] * lat.weighted.array ## check

        ## select wind anomalies for all days and years only for the chosen period and place them in vertical:
        if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr" || var.name[var.num] == "psl") dom.period.full <- vareuFullAnomRel[1,1,, my.pos.period,,] else dom.period.full <- vareuFullAnom[1,1,, my.pos.period,,] 

        ##dom.period.full <- vareuFullAnomRel[1,1,, my.pos.period,,]            
        dom.period.full.seq <- array(aperm(dom.period.full[,,,, drop=FALSE], c(2,1,3,4)), c(n.years * ndays, length(imp.area.lat) * length(imp.area.lon)))

        ## loop on the number identifier of the EDPR USA plant to study (from 1 to 38) where we want to maximize the impact of the WRs on wind speed
        for(pnt in farms.seq){    
            print(paste0("EDPR plant num. ", pnt))            
            ## detect plant coordinates:
            plant.lon <- my.farm[pnt, 1]
            plant.lat <- my.farm[pnt, 2]

            ## 'radius' of a block in pixels:
            block.radius <- floor(block.size/2) 

            ## identify coordinates of the psl grid point which is including the plant point:
            closer.lon.pos <- nearest(plant.lat, plant.lon, bigarea.lat, bigarea.lon)[1,2]
            closer.lat.pos <- nearest(plant.lat, plant.lon, bigarea.lat, bigarea.lon)[1,1]

            ## same as before but for the wind anomaly grid point:
            closer.lon.pos.var <- nearest(plant.lat, plant.lon, imp.area.lat, imp.area.lon)[1,2]
            closer.lat.pos.var <- nearest(plant.lat, plant.lon, imp.area.lat, imp.area.lon)[1,1]

            ## find how many blocks can be inserted inside the psl grid:

            ## max numb. of blocks before the rightmost border of the psl grid:
            max.x <- 0; while((closer.lon.pos + max.x*block.size + floor(block.size/2)) <= length(bigarea.lon)) max.x <- max.x + 1
            ## max numb. of blocks before the leftmost border of the psl grid:
            min.x <- 0; while((closer.lon.pos - min.x*block.size - floor(block.size/2)) >= 1) min.x <- min.x + 1
            ## max numb of blocks before the bottommost border of the psl grid (note that max.y correspond to the bottom border of the psl domain):
            max.y <- 0; while((closer.lat.pos + max.y*block.size + floor(block.size/2)) <= length(bigarea.lat)) max.y <- max.y + 1
            ## max numb of blocks before th topmost border of the psl grid (note that min.y corresponds to the topmost border of the psl domain):
            min.y <- 0; while((closer.lat.pos - min.y*block.size - floor(block.size/2)) >= 1) min.y <- min.y + 1 

            ## Since the while loop doesn't exit immediatly when the condition is verified, the indexes are increased by one, so you have to quit it now:
            max.x <- max.x - 1; min.x <- min.x - 1; max.y <- max.y - 1; min.y <- min.y - 1

            ## time series of the observed mean wind speed at plant site:
            if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr" || var.name[var.num] == "psl"){
                pnt.mean.obs.year <- apply(vareuFullAnomRel[1,1,, my.pos.period, closer.lat.pos.var, closer.lon.pos.var], 1, mean)
            } else {
                pnt.mean.obs.year <- apply(vareuFullAnom[1,1,, my.pos.period, closer.lat.pos.var, closer.lon.pos.var], 1, mean)
            }

            ##pnt.mean.obs.year <- apply(vareuFullAnomRel[1,1,, my.pos.period, closer.lat.pos.var, closer.lon.pos.var], 1, mean)
                            
            print(paste0("The maximum number of blocks in each direction is: ", min.x, " to the West of the plant, ", max.x, " to the East, ", min.y, " to the North and ", max.y, " to the South"))

            if(min.x == 0 || max.x == 0 || min.y == 0 || max.y == 0){
                print(paste0("Plant #", pnt, " is too close to the border of the psl grid. Decrease the block size."))
                
            } else { ## if there is the possibility to place at least one block in each direction nearby the plant block, then the domain sensitivity test can start:
                    
                ## create a new domain, initially with only one block over the plant position, inside the psl grid:
                dom.shape <- array(0, c(length(bigarea.lat), length(bigarea.lon)))   ## same size of whole psl region
                dom.shape[(closer.lat.pos - block.radius):(closer.lat.pos + block.radius), (closer.lon.pos - block.radius):(closer.lon.pos + block.radius)] <- 1  ## starting domain with only 1 block in the center

                ## identify psl coordinates of starting block:
                ##block.lons.pos <- (closer.lon.pos-block.radius):(closer.lon.pos+block.radius)
                ##block.lats.pos <- (closer.lat.pos-block.radius):(closer.lat.pos+block.radius)
                
                ## try to increase the cluster domain, adding another block:        
                n.blocks <- 1; k <- 0; imp.dom.top <- 0
                dom.optimal <- dom.bigger <- list() ## dom.bigger is equal to 2 in the points with best impact and 1 in the points with at least 'best.perc'% of max impact possible
                dom.imp.optimal  <- dom.imp.bigger <- c()
                while(n.blocks <= 10){ ## 1000 is not to increase too much computational times
                    cat(paste0("   Domain size: ", n.blocks, " blocks"))
                    
                    ## (re-)create new cluster domains, one for each possible free space (in the four main directions) near the current cluster domains (dom.shape):
                    dom.shape.new <- list()
                    
                    ## generate all new possible cluster domains one block bigger then the previous domain:
                    new.bl <- 0 ## variable which stores how many new blocks need to be tried before finding the best one
                    for(i in (-min.y+1):(max.y-1)){
                        for(j in (-min.x+1):(max.x-1)){
                            ##print(i)
                            ##print(j)

                            ## check point above:
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i-1)*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 0) {
                                new.bl <- new.bl + 1
                                dom.shape.new[[new.bl]] <- dom.shape
                                dom.shape.new[[new.bl]][((i-1)*block.size + closer.lat.pos - block.radius):((i-1)*block.size + closer.lat.pos + block.radius), (j*block.size + closer.lon.pos - block.radius):(j*block.size + closer.lon.pos + block.radius)] <- 1
                            }

                            ## check below:
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i+1)*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][((i+1)*block.size + closer.lat.pos - block.radius):((i+1)*block.size + closer.lat.pos + block.radius), (j*block.size + closer.lon.pos - block.radius):(j*block.size + closer.lon.pos + block.radius)] <- 1 }

                            ## check to the left:
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[i*block.size + closer.lat.pos, (j-1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][(i*block.size + closer.lat.pos - block.radius):(i*block.size + closer.lat.pos + block.radius), ((j-1)*block.size + closer.lon.pos - block.radius):((j-1)*block.size + closer.lon.pos + block.radius)] <- 1 }
                            
                            ## check to the right:
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[i*block.size + closer.lat.pos, (j+1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][(i*block.size + closer.lat.pos - block.radius):(i*block.size + closer.lat.pos + block.radius), ((j+1)*block.size + closer.lon.pos - block.radius):((j+1)*block.size + closer.lon.pos + block.radius)] <- 1 }

                            ## check  blocks in the four diagonals too:
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i-1)*block.size + closer.lat.pos, (j-1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][((i-1)*block.size + closer.lat.pos - block.radius):((i-1)*block.size + closer.lat.pos + block.radius), ((j-1)*block.size + closer.lon.pos - block.radius):((j-1)*block.size + closer.lon.pos + block.radius)] <- 1 }

                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i-1)*block.size + closer.lat.pos, (j+1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][((i-1)*block.size + closer.lat.pos - block.radius):((i-1)*block.size + closer.lat.pos + block.radius), ((j+1)*block.size + closer.lon.pos - block.radius):((j+1)*block.size + closer.lon.pos + block.radius)] <- 1 }

                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i+1)*block.size + closer.lat.pos, (j-1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][((i+1)*block.size + closer.lat.pos - block.radius):((i+1)*block.size + closer.lat.pos + block.radius), ((j-1)*block.size + closer.lon.pos - block.radius):((j-1)*block.size + closer.lon.pos + block.radius)] <- 1 }
                            
                            if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 1 && dom.shape[(i+1)*block.size + closer.lat.pos, (j+1)*block.size + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][((i+1)*block.size + closer.lat.pos - block.radius):((i+1)*block.size + closer.lat.pos + block.radius), ((j+1)*block.size + closer.lon.pos - block.radius):((j+1)*block.size + closer.lon.pos + block.radius)] <- 1 }
                            
                            ## old version, but more intuitive:
                            ##if(dom.shape[i,j] == 1 && dom.shape[i-1,j] == 0) { dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i-1,j] <- 1; new.bl <- new.bl + 1 }
                            ##if(dom.shape[i,j] == 1 && dom.shape[i+1,j] == 0) { dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i+1,j] <- 1; new.bl <- new.bl + 1 }
                            ##if(dom.shape[i,j] == 1 && dom.shape[i,j-1] == 0) { dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i,j-1] <- 1; new.bl <- new.bl + 1 }
                            ##if(dom.shape[i,j] == 1 && dom.shape[i,j+1] == 0) { dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i,j+1] <- 1; new.bl <- new.bl + 1 }

                            ## shorter version without blocks:
                            ##if(dom.shape[i + closer.lat.pos, j + closer.lon.pos] == 1 && dom.shape[(i-1) + closer.lat.pos, j + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i-1, j] <- 1 }
                            
                            ##if(dom.shape[i + closer.lat.pos, j + closer.lon.pos] == 1 && dom.shape[(i+1) + closer.lat.pos, j + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i+1, j] <- 1 }

                            ##if(dom.shape[i + closer.lat.pos, j + closer.lon.pos] == 1 && dom.shape[i + closer.lat.pos, (j-1) + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i, j-1] <- 1 }

                            ##if(dom.shape[i + closer.lat.pos, j + closer.lon.pos] == 1 && dom.shape[i + closer.lat.pos, (j+1) + closer.lon.pos] == 0) { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][i, j+1] <- 1 }

                            ## no proximity limitation, search on all the psl grid:
                            ##if(dom.shape[i*block.size + closer.lat.pos, j*block.size + closer.lon.pos] == 0)  { new.bl <- new.bl + 1; dom.shape.new[[new.bl]] <- dom.shape; dom.shape.new[[new.bl]][(i*block.size + closer.lat.pos - block.radius):(i*block.size + closer.lat.pos + block.radius), (j*block.size + closer.lon.pos - block.radius):(j*block.size + closer.lon.pos + block.radius)] <- 1 }

                        }
                    }

                    print(paste0("Found ", new.bl, " new block candidates"))
                    
                    ## check if some new cluster domain is repeated twice or more; in this case, remove it:
                    dom.repeated <- c()
                    dom.repeated[1] <- FALSE ## the first domain cannot be repeated!
                    
                    for(bl in 2:new.bl){
                        dom.repeated[bl] <- FALSE ## start assigning to each domain the flag "not repeated"
                        
                        for(bl2 in 1:(bl-1)){
                            if(identical(dom.shape.new[[bl]], dom.shape.new[[bl2]])) dom.repeated[bl] <- TRUE
                        }
                    }
                    
                    dom.repeated[new.bl+1] <- FALSE ## add the previous old reference domain
                    
                    dom.shape.new[[new.bl+1]] <- dom.shape
                    
                    ## measure the overall impact/var.ratio of WRs on wind in the plant point for each one of the new cluster domains:
                    ##my.domains <- 1:(new.bl+1)
                    my.domains <- (1:(new.bl+1)) * !dom.repeated ## select only domains which are not repeated
                    if(length(which(my.domains == 0) != 0)) my.domains <- my.domains[-which(my.domains == 0)]

                    dom.imp.tot <- array(NA, new.bl+1)
                    dom.wr <- list()
                    for(bl in my.domains){ ## the last value is the old domain, to check it too
                        n.points.dom <- length(which(dom.shape.new[[bl]] == 1))
                        pslPeriod.dom.new <- array(NA, c(n.years, n.days.in.a.period(p, 1), n.points.dom))
                        
                        ## select psl fields only for chosen domain:
                        latxlon <- 0
                        for(i in 1:length(bigarea.lat)){
                            for(j in 1:length(bigarea.lon)){
                                if(dom.shape.new[[bl]][i,j] == 1){ latxlon <- latxlon + 1; pslPeriod.dom.new[,,latxlon] <- pslPeriod[,,i,j]}
                            }
                        }
                        
                        ## psl ready for kmeans algorithm:    
                        pslPeriod.km <- array(aperm(pslPeriod.dom.new[,,, drop=FALSE], c(2,1,3)), c(n.years * n.days.in.a.period(p, 1), n.points.dom))

                        ## cluster psl for domain made up only by the selected blocks:
                        test.cluster <- kmeans(pslPeriod.km, centers=n.cl, iter.max=my.iter.max, nstart=my.nstart, trace=FALSE)  # n.cl is the number of clusters

                        cluster.sequence <- test.cluster$cluster
                        if(subdaily) cluster.sequence <- rep(test.cluster$cluster, each=4) ## repeat 4 times the daily cluster series to create the 6-hourly cluster series

                        ## separate days or 6-hourly time intervals in WRs:
                        dom.wr[[bl]] <- list() ; for(cl in 1:n.cl) dom.wr[[bl]][[cl]] <- which(cluster.sequence == cl) ## similar to var.wrs but for domains
                        
                        ## select wind anomalies for all days and years only for the chosen period and at plant site:
                        if(var.name[var.num] == "sfcWind" || var.name[var.num] == "prlr" || var.name[var.num] == "psl"){
                            dom.varPeriodRel <- vareuFullAnomRel[1,1,, my.pos.period, closer.lat.pos.var, closer.lon.pos.var]    
                        } else {
                            dom.varPeriodRel <- vareuFullAnom[1,1,, my.pos.period, closer.lat.pos.var, closer.lon.pos.var]    
                        }

                        ## convert them to a vector with all years and days:
                        dom.varPeriodRel.seq <- array(t(dom.varPeriodRel), c(n.years *  ndays))

                        ## measure the impact of each WR on wind speed in the plant for that domain:
                        dom.imp.wr <- list(); for(cl in 1:n.cl) dom.imp.wr[[cl]] <- mean(dom.varPeriodRel.seq[dom.wr[[bl]][[cl]]])
                           
                        ## measure the criteria to optimize:
                        if(criteria == 1){
                            ## measure the overall impact of the WRs on wind speed in the plant for that domain: (the value we want to confront)
                            dom.imp.tot[bl] <- mean(sapply(dom.imp.wr, abs)) ## mean of the absolute values of each impact
                            
                        } else {
                            
                            dom.mean.recon.year <- c()
                            for(y in year.start:year.end){
                                y2 <- y - year.start + 1
                                ## time series of the reconstructer mean wind speed:
                                dom.mean.recon.year[y2] <- 0; for(cl in 1:n.cl) dom.mean.recon.year[y2] <- dom.mean.recon.year[y2] + dom.imp.wr[[cl]] * wrs.num.year[y2, cl]
                            }
                            
                            ## normalize for the total number of days or 6-hourly intervals to get the average wind speed:
                            dom.mean.recon.year <- dom.mean.recon.year / ndays

                            ## measure the variance ratio of the mean wind speed at the plant for that domain: (the value we want to confront)
                            dom.imp.tot[bl] <- var(dom.mean.recon.year) / varvar(pnt.mean.obs.year)

                        }

                    } ## close for on bl

                    ## select the domain with the highest overall impact:
                    dom.best <- which.max(dom.imp.tot[-(new.bl+1)])    ## number of the best domain (removing the last one, which is the previous old domain)
                    imp.dom.best <- dom.imp.tot[dom.best] ## overall impact value of the best domain
                    wr.dom.best <- dom.wr[[dom.best]] ## daily regime sequence of the domain with the best impact
                    
                    ## ## stop the analysis without changing the old previous domain shape ('dom.shape'), if no one of the new domain shapes are better than the old one:
                    ## if(imp.dom.best < dom.imp.tot[new.bl+1] && k == 0) {
                    ##     print(paste0("Optimal domain found with ", round(100*dom.imp.tot[new.bl+1],2),"% overall impact. Expanding it to ",100*best.perc, "% of maximum impact"))
                    ##     dom.optimal[[pnt]] <- dom.shape.new[[new.bl+1]]; dom.imp.optimal[pnt] <- dom.imp.tot[new.bl+1]; k <-k+1
                    ## }
                    
                    ## ## keep going with the analysis until the total impact is X% of the maximum impact:
                    ## if(imp.dom.best < best.perc*dom.imp.tot[new.bl+1]) {
                    ##     dom.bigger[[pnt]] <- dom.shape.new[[new.bl+1]] + dom.optimal[[pnt]]; dom.imp.bigger[pnt] <- dom.imp.tot[new.bl+1]
                    ##     break
                    ## }

                    if(imp.dom.best > imp.dom.top) {
                        imp.dom.top <- imp.dom.best
                        dom.top <- dom.shape.new[[dom.best]]
                        n.blocks.top <- n.blocks
                    }
                    

                    print(paste0("Overall impact of domain: ",round(100*imp.dom.best,2), "%"," Highest impact: ",round(100*imp.dom.top,2), "% for ", n.blocks.top ," blocks"))
                    ## set the new, permanent domain as the best domain between the new ones: (ready for the next iteration)
                    dom.shape <- dom.shape.new[[dom.best]]

                    ## increase the number of blocks:
                    n.blocks <- n.blocks + 1 
                } ## close while
                

                ## wind speed impact on the whole area:
                dom.best.wr <- list(); for(cl in 1:n.cl) dom.best.wr[[cl]] <- dom.period.full.seq[wr.dom.best[[cl]],]
                imp.dom.best.wr <- list(); for(cl in 1:n.cl) imp.dom.best.wr[[cl]] <- colMeans(dom.best.wr[[cl]])
                imp.dom.best.wr.matrix <- list(); for(cl in 1:n.cl) imp.dom.best.wr.matrix[[cl]] <- array(t(imp.dom.best.wr[[cl]]), c(length(imp.area.lat),length(imp.area.lon)))
                imp.dom.best.tot.list <- lapply(imp.dom.best.wr.matrix, abs)
                imp.dom.best.tot <- imp.dom.best.tot.list[[1]] * 0 ; for(cl in 1:n.cl) imp.dom.best.tot <- imp.dom.best.tot + imp.dom.best.tot.list[[cl]]
                imp.dom.best.tot <- imp.dom.best.tot/n.cl

                ## ## select which blocks belong to the best domain:
                ## bl <- 0
                ## my.box <- list()    #c(lon.min, lat.min, lon.max, lat.max)
                ## for(i in 1:length(bigarea.lat)){
                ##     for(j in 1:length(bigarea.lon)){
                ##         ## best domain:
                ##         if(dom.bigger[[pnt]][i,j] == 2){ bl <- bl + 1; my.box[[bl]] <- c(bigarea.lon[j]-psl.res/2, bigarea.lat[i]-psl.res/2, bigarea.lon[j]+psl.res/2, bigarea.lat[i]+psl.res/2) } ##pslPeriod.dom.new[,,latxlon] <- pslPeriod[,,i,j]}

                ##     }
                ## }

                ## add blocks belong to the bigger domain:
                ##my.box.bigger <- list()    #c(lon.min, lat.min, lon.max, lat.max)
                bl2 <- 0
                for(i in 1:length(bigarea.lat)){
                    for(j in 1:length(bigarea.lon)){
                        ## bigger domain:
                        if(dom.shape[i,j] == 1){ bl2 <- bl2 + 1; my.box[[bl2]] <- c(bigarea.lon[j]-psl.res/2, bigarea.lat[i]-psl.res/2, bigarea.lon[j]+psl.res/2, bigarea.lat[i]+psl.res/2) } ##pslPeriod.dom.new[,,latxlon] <- pslPeriod[,,i,j]}

                    }
                }

                ## plot impact with best and bigger domain:
                fileoutput.sensitivity <- paste0(workdir,"/",year.end,"_",my.period[p],"_best_cluster_domain_EDPR_plant_",pnt,".png")
                
                png(filename=fileoutput.sensitivity, width=1000, height=750) #550, height=650)   
                plot.new()
                par(fig=c(0.01,0.99, 0.07, 0.99), new=TRUE)
                
                PlotEquiMap(imp.dom.best.tot, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks=mean.brks, cols=mean.cols, axelab=TRUE, toptitle=paste0("Total influence of WRs on ", var.name[var.num]), drawleg=F, boxlim=my.box, boxcol="green", boxlwd=3) #, intxlon=my.intx, intylat=my.inty)
                points(plant.lon, plant.lat, cex=2, col="darkgreen", pch=4, lwd=3)

                par(fig=c(0.2,0.8, 0.00, 0.06), new=TRUE)  
                ColorBar(brks=round(100*mean.brks[1:(l(mean.brks)-1)],0), cols=mean.cols[1:(length(mean.cols)-1)], vert=FALSE, label_scale=1.6, col_sup=mean.cols[l(mean.cols)])
                par(fig=c(0.7,0.9, 0.055, 0.08), new=TRUE)  
                mtext("%", font=2, cex=1.5)
                
                dev.off()

            } ## close if on max.x == 0 ...
            
        } ## close for on pnt (plant number)

        
    } ## close if on test.domain
    
    print("Finished!")
} ## close if on stations



extra.analysis <- FALSE
if(extra.analysis){  
    ##
    ## save .txt with the monthly frequencies of occurrence of the regimes for Belen:
    ##
    
    ## load(paste0(rootdir,"/2016_December/2016_December_psl.RData"))
    ## write.table(data.frame(1981:2016, round(100*wr1y,2), round(100*wr2y,2), round(100*wr3y,2), round(100*wr4y,2)), file="/shared/earth/Operational/EDPR/Belen/December.txt", row.names=FALSE, col.names=c("Year","Regime1", "Regime2", "Regime3", "Regime4"), sep="\t", quote=FALSE)


    ##
    ## monthly composition of impact of WRs on Capacity Factor:
    ##
    
    library(s2dverification)
    my.period <- c("January","February","March","April","May","June","July","August","September","October","November","December")
    my.brks.cf <- c(seq(-0.26,0.26,0.04)) ## 15 intervals and for values from 0 to 1 for the CF
    
    for(p in 1:12){
        my.title <- paste0("Impact of WRs on Wind Speed and CF in ", my.period[p], " 1981-2016\nSource: ERA-Interim")
        
        ##load imp, imp.area.lon e imp.area.lat variables:
        load(paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/EU_CF_iec1/2016_", my.period[p],"/WR_impact_on_CF.RData"))
        impact <- array(NA, c(16, dim(imp[[1]])))
        cl <- 1; for(fig in c(2,6,10,14)) { impact[fig,,] <- imp[[cl]]; cl <- cl + 1 }
        load(paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/EU_CF_iec2/2016_",my.period[p],"/WR_impact_on_CF.RData"))
        cl <- 1; for(fig in c(3,7,11,15)) { impact[fig,,] <- imp[[cl]]; cl <- cl + 1 }
        load(paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/EU_CF_iec3/2016_",my.period[p],"/WR_impact_on_CF.RData"))
        cl <- 1; for(fig in c(4,8,12,16)) { impact[fig,,] <- imp[[cl]]; cl <- cl + 1 }

        ## load relative wind impact too and psl anomalies:
        load(paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/EU_CF_sfcWind/2016_",my.period[p],"/WR_impact_on_sfcWind.RData"))
        cl <- 1; for(fig in c(1,5,9,13)) { impact[fig,,] <- impRel[[cl]]; cl <- cl + 1}

        PlotLayout(fun = PlotEquiMap, plot_dims = c(2,3), var = impact, lat = imp.area.lat, lon = imp.area.lon, nrow = 4, ncol = 4, filled.continents = FALSE, toptitle = my.title, title_scale=.7, title_margin_scale = 3, row_titles = c("WR 1", "WR 2", "WR 3", "WR 4"), col_titles = c("Surface Wind", "CF iec 1", "CF iec 2", "CF iec 3"), brks = my.brks.cf, triangle_ends = c(TRUE, TRUE), subsample = 1, bar_scale = 0.4, drawleg = "bottom", fileout = paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/compositions/composition_", my.period[p],".png"), width = 11, height = 12.5)

        ## Titleless for the S2S4E document:
        PlotLayout(fun = PlotEquiMap, plot_dims = c(2,3), var = impact, lat = imp.area.lat, lon = imp.area.lon, nrow = 4, ncol = 4, filled.continents = FALSE, row_titles = c("WR 1", "WR 2", "WR 3", "WR 4"), col_titles = c("Surface Wind", "CF iec 1", "CF iec 2", "CF iec 3"), brks = my.brks.cf, triangle_ends = c(TRUE, TRUE), subsample = 1, bar_scale = 0.4, drawleg = "bottom", fileout = paste0("/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor/compositions/composition_", my.period[p],"_titleless.png"), width = 10, height = 10.3)

    } ## close for on p




    ##
    ## Draw a similar composition but without PlotLayout()
    ##
    
    library(s2dverification)
    library(RColorBrewer)
    rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor" ## dir where the input files are stores
    source('/esarchive/scratch/ncortesi/ESS/general/hatching.R') # for hatching() function
    my.period <- c("January","February","March","April","May","June","July","August","September","October","November","December")
    my.brks.cf <- c(-1, seq(-0.26,0.26,0.04), 1) ## 15 intervals and for values from 0 to 1 for the CF
    my.cols.cf <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.cf)-1)    # blue--white--red colors
    pval <- 0.01 ## p-value level to show with hatching 

    size.horiz <- 0.21  ## width of a figure from 0 to 1 
    size.vert <- 0.19   ## height of a figure from 0 to 1
    size.cex <- 3       ## size of the colum and row titles
    left.border <- 0.07 ## space from the left border to the first column of figures
    down.border <- 0.03 ## space from the bottom border to the bottom figures
    column.title <- paste0("Regime ", 1:4) ## vector with the column titles

    my.cl <- array(NA, c(12,4)) ## array with the WR order
    my.cl[1,] <- c(1,4,3,2); my.cl[2,] <- c(1,4,3,2); my.cl[3,] <- c(1,4,3,2); my.cl[4,] <- c(4,2,1,3); my.cl[5,] <- c(4,2,3,1); my.cl[6,] <- c(2,1,4,3); 
    my.cl[7,] <- c(2,3,1,4); my.cl[8,] <- c(4,2,1,3); my.cl[9,] <- c(2,4,1,3); my.cl[10,] <- c(1,2,4,3); my.cl[11,] <- c(4,3,2,1); my.cl[12,] <- c(4,2,1,3);
    
    for(p in 1:12){
        my.fileout <- paste0(rootdir, "/compositions/impact_composition_", my.period[p],".png")
        
        png(filename = my.fileout, width=2200, height=2300)
        plot.new()

        ##
        ## Draw titles
        ##
        
        ## draw main title:
        par(fig=c(0, 1, 0.98, 0.995), new=TRUE)
        my.title <- paste0("Impact of WRs on Wind Speed and CF in ", my.period[p], " 1981-2016")
        mtext(my.title, cex = 4)
        
        ## draw column titles:
        for(cl in 1:4) { par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.90, 0.965), new=TRUE); mtext(text = column.title[cl], cex = size.cex) }

        ## draw row titles:
        my.row.label <- c("SLP", "sfcWind", "CF iec 1", "CF iec 2", "CF iec 3")
        for(r in 1:5){
            par(fig=c(0.01, 0.05, down.border + (r-1) * size.vert, down.border + r * size.vert), new=TRUE)
            if(r == 5) par(fig=c(0.01, 0.05, 0.81, 0.81 + 0.12), new=TRUE)
            mtext(side = 2, text = rev(my.row.label)[r], cex = size.cex, line = -1)
        }

        ##
        ## Draw figures
        ##
        
        ## load SLP anomalies:      
        load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[p], "/WR_impact_on_sfcWind.RData"))

        ## beware that the hatching() function only works if longitude values are continuous. The discontinuity between 360 degrees and 0 degrees is not considered.
        ## If your lon values go from 0 to 360, you have to modify the lon vector removing the discontinuity at 0 in order to draw the hatching lines correctly:
        lon.discontinuity <- 64 ## position of the element inside the lon vector 'bigarea.lon' corresponding to the start of the discontinuity
        bigarea.lon.mod <- c(bigarea.lon[lon.discontinuity:length(bigarea.lon)] - 360, bigarea.lon[1:(lon.discontinuity - 1)])
        sig.psl.mod <- list(); for(cl in 1:4) sig.psl.mod[[cl]] <- sig.psl[[cl]][, c(lon.discontinuity:length(bigarea.lon), 1:(lon.discontinuity - 1))]

        ## draw SLP anomalies:
        for(cl in 1:4){
            par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.81, 0.81 + 0.12), new=TRUE)
            PlotEquiMap(slpwrmean[[my.cl[p, cl]]], bigarea.lon, bigarea.lat, filled.continents = FALSE, brks = 100 * my.brks.cf, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE)
            hatching(lats = bigarea.lat, lons = bigarea.lon.mod, mask = t(sig.psl.mod[[my.cl[p, cl]]] < pval), dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE) 
        }

        ## draw sfcWind and iec anomalies:
        for(r in 1:4){
            if(r <= 3) load(paste0(rootdir, "/EU_CF_iec", 4 - r, "/2016_", my.period[p], "/WR_impact_on_CF.RData")) ## load CF iec X data
            if(r == 4) load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[p], "/WR_impact_on_sfcWind.RData")) ## load sfcWind data
            
            lon.discontinuity <- 58  ## position of the element inside the lon vector 'imp.area.lon' corresponding to the start of the discontinuity
            imp.area.lon.mod <- c(imp.area.lon[lon.discontinuity:length(imp.area.lon)] - 360, imp.area.lon[1:(lon.discontinuity - 1)])
            sig.mod <- list(); for(cl in 1:4) sig.mod[[cl]] <- sig[[cl]][, c(lon.discontinuity:length(imp.area.lon), 1:(lon.discontinuity -1))]

            for(cl in 1:4){
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border + (r-1) * size.vert, down.border + r * size.vert), new=TRUE)
                if(r <= 3) my.fig <- imp[[my.cl[p, cl]]] else my.fig <- impRel[[my.cl[p, cl]]] ## CF iec X data is stored inside 'imp', sfcWind data is stored inside 'impRel'
                PlotEquiMap(my.fig, imp.area.lon, imp.area.lat, filled.continents = FALSE, brks = my.brks.cf, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE, margin_scale = rep(1,4))
                hatching(lats = imp.area.lat, lons = imp.area.lon.mod, mask = t(sig.mod[[my.cl[p, cl]]] < pval), dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
            }
        }
        

        ##
        ## Draw ColorBars
        ##

        unit <- c("", "", "", "%", "hPa")
        brks.multiplier <- c(1, 1, 1, 100, 100)
        for(r in 1:5){
            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.06, down.border + (r-1) * size.vert + 0.01,  down.border + r * size.vert - 0.01), new=TRUE)
            if(r == 5) par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.06, 0.81, 0.81 + 0.12), new=TRUE)
            
            ColorBar(brks = brks.multiplier[r] * my.brks.cf[-c(1,length(my.brks.cf))], cols = my.cols.cf[-c(1, length(my.cols.cf))], vert = TRUE, subsample = 1, label_scale = 1.8, triangle_ends = c(TRUE, TRUE), col_inf = my.cols.cf[1], col_sup = my.cols.cf[length(my.cols.cf)])

            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.06, down.border + r * size.vert - 0.01, down.border + r * size.vert - 0.009), new=TRUE)
            if(r == 5) par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.06, 0.93, 0.932), new=TRUE)
            
            mtext(unit[r], cex = 2)

        }


        ##
        ## Draw coordinate labels
        ##
        
        for(cl in 1:4){
            ## add geographical coordinated at the bottom:
            par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border - 0.03, down.border - 0.005), new=TRUE)
            mtext("                                            10W           0          10E         20E         30E", cex = 1.5)
            
            ## add geographical coordinated at the top (SLP maps):
            par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.795, 0.805), new=TRUE)
            mtext("                                              70W      50W      30W      10W      10E      30E", cex = 1.5)
            
            ## add geographical coordinated at the left:
            par(fig=c(0.067, 0.077, down.border - 0.025 + (cl - 1) * size.vert, down.border + cl * size.vert), new=TRUE)
            mtext("                       40N              50N              60N              70N", cex = 1.5, side = 2)

            ## add geographical coordinated at the top left (SLP maps):
            par(fig=c(0.067, 0.077, 0.81, 0.81 + 0.12), new=TRUE)
            if(cl == 1) mtext("          40N            60N            80N", cex = 1.5, side = 2)
        }
        
        dev.off()
        
    } ## close for on p


    ##
    ## Composition with the SLP or sfcWind anomalies for each WR and month:
    ##
            
    library(s2dverification)
    library(RColorBrewer)
    source('/esarchive/scratch/ncortesi/ESS/general/hatching.R') # for hatching() function
    rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor" ## dir where the input files are stores
    my.period <- c("January","February","March","April","May","June","July","August","September","October","November","December")
    my.brks.cf <- c(-1, seq(-0.26,0.26,0.04), 1) ## 15 intervals and for values from 0 to 1 for the CF
    my.cols.cf <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.cf)-1)    # blue--white--red colors

    pval <- 0.01 ## p-value level to show with hatching 
    size.horiz <- 0.21  ## width of a figure from 0 to 1 
    size.vert <- 0.15   ## height of a figure from 0 to 1
    size.cex <- 3       ## size of the colum and row titles
    left.border <- 0.07 ## space from the left border to the first column of figures
    down.border <- 0.03 ## space from the bottom border to the bottom figures
    column.title <- paste0("Regime ", 1:4) ## vector with the column titles

    for(variable in c("sfcWind", "SLP")){        
        ## names to show in the filename and in the figures:
        if(variable == "sfcWind") { variable.name <- "Surface_Wind"; variable.fig <- "Surface Wind" }
        if(variable == "SLP") { variable.name <- "SLP"; variable.fig <- "Sea Level Pressure" }

        for(figures in 1:2){
            my.months <- 1:6 + 6 * (figures - 1)    ## select which months are to be plotted
            my.fileout <- paste0(rootdir, "/compositions/composition_", variable.name, "_", figures, ".png")

            if(variable == "sfcWind") my.height <- 2700 else my.height <- 1800
            png(filename = my.fileout, width=2200, height=my.height)
            
            plot.new()

            ##
            ## Draw titles
            ##
            
            ## draw main title:
            par(fig=c(0, 1, 0.98, 0.995), new=TRUE)
            my.title <- paste0("Impact of WRs on ", variable.fig, " in 1981-2016")
            mtext(my.title, cex = 4)
            
            ## draw column titles:
            if(variable == "sfcWind") mod.var <- 0 else mod.var <- 0.06
            for(cl in 1:4) {
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.96, 0.965), new=TRUE)
                mtext(text = column.title[cl], cex = size.cex)
            }

            ## draw row titles:
            my.row.label <- my.period[my.months]
            for(r in my.months){
                if(figures == 2) m <- r - 6 else m <- r
                par(fig=c(0.01, 0.05, down.border + (m-1) * size.vert, down.border + m * size.vert), new=TRUE)
                mtext(side = 2, text = rev(my.row.label)[m], cex = size.cex, line = -2)
            }

            ##
            ## Draw figures
            ##

            ## draw sfcWind anomalies:
            for(r in my.months){
                load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[r], "/WR_impact_on_sfcWind.RData")) ## load sfcWind and SLP data

                if(variable == "SLP"){
                    lon.discontinuity <- 64 ## position of the element inside the lon vector 'bigarea.lon' corresponding to the start of the discontinuity
                    bigarea.lon.mod <- c(bigarea.lon[lon.discontinuity:length(bigarea.lon)] - 360, bigarea.lon[1:(lon.discontinuity - 1)])
                    sig.psl.mod <- list(); for(cl in 1:4) sig.psl.mod[[cl]] <- sig.psl[[cl]][, c(lon.discontinuity:length(bigarea.lon), 1:(lon.discontinuity - 1))]
                    my.lat <- bigarea.lat
                    my.lon <- bigarea.lon
                    my.lon.mod <- bigarea.lon.mod
                } else {
                    lon.discontinuity <- 58  ## position of the element inside the lon vector 'imp.area.lon' corresponding to the start of the discontinuity
                    imp.area.lon.mod <- c(imp.area.lon[lon.discontinuity:length(imp.area.lon)] - 360, imp.area.lon[1:(lon.discontinuity - 1)])
                    sig.mod <- list(); for(cl in 1:4) sig.mod[[cl]] <- sig[[cl]][, c(lon.discontinuity:length(imp.area.lon), 1:(lon.discontinuity -1))]
                    my.lat <- imp.area.lat
                    my.lon <- imp.area.lon
                    my.lon.mod <- imp.area.lon.mod
                }
                
                if(figures == 2) m <- 13 - r else m <- 7 - r
                for(cl in 1:4){
                    par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border + (m-1) * size.vert, down.border + m * size.vert), new=TRUE)
                    if(variable == "sfcWind") {my.imp <- impRel[[my.cl[r, cl]]]; my.sig <- sig.mod[[my.cl[r, cl]]]; brks.mod <- 1 } else { my.imp <- slpwrmean[[my.cl[r, cl]]]; my.sig <- sig.psl.mod[[my.cl[r, cl]]]; brks.mod = 100 }

                    PlotEquiMap(my.imp, my.lon, my.lat, filled.continents = FALSE, brks = my.brks.cf * brks.mod, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE, margin_scale = rep(1,4))
                    hatching(lats = my.lat, lons = my.lon.mod, mask = t(my.sig < pval), dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
                }
            }
            
            ##
            ## Draw ColorBars
            ##

            unit <- c("%", "hPa")
            brks.multiplier <- c(1, 1, 1, 100, 100)
            
            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.09, down.border + 0.1,  down.border + 6 * size.vert - 0.1), new=TRUE)

            ColorBar(brks = 100 * my.brks.cf[-c(1,length(my.brks.cf))], cols = my.cols.cf[-c(1, length(my.cols.cf))], vert = TRUE, subsample = 1, label_scale = 2.8, triangle_ends = c(TRUE, TRUE), col_inf = my.cols.cf[1], col_sup = my.cols.cf[length(my.cols.cf)])

            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.09, down.border + 6 * size.vert - 0.13, down.border + 6 * size.vert - 0.13 + 0.01), new=TRUE)    
            if(variable == "sfcWind") mtext(unit[1], cex = 3) else  mtext(unit[2], cex = 3)

            
            ##
            ## Draw coordinate labels
            ##
            
            for(cl in 1:4){
                ## add geographical coordinated at the bottom:
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border - 0.03, down.border - 0.005), new=TRUE)
                if(variable == "sfcWind") mtext("                                            10W           0          10E         20E         30E", cex = 1.5)
                if(variable == "SLP") mtext("                                              70W      50W      30W      10W      10E      30E", cex = 1.5)
            }

            for(r in 1:6){
                ## add geographical coordinated at the left:
                par(fig=c(0.067, 0.077, down.border - 0.025 + (r - 1) * size.vert, down.border + r * size.vert), new=TRUE)
                if(variable == "sfcWind") mtext("                       40N              50N              60N              70N", cex = 1.5, side = 2)
                if(variable == "SLP") mtext("          40N            60N            80N", cex = 1.5, side = 2)
            }
            
            dev.off()
            
        } ## close for on figures    

    } ## close for on variables

    ## save bigdate.lon and bigdata.lat in the .RData files if they were not saved when the .RData was created:
    ## for(mm in 1:12){
    ##     load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[mm], "/WR_impact_on_sfcWind.RData")) ## load sfcWind and SLP data
    ##     save(impRel, sig, slpwrmean, sig.psl, imp.area.lon, imp.area.lat, bigarea.lon, bigarea.lat, file=paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[mm], "/WR_impact_on_sfcWind.RData"))
    ## }



    ##
    ## Draw a similar composition but for Teleconnections instead of regimes:
    ##
    
    library(s2dverification)
    library(RColorBrewer)
    rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor" ## dir where the input files are stores
    source('/esarchive/scratch/ncortesi/ESS/general/hatching.R') # for hatching() function
    my.period <- c("January","February","March","April","May","June","July","August","September","October","November","December")
    my.brks.cf <- seq(-1, 1, 0.1) ## 15 intervals and for values from 0 to 1 for the CF
    my.cols.cf <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.cf)-1)    # blue--white--red colors

    size.horiz <- 0.21  ## width of a figure from 0 to 1 
    size.vert <- 0.185   ## height of a figure from 0 to 1
    size.cex <- 3       ## size of the colum and row titles
    left.border <- 0.07 ## space from the left border to the first column of figures
    down.border <- 0.05 ## space from the bottom border to the bottom figures
    column.title <- c("NAO", "EA", "EA/WR", "SCA") ## vector with the column titles

    ## load data:
    data <- readRDS("/esarchive/scratch/llledo/S2S4E/EATC/EATC_impact_correlations.RDS")
    data.g500 <- readRDS("/esarchive/scratch/llledo/S2S4E/EATC/EATC_corr.RDS")  ## format: [12, 4, 85, 214] = [month, TP, lat, lon]

    ## load imp.area.lon and imp.area.lat:     
    load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[1], "/WR_impact_on_sfcWind.RData"))
    
    ## load lat and lon data from era-interim:      
    erai <- Load('psl', exp = NULL,
             obs = 'erainterim',
             sdates = paste0(1981, '0101'),
             storefreq = 'monthly',
             leadtimemin = 1, leadtimemax = 1,
             output = 'lonlat', nprocs=1)

    ## erai$lat ## check once which value of lat corresponds to the first value of imp.area.lat (25)
    ## erai$lon ## check once which value of lon corresponds to the discontinuity value of impact.area.lon (488)
    
    ## load lat and lon data of g500 (bigger domain) It should be [85x214]
    coord.g500 <- Load('g500', exp = NULL,
             obs = 'erainterim',
             sdates = paste0(1981, '0101'),
             storefreq = 'monthly',
             leadtimemin = 1, leadtimemax = 1,
             latmin = 20, latmax = 80,
             lonmin = 270, lonmax = 60, output = 'lonlat', nprocs=1)

    bigarea.lat <- coord.g500$lat
    bigarea.lon <- coord.g500$lon

    for(p in 1:12){
        my.fileout <- paste0(rootdir, "/compositions_teleconnections/impact_composition_", my.period[p],".png")
        
        png(filename = my.fileout, width=2200, height=2300)
        plot.new()

        ##
        ## Draw titles
        ##
        
        ## draw main title:
        par(fig=c(0, 1, 0.98, 0.995), new=TRUE)
        my.title <- paste0("Impact of Euro-Altantic Teleconnections on Wind Speed and CF in ", my.period[p], " 1981-2016")
        mtext(my.title, cex = 4)
        
        ## draw column titles:
        for(cl in 1:4) { par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.90, 0.965), new=TRUE); mtext(text = column.title[cl], cex = size.cex) }

        ## draw row titles:
        my.row.label <- c("g500", "sfcWind", "CF iec 1", "CF iec 2", "CF iec 3")
        for(r in 1:5){
            par(fig=c(0.01, 0.05, down.border + (r-1) * size.vert, down.border + r * size.vert), new=TRUE)
            if(r == 5) par(fig=c(0.01, 0.05, 0.81, 0.81 + 0.12), new=TRUE)
            mtext(side = 2, text = rev(my.row.label)[r], cex = size.cex, line = -1)
        }

        ##
        ## Draw figures
        ##
       
        ## beware that the hatching() function only works if longitude values are continuous. The discontinuity between 360 degrees and 0 degrees is not considered.
        ## If your lon values go from 0 to 360, you have to modify the lon vector removing the discontinuity at 0 in order to draw the hatching lines correctly:
        lon.discontinuity <- 87 ## position of the element inside the lon vector 'bigarea.lon' corresponding to the start of the discontinuity
        bigarea.lon.mod <- c(bigarea.lon[lon.discontinuity:length(bigarea.lon)] - 360, bigarea.lon[1:(lon.discontinuity - 1)])
        data.g500.mod <- data.g500 * NA; for(cl in 1:4) data.g500.mod[p, cl,,] <- data.g500[p, cl,, c(lon.discontinuity:length(bigarea.lon), 1:(lon.discontinuity - 1))]

        ## draw g500 anomalies:
        for(cl in 1:4){
            par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.81, 0.81 + 0.12), new=TRUE)
            PlotEquiMap(data.g500[p, cl,,], bigarea.lon, bigarea.lat, filled.continents = FALSE, brks = my.brks.cf, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE)
            data.g500.mod.sig <- array(as.logical((data.g500.mod[p, cl,,] < 0.4238) * (data.g500.mod[p, cl,,] > -0.4238)), c(length(bigarea.lat), length(bigarea.lon)))
            hatching(lats = bigarea.lat, lons = bigarea.lon.mod, mask = t(!data.g500.mod.sig), dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
        }

        ## draw sfcWind and iec anomalies:
        for(r in 1:4){
            my.r <- c(4, 3, 2, 1)
            lon.discontinuity <- 58  ## position of the element inside the lon vector 'imp.area.lon' corresponding to the start of the discontinuity
            imp.area.lon.mod <- c(imp.area.lon[lon.discontinuity:length(imp.area.lon)] - 360, imp.area.lon[1:(lon.discontinuity - 1)])
            data.mod <- list(); for(cl in 1:4) data.mod[[cl]] <- data[[p]][[cl]][[my.r[r]]][c(488:length(erai$lon), 1:(lon.discontinuity - 1)), 26:(26 + length(imp.area.lat) - 1)]

            for(cl in 1:4){
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border + (r-1) * size.vert, down.border + r * size.vert), new=TRUE)

                PlotEquiMap(data.mod[[cl]], imp.area.lon.mod, imp.area.lat, filled.continents = FALSE, brks = my.brks.cf, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE, margin_scale = rep(1,4))

                data.mod.sig <- array(as.logical((data.mod[[cl]] < 0.4238) * (data.mod[[cl]] > -0.4238)), c(length(imp.area.lon), length(imp.area.lat)))

                hatching(lats = imp.area.lat, lons = imp.area.lon.mod, mask = !data.mod.sig, dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
            }
        }
        
        
        
        ##
        ## Draw coordinate labels
        ##
        
        for(cl in 1:4){
            ## add geographical coordinated at the bottom:
            par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border - 0.03, down.border - 0.005), new=TRUE)
            mtext("10W           0          10E         20E         30E", cex = 1.5)
            
            ## add geographical coordinated at the top (SLP maps):
            par(fig=c(left.border + (cl-1) * size.horiz - 0.01, left.border + (cl-1) * size.horiz + size.horiz, 0.795, 0.805), new=TRUE)
            mtext("70W     50W     30W     10W     10E     30E", cex = 1.5)
            
            ## add geographical coordinated at the left:
            par(fig=c(0.067, 0.077, down.border - 0.025 + (cl - 1) * size.vert, down.border + cl * size.vert), new=TRUE)
            mtext("                       40N              50N              60N              70N", cex = 1.5, side = 2)

            ## add geographical coordinated at the top left (SLP maps):
            par(fig=c(0.067, 0.077, 0.81, 0.81 + 0.12), new=TRUE)
            if(cl == 1) mtext("          40N            60N            80N", cex = 1.5, side = 2)
        }

        ##
        ## Draw ColorBars
        ##        

        par(fig=c(0.2, 0.8, 0, 0.04), new=TRUE)            
        ColorBar(brks = my.brks.cf, cols = my.cols.cf, vert = FALSE, subsample = 1, label_scale = 1.8, title = "correlation", title_scale = 2)

        dev.off()

        
    } ## close for on p


    ##
    ## Composition with the Geopotential or sfcWind anomalies for each teleconnection and month:
    ##
            
    library(s2dverification)
    library(RColorBrewer)
    source('/esarchive/scratch/ncortesi/ESS/general/hatching.R') # for hatching() function
    rootdir <- "/esarchive/scratch/ncortesi/Regimes/88_Capacity_Factor" ## dir where the input files are stores
    my.period <- c("January","February","March","April","May","June","July","August","September","October","November","December")
    my.brks.cf <- seq(-1, 1, 0.1) ## 15 intervals and for values from 0 to 1 for the CF
    my.cols.cf <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.cf)-1)    # blue--white--red colors

    size.horiz <- 0.21  ## width of a figure from 0 to 1 
    size.vert <- 0.15   ## height of a figure from 0 to 1
    size.cex <- 3       ## size of the colum and row titles
    left.border <- 0.07 ## space from the left border to the first column of figures
    down.border <- 0.03 ## space from the bottom border to the bottom figures
    column.title <- c("NAO", "EA", "EA/WR", "SCA") ## vector with the column titles
    
    ## load data:
    data <- readRDS("/esarchive/scratch/llledo/S2S4E/EATC/EATC_impact_correlations.RDS")
    data.g500 <- readRDS("/esarchive/scratch/llledo/S2S4E/EATC/EATC_corr.RDS")  ## format: [12, 4, 85, 214] = [month, TP, lat, lon]

    ## load imp.area.lon and imp.area.lat:     
    load(paste0(rootdir, "/EU_CF_sfcWind/2016_", my.period[p], "/WR_impact_on_sfcWind.RData"))
    
    ## load lat and lon data from era-interim:      
    erai <- Load('psl', exp = NULL,
             obs = 'erainterim',
             sdates = paste0(1981, '0101'),
             storefreq = 'monthly',
             leadtimemin = 1, leadtimemax = 1,
             output = 'lonlat', nprocs=1)

     ## load lat and lon data of g500 (bigger domain) It should be [85x214]
    coord.g500 <- Load('g500', exp = NULL,
             obs = 'erainterim',
             sdates = paste0(1981, '0101'),
             storefreq = 'monthly',
             leadtimemin = 1, leadtimemax = 1,
             latmin = 20, latmax = 80,
             lonmin = 270, lonmax = 60, output = 'lonlat', nprocs=1)

    bigarea.lat <- coord.g500$lat
    bigarea.lon <- coord.g500$lon
    
    for(variable in c("sfcWind", "g500")){        
        ## names to show in the filename and in the figures:
        if(variable == "sfcWind") { variable.name <- "Surface_Wind"; variable.fig <- "Surface Wind" }
        if(variable == "g500") { variable.name <- "g500"; variable.fig <- "Geopotential Height" }

        for(figures in 1:2){
            my.months <- 1:6 + 6 * (figures - 1)    ## select which months are to be plotted
            my.fileout <- paste0(rootdir, "/compositions_teleconnections/", variable.name, "_composition_", figures, ".png")

            if(variable == "sfcWind") my.height <- 2700 else my.height <- 1800
            png(filename = my.fileout, width=2200, height=my.height)
            
            plot.new()

            ##
            ## Draw titles
            ##
            
            ## draw main title:
            par(fig=c(0, 1, 0.98, 0.995), new=TRUE)
            my.title <- paste0("Impact of Teleconnections on ", variable.fig, " in 1981-2016")
            mtext(my.title, cex = 4)
            
            ## draw column titles:
            if(variable == "sfcWind") mod.var <- 0 else mod.var <- 0.06
            for(cl in 1:4) {
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, 0.96, 0.965), new=TRUE)
                mtext(text = column.title[cl], cex = size.cex)
            }

            ## draw row titles:
            my.row.label <- my.period[my.months]
            for(r in my.months){
                if(figures == 2) m <- r - 6 else m <- r
                par(fig=c(0.01, 0.05, down.border + (m-1) * size.vert, down.border + m * size.vert), new=TRUE)
                mtext(side = 2, text = rev(my.row.label)[m], cex = size.cex, line = -2)
            }

            ##
            ## Draw figures
            ##

            ## draw sfcWind anomalies:
            for(r in my.months){
                if(variable == "g500"){
                    lon.discontinuity <- 87 ## position of the element inside the lon vector 'bigarea.lon' corresponding to the start of the discontinuity
                    bigarea.lon.mod <- c(bigarea.lon[lon.discontinuity:length(bigarea.lon)] - 360, bigarea.lon[1:(lon.discontinuity - 1)])
                    data.g500.mod <- data.g500 * NA; for(cl in 1:4) data.g500.mod[r, cl,,] <- data.g500[r, cl,, c(lon.discontinuity:length(bigarea.lon), 1:(lon.discontinuity - 1))]
                    my.lat <- bigarea.lat
                    my.lon <- bigarea.lon
                    my.lon.mod <- bigarea.lon.mod

                } else {
                    lon.discontinuity <- 58  ## position of the element inside the lon vector 'imp.area.lon' corresponding to the start of the discontinuity
                    imp.area.lon.mod <- c(imp.area.lon[lon.discontinuity:length(imp.area.lon)] - 360, imp.area.lon[1:(lon.discontinuity - 1)])
                    data.mod <- list(); for(cl in 1:4) data.mod[[cl]] <- data[[r]][[cl]][[1]][c(488:length(erai$lon), 1:(lon.discontinuity - 1)), 26:(26 + length(imp.area.lat) - 1)]
                    my.lat <- imp.area.lat
                    my.lon <- imp.area.lon
                    my.lon.mod <- imp.area.lon.mod
                }
                
                if(figures == 2) m <- 13 - r else m <- 7 - r
                for(cl in 1:4){
                    par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border + (m-1) * size.vert, down.border + m * size.vert), new=TRUE)
                    
                    if(variable == "sfcWind") {
                        my.imp <- data.mod[[cl]]
                        my.sig <- t(array(as.logical((data.mod[[cl]] < 0.4238) * (data.mod[[cl]] > -0.4238)), c(length(imp.area.lon), length(imp.area.lat))))
                    } else {
                        my.imp <- data.g500.mod[r, cl,,]
                        my.sig <- array(as.logical((data.g500.mod[r, cl,,] < 0.4238) * (data.g500.mod[r, cl,,] > -0.4238)), c(length(bigarea.lat), length(bigarea.lon)))    
                    }

                    PlotEquiMap(my.imp, my.lon.mod, my.lat, filled.continents = FALSE, brks = my.brks.cf, cols = my.cols.cf, drawleg = FALSE, axelab = FALSE, margin_scale = rep(1,4))
                    hatching(lats = my.lat, lons = my.lon.mod, mask = t(!my.sig), dens = 10, ang = 45, col_line = '#252525', lwd_size = 1, crosshatching = FALSE)
                }
            }
         
            ##
            ## Draw ColorBars
            ##

            unit <- c("cor", "cor")
            
            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.09, down.border + 0.1,  down.border + 6 * size.vert - 0.1), new=TRUE)

            ColorBar(brks = my.brks.cf, cols = my.cols.cf, vert = TRUE, subsample = 1, label_scale = 2.8)

            par(fig=c(left.border + 4 * size.horiz, left.border + 4 * size.horiz + 0.09, down.border + 6 * size.vert - 0.13, down.border + 6 * size.vert - 0.13 + 0.01), new=TRUE)    
            if(variable == "sfcWind") mtext(unit[1], cex = 3) else  mtext(unit[2], cex = 3)

            
            ##
            ## Draw coordinate labels
            ##
            
            for(cl in 1:4){
                ## add geographical coordinated at the bottom:
                par(fig=c(left.border + (cl-1) * size.horiz , left.border + (cl-1) * size.horiz + size.horiz, down.border - 0.03, down.border - 0.005), new=TRUE)
                if(variable == "sfcWind") mtext("                                            10W           0          10E         20E         30E", cex = 1.5)
                if(variable == "g500") mtext("                                              70W      50W      30W      10W      10E      30E", cex = 1.5)
            }

            for(r in 1:6){
                ## add geographical coordinated at the left:
                par(fig=c(0.067, 0.077, down.border - 0.025 + (r - 1) * size.vert, down.border + r * size.vert), new=TRUE)
                if(variable == "sfcWind") mtext("                       40N              50N              60N              70N", cex = 1.5, side = 2)
                if(variable == "g500") mtext("          40N            60N            80N", cex = 1.5, side = 2)
            }
            
            dev.off()
            
        } ## close for on figures    

    } ## close for on variables
    
} ## close if on extra.analysis



