
# Creation:  6/2016
# Author: Nicola Cortesi
# Aim: To compute the four Euro-Atlantic weather regimes from a reanalysis or from a forecast system
#
# I/O: input must be in a format compatible with Load(); 1 output .RData file is created in the 'workdir' folder.
#      You can also run this script from terminal with: Rscript ~/scripts/weather_regimes_maps.R
#
# Assumption:  its output are needed by the scripts weather_regimes_impact.R and  weather_regimes.R
#
# Branch: weather_regimes

rm(list=ls())
library(s2dverification)  # for the function Load() and InsertDim()
library(abind) # for function abind()
library(Kendall) # for the MannKendall test
library(reshape2) # for functions acast() and melt(). WARNING: after each update of s2dverification, it's better to remove and install this package again because sometimes it gets broken! 

source('/home/Earth/ncortesi/scripts/Rfunctions.R')

rean <- '/esnas/recon/jma/jra55/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc' 
rean.name <- "JRA-55"

psl <- "psl" #"g500"                           # pressure variable to use from the chosen reanalysis
psl.name <- "SLP" # "Z500"                     # the name to show in the maps

year.start <- 1981 
year.end <- 2017

LOESS <- TRUE              # To apply the LOESS filter or not to the climatology
running.cluster <- FALSE   # add to the clustering also the daily SLP data of the two closer months to the month to use (only for monthly analysis)
running.15 <- FALSE        # add to the clustering also the daily SLP data of the 15 days of the two closer months (only for monthly analysis). You cannot set to TRUE both
                           # this variable and 'running.cluster' above
lat.weighting <- TRUE      # set it to true to weight psl data on latitude before applying the cluster analysis
subdaily <- FALSE          # id TRUE, compute the clustering using 6-hourly data instead of daily data, to be more robust (only for reanalysis with 6-hourly data avail.)

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

# Coordinates of the box enclosing the study region (the Northern Atlantic in this case):
lat.max <- 81 #81 #80 #70
lat.min <- 27 #30 #20 #30
lon.max <- 45 #36 #30 #40 
lon.min <- 274.5 #274.5 #270 #280 # put a positive number here because the geopotential has only positive vaues of longitud!

period <- 1  #1:12 #13:16           # 1-12: Jan-Dec; 13-16: Winter-Spring-Summer-Autumn  [bypassed by the optional argument of the script]

var.num <- 1                                     # Choose a variable. 1: sfcWind  2: tas
var.name <- c("sfcWind","tas")                   # name of the 'predictand' variable of the chosen reanalysis
var.name.full <- c("wind Speed","temperature")   # full name of the 'predictand' variable to put in the title of the graphs
var.unit <- c("m/s", "ºC")                       # unit of measure of var (for drawing color scales)

orden <- c("NAO+","NAO-","Blocking","Atl.Ridge")

no.regimes <- TRUE # if TRUE, instead of putting the regime names in the figure titles, insert "Cluster1", "Cluster2", "Cluster3" and "Cluster4"
                   # (when composition='edpr' or monthly_anomalies = TRUE)

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

# in case the script is run with two external arguments, it is assumed a forecast is used and the first argument represents the startmonth and the second one the leadmonth.
script.arg <- as.integer(commandArgs(TRUE))

if(length(script.arg) >= 2){
   year.end <- script.arg[1]                 
   period <- script.arg[2]
}

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

if(running.cluster && running.15) stop("both 'running.cluster' and 'running.15' cannot be TRUE simultaneously")

cat(paste0("Rean: ", rean.name, " Period: ", period, " Year: ", year.end, "\n"))

if(no.regimes) { regime.title <- paste0("Cluster",1:4) } else { regime.title <- orden}

## create working directory:
workdir <- paste0("/shared/earth/EarthSystemServices/EDPR/", year.end, "_", my.month[period])   # working dir where output files will be generated
dir.create(file.path(workdir))

n.map <- 0

cat("Loading lat/lon. Please wait...\n")

## load only 1 day of pressure data to detect the minimum and maximum lat and lon values which identify only the North Atlantic area:
domain <- Load(var = psl, exp = NULL, obs = list(list(path=rean)), paste0(year.start,'0101'), storefreq = 'daily', leadtimemax = 1, output = 'lonlat', nprocs=1)

n.lon <- length(domain$lon)
n.lat <- length(domain$lat)

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

pos.lat <- if(pos.lat.min < pos.lat.max) {pos.lat.min:pos.lat.max} else {pos.lat.max:pos.lat.min}
pos.lon <- c(1:pos.lon.max,pos.lon.min:length(domain$lon)) # beware that it only consider the case where the study area cross the meridian of Greenwhich!
n.pos.lat <- length(pos.lat)
n.pos.lon <- length(pos.lon)

lat <- domain$lat[pos.lat] # lat values of chosen area only (it is smaller than the whole spatial domain loaded by the data)
#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 chosen area only

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

#################### Start analysis #######################################################3

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

psleuFull <-array(NA,c(1, 1, n.years, 365, n.pos.lat, n.pos.lon))

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=1)

## remove bisestile days to have all arrays with the same dimensions:
cat("Removing bisestile days. Please wait...\n")
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()

if((running.cluster || running.15)) {        
    ## the months after the last month of the last year loaded are automatically filled with NA by Load(); however, the clustering algorithm doesn't want NA, so
    ## we have to replace them with some values, in this case the mean of the previous years not to affect the analysis too much.
    ## if we want to be able to compute the running clustering.
    ## WARNING: in case your last month is December, for the running clustering it will use the january data of the last year loaded, not of the next year:
    ## psleuFull[,,n.years,305:334,,] <-  psleuFull[,,n.years-1,305:334,,]
    
    month.NA <- psleuFull366$not_found_files[1] # filename of the file with the first month with NA (string value with full file path)
    first.month.NA <- as.integer(substr(month.NA,nchar(month.NA)-4,nchar(month.NA)-3)) # first month with NA
    first.day.NA <- pos.period(1,first.month.NA)[1] # first day with NA (counting from the start of the year)

    psleuFullnolast <- psleuFull[,,1:(n.years-1),first.day.NA:365,,]
    psleuFullMean <- apply(psleuFullnolast, c(2,3,4), mean, na.rm=TRUE) # mean of the previous years
    
    psleuFull[,,n.years,first.day.NA:365,,] <-  psleuFullMean
    
    rm(psleuFullnolast, psleuFullMean)

}

## convert psl in daily anomalies with the LOESS filter:
cat("Calculating anomalies. Please wait...\n")
psleuFull_no_last_year <- psleuFull[1,1,1:n.years.clim,,,,drop=FALSE]
pslPeriodClim <- apply(psleuFull_no_last_year, c(1,2,4,5,6), mean, na.rm=T)
rm(psleuFull_no_last_year)
gc()

if(LOESS == TRUE){
    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=pslPeriodClim[1,1,,i,j], day=1:365)
            my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
            pslPeriodClimLoess[1,1,,i,j] <- predict(my.loess)
        }
    }

    rm(pslPeriodClim)
    gc()

    pslPeriodClim2 <- InsertDim(pslPeriodClimLoess, 3, n.years)
    
} else { # leave the daily climatology to compute the anomalies:
    pslPeriodClim2  <- InsertDim(pslPeriodClim, 3, n.years)
    
    rm(pslPeriodClim)
    gc()
}

psleuFull <- psleuFull - pslPeriodClim2    
rm(pslPeriodClim2)
gc()

if(psl=="g500") 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()

# compute the cluster analysis:
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:

    ## pslPeriod <- psleuFull[days.period[[p]],,] # select only days in the chosen period (i.e: winter)
    if(running.cluster) {
        if(subdaily){
            my.hours <- sort(c(pos.month.extended(1,p)*4-3,  pos.month.extended(1,p)*4-2,  pos.month.extended(1,p)*4-1,  pos.month.extended(1,p)*4))
            if(p == 1) my.hours <- c(1337:1460,1:236)
            if(p == 12) my.hours <- c(1217:1460,1:124)
            
            pslPeriod <- psleuFull[,my.hours,,] # select all days in the period of 3 months centered on the target month p
            
        } else {
            pslPeriod <- psleuFull[1,1,,pos.month.extended(1,p),,] # select all days in the period of 3 months centered on the target month p
        }
        
    }

    if(running.15) pslPeriod <- psleuFull[1,1,,pos.month.extended15(1,p),,]
    
    ## if there isn't any kind of running clustering:
    if(!running.cluster && !running.15) {    
        if(subdaily){
            my.hours <- sort(c(pos.month(1,p)*4-3, pos.month(1,p)*4-2, pos.month(1,p)*4-1, pos.month(1,p)*4))
            pslPeriod <- psleuFull[,my.hours,,]
        } else {             
            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){
        lat.weighted <- cos(lat*pi/180)^0.5
        if(!running.cluster && !running.15) lat.weighted.array <- InsertDim(InsertDim(InsertDim(lat.weighted,2,n.pos.lon), 1, length(pos.period(2001,p))), 1, n.years)
        if(running.cluster)  lat.weighted.array <- InsertDim(InsertDim(InsertDim(lat.weighted,2,n.pos.lon), 1, length(pos.month.extended(2001,p))), 1, n.years)
        if(running.15)  lat.weighted.array <- InsertDim(InsertDim(InsertDim(lat.weighted,2,n.pos.lon), 1, length(pos.month.extended15(2001,p))), 1, n.years)

        pslPeriod <- pslPeriod * lat.weighted.array
        
        rm(lat.weighted.array)
        gc()
    }

    gc()
    cat("Preformatting data for clustering. Please wait...\n")
    psl.melted <- melt(pslPeriod[,,,, drop=FALSE], varnames=c("Year","Day","Lat","Lon"))
    gc()
    
    cat("Preformatting data for clustering. Please wait......\n")
    
    ## this function eats much memory!!!
    psl.kmeans <- unname(acast(psl.melted, Year + Day ~ Lat + Lon))
    gc()

        
    # compute the clustering:
    cat("Clustering data. Please wait.........\n")
    if(PCA){ 
       my.seq <- seq(1, n.pos.lat*n.pos.lon, 16) # select only 1 point of 9
       pslcut <- psl.kmeans[,my.seq]
  
       my.PCA <- princomp(pslcut,cor=FALSE)
       tot.variance <- head(cumsum(my.PCA$sdev^2 / sum(my.PCA$sdev^2)),50)  # 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 80% of variance
       my.cluster <- kmeans(my.PCA$scores[,1:n.pcs], centers=4, iter.max=100, nstart=30)  # 4 is the number of clusters
       rm(pslcut)
       
    } else {  # 4 is the number of clusters:

       my.cluster <- kmeans(psl.kmeans, centers=4, iter.max=100, nstart=30, trace=FALSE)        
       gc()
        
    }
    
    rm(psl.kmeans)
    gc()
        
    cat("Extracting monthly regimes. Please wait............\n")

    if(running.cluster && p < 13){
        ## select only the days inside the 3-months cluster series that belong only to the target month p:
        n.days.period <- length(pos.month.extended(1,p))  # total number of days in the three months
        
        days.month <- days.month.new <- days.month.full <- c()
        days.month <- which(pos.month.extended(1,p) == pos.month(1,p)[1]) - 1 + 1:length(pos.month(1,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)
            ## print(days.month.new)
            ## print(days.month)
        }

        ## in this case, we are not selecting days but 6-hourly intervals:
        if(subdaily) days.month.full <- sort(c(days.month.full*4, days.month.full*4+1, days.month.full*4+2, days.month.full*4+3))

        ## select only the days of the cluster series inside the target month p:
        cluster.sequence <- my.cluster$cluster[days.month.full] 

    }

    if(running.15 && p < 13){
        ## select only the days inside the 3-months cluster series that belong only to the target month p:
        n.days.period <- length(pos.month.extended15(1,p))  # total number of days in the three months
        
        days.month <- days.month.new <- days.month.full <- c()
        days.month <- which(pos.month.extended15(1,p) == pos.month(1,p)[1]) - 1 + 1:length(pos.month(1,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)
            ##print(days.month.new)
            ##print(days.month)
        }

        ## select only the days of the cluster series inside the target month p:
        cluster.sequence <- my.cluster$cluster[days.month.full] 

    }

    if(!running.cluster && !running.15) cluster.sequence <- my.cluster$cluster
    
    ## convert cluster sequence from 6-hourly to daily:
    if(subdaily){
        type <- c()
        
        for(day in 1:(length(cluster.sequence)/4)){
                                        #day <- ceiling(hour/4)
            hourly <- cluster.sequence[(1+(day-1)*4):(4+(day-1)*4)]
            
            t1 <- length(which(hourly == 1))
            t2 <- length(which(hourly == 2))
            t3 <- length(which(hourly == 3))
            t4 <- length(which(hourly == 4))    
            tt <- c(t1,t2,t3,t4)
            
            ## if all the 4 time steps belong to the same regime, assign it to this day:
            if(length(unique(hourly)) == 1) type[day] <- hourly[1] 

            ## if there are two different regimes, check if one has a higher frequency:
            if(length(unique(hourly)) == 2){
                if(any(tt == 3)){  # if 3 of the 4 time intervals belong to the same weather regime, assign this day to it
                    type[day] <- which(tt == 3) 
                } else {  # in this case both regimes occur in 2 of the 4 time steps; arbitrary assign the regime occurring at 12.00 of that day
                    type[day] <- hourly[3]
                }
            }

            ## if there are three different regimes, assign it to the only possible regime with 2 time steps in that day:
            if(length(unique(hourly)) == 3)  type[day] <- which(tt == 2) 

            ## if there are four different regimes (a very rare event!), assign it to the regime occurring at 12.00 of that day:
            if(length(unique(hourly)) == 3)  type[day] <-  hourly[3]
            
        } # close for on day

    } # close for on subdaily
        
    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


    ## Replace the days belonging to a regime with the days belonging to a sequence of at least 5 days of that regime:
    wr1 <- which(cluster.sequence == 1)
    wr2 <- which(cluster.sequence == 2)
    wr3 <- which(cluster.sequence == 3)
    wr4 <- which(cluster.sequence == 4)
    
    ## yearly frequency of each regime:    
    wr1y <- wr2y <- wr3y <-wr4y <- c()

    mod.subdaily <- ifelse(subdaily,4,1)
    np <- n.days.in.a.period(p,1)*mod.subdaily

    for(y in year.start:year.end){
        ## for both reanalysis and S4, the time order is always: year1day1, year1day2, ..., year1day31, year2day1, year2day2, ..., year2day28, etc,
        wr1y[y-year.start+1] <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == 1))
        wr2y[y-year.start+1] <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == 2))
        wr3y[y-year.start+1] <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == 3))
        wr4y[y-year.start+1] <- length(which(cluster.sequence[(y-year.start)*np + (1:np)] == 4))
    }

    ## convert to frequencies in %:
    wr1y <- wr1y/np
    wr2y <- wr2y/np
    wr3y <- wr3y/np
    wr4y <- wr4y/np

    gc()

    cat("Extracting monthly regimes structure. Please wait...............\n")

    ## measure regime anomalies:        
    pslmat <- unname(acast(psl.melted, Year + Day ~ Lat ~ Lon))

    if(running.cluster || running.15){
        pslmat.new <- pslmat
        pslmat <- pslmat.new[days.month.full,,]
        rm(pslmat.new)
        gc()
    }

    
    pslwr1 <- pslmat[wr1,,, drop=F]
    pslwr2 <- pslmat[wr2,,, drop=F]
    pslwr3 <- pslmat[wr3,,, drop=F]
    pslwr4 <- pslmat[wr4,,, drop=F]

    ## regime structure:
    pslwr1mean <- apply(pslwr1, c(2,3), mean, na.rm=T)
    pslwr2mean <- apply(pslwr2, c(2,3), mean, na.rm=T)
    pslwr3mean <- apply(pslwr3, c(2,3), mean, na.rm=T)
    pslwr4mean <- apply(pslwr4, c(2,3), mean, na.rm=T)

    ## spatial mean for each day to save for the measure of the FairRPSS:
    pslwr1spmean <- apply(pslwr1, 1, mean, na.rm=T)
    pslwr2spmean <- apply(pslwr2, 1, mean, na.rm=T)
    pslwr3spmean <- apply(pslwr3, 1, mean, na.rm=T)
    pslwr4spmean <- apply(pslwr4, 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(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, pslwr1mean, pslwr2mean, pslwr3mean, pslwr4mean, pslwr1spmean, pslwr2spmean, pslwr3spmean, pslwr4spmean, wr1y,wr2y,wr3y,wr4y,wr1,wr2,wr3,wr4, LOESS, running.cluster, running.15, lat.weighting, file=paste0(workdir,"/",rean.name,"_",my.period[p],"_psl.RData"))
    
   
   # cat("Finished!\n")
} # close the for loop on 'p' 


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

################################################################################
#                         Measure impact maps                                  #
################################################################################
cat("Measuring impact. Please wait.....................\n")

# Load var data:
info.period <- period[1]  # period used to get the variables n.years, lat.min, lat.max, lon.min y lon.max
period.old <- period

vareuFull366 <-  Load(var = var.name[var.num], 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=1)$obs

vareuFull <-array(NA,c(1,1,n.years,365, dim(vareuFull366)[5], dim(vareuFull366)[6]))

## remove bisestile days to have all arrays with the same dimensions:
cat("Removing bisestile days. Please wait...\n")
vareuFull[,,,,,] <- vareuFull366[,,,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[,,y,61:366,,] # take the march to december period removing the 29th of February
}

rm(vareuFull366)
gc()

## convert psl in daily anomalies with the LOESS filter:
cat("Calculating anomalies. Please wait...\n")
varPeriodClim <- apply(vareuFull, c(1,2,4,5,6), mean, na.rm=T)

varPeriodClimLoess <- varPeriodClim
for(i in n.pos.lat){
    for(j in n.pos.lon){
        my.data <- data.frame(ens.mean=varPeriodClim[1,1,,i,j], day=1:365)
        my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
        varPeriodClimLoess[1,1,,i,j] <- predict(my.loess)
    }
}

rm(varPeriodClim)
gc()

varPeriodClim2 <- InsertDim(varPeriodClimLoess, 3, n.years)

vareuFull <- vareuFull - varPeriodClim2    
##rm(varPeriodClim2)
gc()

for(p in period){
    ##p=1 # for the debug

    ## load regime data for chosen month:
    varPeriod <- vareuFull[1,1,,pos.period(1,p),,] # select only var data during the chosen period
    varPeriodClim <- varPeriodClim2[1,1,,pos.period(1,p),,]
    varPeriodRel <- varPeriod / varPeriodClim
    
    load(file=paste0(workdir,"/",rean.name,"_",my.period[p],"_psl.RData"))
    
    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
    }
    
    wr1 <- which(cluster.sequence == 1)
    wr2 <- which(cluster.sequence == 2)
    wr3 <- which(cluster.sequence == 3)
    wr4 <- which(cluster.sequence == 4)
    
    gc()
    
    cat("Formatting var 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("Formatting var data. Please wait......\n")
    varmat <- unname(acast(var.melted, Year + Day ~ Lat ~ Lon))
    varmatRel <- unname(acast(var.meltedRel, Year + Day ~ Lat ~ Lon))

    varwr1 <- varmat[wr1,,,drop=F]
    varwr2 <- varmat[wr2,,,drop=F]
    varwr3 <- varmat[wr3,,,drop=F]
    varwr4 <- varmat[wr4,,,drop=F]

    varwr1Rel <- varmatRel[wr1,,,drop=F]
    varwr2Rel <- varmatRel[wr2,,,drop=F]
    varwr3Rel <- varmatRel[wr3,,,drop=F]
    varwr4Rel <- varmatRel[wr4,,,drop=F]
    
    
    varwr1mean <- apply(varwr1,c(2,3),mean,na.rm=T)
    varwr2mean <- apply(varwr2,c(2,3),mean,na.rm=T)
    varwr3mean <- apply(varwr3,c(2,3),mean,na.rm=T)
    varwr4mean <- apply(varwr4,c(2,3),mean,na.rm=T)

    varwr1meanRel <- apply(varwr1Rel,c(2,3),mean,na.rm=T)
    varwr2meanRel <- apply(varwr2Rel,c(2,3),mean,na.rm=T)
    varwr3meanRel <- apply(varwr3Rel,c(2,3),mean,na.rm=T)
    varwr4meanRel <- apply(varwr4Rel,c(2,3),mean,na.rm=T)
    
    n.datos <- n.years * n.days.in.a.period(p,2001)
    
    varwrBoth1 <- abind(varmat, varwr1, along = 1)
    pvalue1 <- apply(varwrBoth1, c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
    rm(varwrBoth1, varwr1)
    gc()

    varwrBoth2 <- abind(varmat, varwr2, along = 1)
    pvalue2 <- apply(varwrBoth2, c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
    rm(varwrBoth2, varwr2)
    gc()
    
    varwrBoth3 <- abind(varmat, varwr3, along = 1)
    pvalue3 <- apply(varwrBoth3, c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
    rm(varwrBoth3, varwr3)
    gc()
    
    varwrBoth4 <- abind(varmat, varwr4, along = 1)
    pvalue4 <- apply(varwrBoth4, c(2,3), function(x) t.test(x[1:n.datos],x[(n.datos+1):length(x)])$p.value)
    rm(varwrBoth4, varwr4)
    
    rm(varmat, varmatRel)
    gc()

    ## save all the data necessary to redraw the graphs when we know the right regime:
    save(varwr1mean, varwr2mean, varwr3mean,varwr4mean, pvalue1, pvalue2, pvalue3, pvalue4, varwr1meanRel, varwr2meanRel, varwr3meanRel,varwr4meanRel, file=paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],".RData"))
    
    rm(pvalue1,pvalue2,pvalue3,pvalue4)
    rm(varwr1mean,varwr2mean,varwr3mean,varwr4mean)
    gc()
    
} # close p on period

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

#######################################################################################################
#                                  Order clusters for explained variance                              #
#######################################################################################################

### order clusters for variance ( as in composition == "variance") and save them with '_ClusterNames' suffix:
cat("Ordening clusters for variance. Please wait........................\n")

ordering <- TRUE
save.names <- TRUE
as.pdf <- FALSE

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

    print(paste("p =",p))
    
    ## load regime data 
    impact.data <- FALSE

    load(file=paste0(workdir,"/",rean.name,"_",my.period[p],"_","psl",".RData"))
    
    ## load impact data only if it is available, if not it will leave an empty space in the composition:
    if(file.exists(paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],".RData"))){
        impact.data <- TRUE
        print(paste0("Impact data for variable ",var.name[var.num] ," available for reanalysis ", rean.name))
        
        load(file=paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],".RData"))
        
    } else {
        impact.data <- FALSE
        print(paste0("Impact data for variable ",var.name[var.num] ," not available for reanalysis ", rean.name))
    }

    
    my.cluster2 <- my.cluster # create a copy of my.cluster
    
    ss1 <- which(my.cluster$cluster == 1)
    ss2 <- which(my.cluster$cluster == 2)
    ss3 <- which(my.cluster$cluster == 3)
    ss4 <- which(my.cluster$cluster == 4)

    withinss <- my.cluster$withinss
    max1 <- which(my.cluster$withinss == max(withinss, na.rm=TRUE)) # first cluster with maximum variance
    withinss[max1] <- NA
    
    max2 <- which(my.cluster$withinss == max(withinss, na.rm=TRUE)) # second cluster with maximum variance
    withinss[max2] <- NA

    max3 <- which(my.cluster$withinss == max(withinss, na.rm=TRUE)) # third cluster with maximum variance
    withinss[max3] <- NA

    max4 <- which(!is.na(withinss)) 
    rm(withinss) 

    ## vector where the first element tells you which is the clister with the maximum variance the second element shows which is the cluster the
    ## second maximum variance, and so on:
    max.seq <- c(max1, max2, max3, max4) 
    
    assign(paste0("cluster",max1,".name"), orden[1]) # associate the cluster with the highest explained variance to the first regime to plot (usually NAO+)
    assign(paste0("cluster",max2,".name"), orden[2])
    assign(paste0("cluster",max3,".name"), orden[3])
    assign(paste0("cluster",max4,".name"), orden[4])

    save(cluster1.name, cluster2.name, cluster3.name, cluster4.name, file=paste0(workdir,"/",rean.name,"_", my.period[p],"_","ClusterNames",".RData"))

}

  
#########################################################################################
#                              Create maps                                              #
#########################################################################################

## Compute climatology and anomalies (with LOESS filter) for sfcWind data, and draw monthly anomalies, if you want to compare the mean daily wind speed anomalies reconstructed by the weather regimes classification with those observed by the reanalysis:

load(paste0(workdir,"/",rean.name,"_",my.period[period],"_psl.RData")) # only to load year.start and year.end

sfcWind366 <-  Load(var = "sfcWind", 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=1)$obs

sfcWind <- sfcWind366[,,,1:365,,]

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

rm(sfcWind366)
gc()

## LOESS anomalies:
sfcWindClimDaily <- apply(sfcWind, c(2,3,4), mean, na.rm=T)

sfcWindClimLoess <- sfcWindClimDaily
for(i in n.pos.lat){
    for(j in n.pos.lon){
        my.data <- data.frame(ens.mean=sfcWindClimDaily[,i,j], day=1:365)
        my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
        sfcWindClimLoess[,i,j] <- predict(my.loess)
    }
}

rm(sfcWindClimDaily)
gc()

sfcWindClim2 <- InsertDim(sfcWindClimLoess, 1, n.years)
sfcWindAnom <- sfcWind - sfcWindClim2
sfcWindAnomRel <- sfcWindAnom / sfcWindClim2

rm(sfcWindClimLoess)
rm(sfcWind)
gc()

## same as above but for computing climatology and anomalies (with LOESS filter) for psl data, and draw monthly slp anomalies:
slp366 <-  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=1)$obs

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()

slpClimDaily <- apply(slp, c(2,3,4), mean, na.rm=T)

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

rm(slpClimDaily)

gc()

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

rm(slpClimLoess)
rm(slp)
gc()

if(psl == "psl") slpAnom <- slpAnom/100   # convert MSLP in Pascal to MSLP in hPa

EU <- c(1:which(lon >= lon.max)[1], (which(lon >= 337)[1]:length(lon)))  # restrict area to continental europe only    

## color scale for impact maps:
## my.brks.var <- c(-20,seq(-3,3,0.5),20)
my.brks.var <- c(-20,seq(-0.6,0.6,0.1),20)
my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--white--red colors

## same but for slp:           
my.brks.var2 <- c(-100,seq(-21,-1,2),0,seq(1,21,2),100)
my.cols.var2 <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var2)-1)    # blue--red colors
my.cols.var2[floor(length(my.cols.var2)/2)] <- my.cols.var2[floor(length(my.cols.var2)/2)+1] <- "white"

## save all monthly anomaly maps:
for(year.test in year.end){
    for(month.test in period){
        ##year.test <- 2016; month.test <- 10 # for the debug
        
        pos.year.test <- year.test - year.start + 1

        ## wind anomaly for the chosen year and month:
        sfcWindAnomPeriod <- sfcWindAnom[pos.year.test, pos.period(1,month.test),,]
        sfcWindAnomPeriodRel <- sfcWindAnomRel[pos.year.test, pos.period(1,month.test),,]
        
        sfcWindAnomPeriodMean <- apply(sfcWindAnomPeriodRel, c(2,3), mean, na.rm=TRUE)

        ## psl anomaly for the chosen year and month:
        slpAnomPeriod <- slpAnom[pos.year.test,pos.period(1,month.test),,]
        
        slpAnomPeriodMean <- apply(slpAnomPeriod, c(2,3), mean, na.rm=TRUE)
        
        fileoutput <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_monthly_anomaly.png")
        
        png(filename=fileoutput,width=2800,height=1000)

        ## reset par to its default values, because drawing with PlotEquiMap() alters some par values:
        if(year.test == year.end && month.test == period) { op <- par(no.readonly = TRUE) }
        
        par(fig=c(0, 0.36, 0.08, 0.98), new=TRUE)
        
        PlotEquiMap(sfcWindAnomPeriodMean[,EU], lon[EU], 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)
        
        par(fig=c(0.03, 0.36, 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(0.34, 0.37, 0, 0.028), new=TRUE)
        mtext("%", cex=1.8)

        par(fig=c(0.37, 1, 0.1, 0.98), new=TRUE)

        PlotEquiMap2(slpAnomPeriodMean, lon, lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var2, brks2=my.brks.var2, cols=my.cols.var2, intxlon=10, intylat=10, drawleg=F, contours=t(slpAnomPeriodMean), contours.lty="F1FF1F", cex.lab=1)

        par(op) # reset par parameters
        par(fig=c(0.37, 1, 0, 0.1), new=TRUE)
        ##ColorBar2(my.brks.var2, cols=my.cols.var2, vert=FALSE, my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) #, subsampleg=1, label_scale=1.8) #, subset=my.subset2)
        ColorBar(brks=my.brks.var2[2:(l(my.brks.var2)-1)], cols=my.cols.var2[2:(l(my.cols.var2)-1)], vert=FALSE, label_scale=3, bar_limits=c(my.brks.var2[2],my.brks.var2[l(my.brks.var2)-1]), col_inf=my.cols.var2[1], col_sup=my.cols.var2[l(my.cols.var2)], subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)

        par(fig=c(0.96, 0.99, 0, 0.027), new=TRUE)
        mtext("hPa", cex=1.8)
        
        dev.off()

        ## same image formatted for the catalogue:
        fileoutput2 <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_monthly_anomaly_fig2cat.png")            

        system(paste0("~/scripts/fig2catalog.sh -s 0.8 -t '",rean.name," / 10m wind speed and sea level pressure / Monthly anomalies \n",month.name[month.test]," / ",year.test,"' -c 'Region: North Atlantic (27°N-81°N, 85.5°W-45°E)\nReference dataset: ",rean.name," reanalysis' ", fileoutput," ", fileoutput2))
        
        ## mean wind speed and slp anomaly only during days of the chosen year:
        load(paste0(workdir,"/",rean.name,"_",my.period[month.test],"_psl.RData")) # load cluster.sequence

        ## arrange the regime sequence in an array, to separate months from years:
        cluster2D <- array(cluster.sequence, c(n.days.in.a.period(month.test,1),n.years))
        ##cluster2D <- array(my.cluster$cluster, c(n.days.in.a.period(p,1),n.years)) # only for NCEP

        cluster.test <- cluster2D[,pos.year.test]

        fre1.days <- length(which(cluster.test == 1))
        fre2.days <- length(which(cluster.test == 2))
        fre3.days <- length(which(cluster.test == 3))
        fre4.days <- length(which(cluster.test == 4))

        ## wind anomaly for the chosen year and month and cluster:
        sfcWind1 <- sfcWindAnomPeriodRel[which(cluster.test == 1),,,drop=FALSE]
        sfcWind2 <- sfcWindAnomPeriodRel[which(cluster.test == 2),,,drop=FALSE]
        sfcWind3 <- sfcWindAnomPeriodRel[which(cluster.test == 3),,,drop=FALSE]
        sfcWind4 <- sfcWindAnomPeriodRel[which(cluster.test == 4),,,drop=FALSE]

        ## in case a regime has NO days in that month, we must set it to NA:
        if(length(which(cluster.test == 1)) == 0 ) sfcWind1 <- array(NA, c(1,dim(sfcWindAnomPeriod)[2:3]))
        if(length(which(cluster.test == 2)) == 0 ) sfcWind2 <- array(NA, c(1,dim(sfcWindAnomPeriod)[2:3]))
        if(length(which(cluster.test == 3)) == 0 ) sfcWind3 <- array(NA, c(1,dim(sfcWindAnomPeriod)[2:3]))
        if(length(which(cluster.test == 4)) == 0 ) sfcWind4 <- array(NA, c(1,dim(sfcWindAnomPeriod)[2:3]))

        sfcWindMean1 <- apply(sfcWind1, c(2,3), mean, na.rm=FALSE)
        sfcWindMean2 <- apply(sfcWind2, c(2,3), mean, na.rm=FALSE)
        sfcWindMean3 <- apply(sfcWind3, c(2,3), mean, na.rm=FALSE)
        sfcWindMean4 <- apply(sfcWind4, c(2,3), mean, na.rm=FALSE)

        ## load regime names:
        load(paste0(workdir,"/",rean.name,"_", my.period[p],"_","ClusterNames",".RData"))
        
        ## add strip with daily sequence of WRs:

        mod.name1 <- substr(cluster1.name, nchar(cluster1.name), nchar(cluster1.name))
        mod.name2 <- substr(cluster2.name, nchar(cluster2.name), nchar(cluster2.name))
        mod.name3 <- substr(cluster3.name, nchar(cluster3.name), nchar(cluster3.name))
        mod.name4 <- substr(cluster4.name, nchar(cluster4.name), nchar(cluster4.name))

        cluster1.name.short <- substr(cluster1.name,1,1)
        cluster2.name.short <- substr(cluster2.name,1,1)
        cluster3.name.short <- substr(cluster3.name,1,1)
        cluster4.name.short <- substr(cluster4.name,1,1)

        ## add + or - at the end of the cluster name, if it is a NAO+ or NAO- regime:
        if(mod.name1 == "+" || mod.name1 == "-") cluster1.name.short <- paste0(substr(cluster1.name,1,1), mod.name1)
        if(mod.name2 == "+" || mod.name2 == "-") cluster2.name.short <- paste0(substr(cluster2.name,1,1), mod.name2)
        if(mod.name3 == "+" || mod.name3 == "-") cluster3.name.short <- paste0(substr(cluster3.name,1,1), mod.name3)
        if(mod.name4 == "+" || mod.name4 == "-") cluster4.name.short <- paste0(substr(cluster4.name,1,1), mod.name4)
        
        c1 <- which(cluster.test == 1)
        c2 <- which(cluster.test == 2)
        c3 <- which(cluster.test == 3)
        c4 <- which(cluster.test == 4)

        cluster.test.letters <- cluster.test
        cluster.test.letters[c1] <- cluster1.name.short
        cluster.test.letters[c2] <- cluster2.name.short
        cluster.test.letters[c3] <- cluster3.name.short
        cluster.test.letters[c4] <- cluster4.name.short

        my.strip <- cluster.test.letters
        
        if(no.regimes) {
            cluster.test.letters2 <- cluster.test.letters
            cluster.test.letters2[which(cluster.test.letters == "N+")] <- "C1"
            cluster.test.letters2[which(cluster.test.letters == "N-")] <- "C2"
            cluster.test.letters2[which(cluster.test.letters == "B")] <- "C3"
            cluster.test.letters2[which(cluster.test.letters == "A")] <- "C4"
            my.strip <- cluster.test.letters2
        }

        cluster.col <- cluster.test.letters
        cluster.col[which(cluster.test.letters == "N+")] <- "Firebrick1"
        cluster.col[which(cluster.test.letters == "N-")] <- "Dodgerblue1"
        cluster.col[which(cluster.test.letters == "B")] <- "White"
        cluster.col[which(cluster.test.letters == "A")] <- "Darkgoldenrod1"

        cluster1 <- which(orden == cluster1.name)
        cluster2 <- which(orden == cluster2.name)
        cluster3 <- which(orden == cluster3.name)
        cluster4 <- which(orden == cluster4.name)

        assign(paste0("fre.days",cluster1), fre1.days)
        assign(paste0("fre.days",cluster2), fre2.days)
        assign(paste0("fre.days",cluster3), fre3.days)
        assign(paste0("fre.days",cluster4), fre4.days)

        assign(paste0("fre",cluster1), wr1y)
        assign(paste0("fre",cluster2), wr2y)
        assign(paste0("fre",cluster3), wr3y)
        assign(paste0("fre",cluster4), wr4y)
        
        assign(paste0("imp.test",cluster1), sfcWindMean1)
        assign(paste0("imp.test",cluster2), sfcWindMean2)
        assign(paste0("imp.test",cluster3), sfcWindMean3)
        assign(paste0("imp.test",cluster4), sfcWindMean4)
        
        ## psl anomaly for the chosen year and month and cluster:
        slp1 <- slpAnomPeriod[which(cluster.test == 1),,,drop=FALSE]
        slp2 <- slpAnomPeriod[which(cluster.test == 2),,,drop=FALSE]
        slp3 <- slpAnomPeriod[which(cluster.test == 3),,,drop=FALSE]
        slp4 <- slpAnomPeriod[which(cluster.test == 4),,,drop=FALSE]

        ## in case a regime has NO days in that month, we must set it to NA:
        if(length(which(cluster.test == 1)) == 0 ) slp1 <- array(NA, c(1,dim(slpAnomPeriod)[2:3]))
        if(length(which(cluster.test == 2)) == 0 ) slp2 <- array(NA, c(1,dim(slpAnomPeriod)[2:3]))
        if(length(which(cluster.test == 3)) == 0 ) slp3 <- array(NA, c(1,dim(slpAnomPeriod)[2:3]))
        if(length(which(cluster.test == 4)) == 0 ) slp4 <- array(NA, c(1,dim(slpAnomPeriod)[2:3]))
        
        slpMean1 <- apply(slp1, c(2,3), mean, na.rm=FALSE)
        slpMean2 <- apply(slp2, c(2,3), mean, na.rm=FALSE)
        slpMean3 <- apply(slp3, c(2,3), mean, na.rm=FALSE)
        slpMean4 <- apply(slp4, c(2,3), mean, na.rm=FALSE)

        assign(paste0("psl.test",cluster1), slpMean1)
        assign(paste0("psl.test",cluster2), slpMean2)
        assign(paste0("psl.test",cluster3), slpMean3)
        assign(paste0("psl.test",cluster4), slpMean4)
        
        ## save strip with the daily regime series for chosen month and year:
        fileoutput.seq <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_regimes_sequence.png")
        png(filename=fileoutput.seq,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()
        
        ## save average impact and sea level pressure only for chosen month and year:
        fileoutput.test <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_monthly_anomaly_regimes.png")
        
        png(filename=fileoutput.test,width=1500,height=2000)
        
        plot.new()
        
        par(fig=c(0, 0.33, 0.77, 0.97), new=TRUE)
        PlotEquiMap2(imp.test1[,EU], lon[EU], lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var, cols=my.cols.var, cex.lab=1.2, intxlon=10, intylat=10, drawleg=F)
        par(fig=c(0, 0.33, 0.54, 0.74), new=TRUE)
        PlotEquiMap2(imp.test2[,EU], lon[EU], lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var, cols=my.cols.var, cex.lab=1.2, intxlon=10, intylat=10, drawleg=F)
        par(fig=c(0, 0.33, 0.31, 0.51), new=TRUE)
        PlotEquiMap2(imp.test3[,EU], lon[EU], lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var, cols=my.cols.var, cex.lab=1.2, intxlon=10, intylat=10, drawleg=F)
        par(fig=c(0, 0.33, 0.08, 0.28), new=TRUE)
        PlotEquiMap2(imp.test4[,EU], lon[EU], lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var, cols=my.cols.var, cex.lab=1.2, intxlon=10, intylat=10, drawleg=F)

        if(no.regimes) { regime.title <- paste0("Cluster",1:4)} else { regime.title <- orden}
        
        par(fig=c(0,0.33,0.955,0.975), new=TRUE)
        mtext(paste0(regime.title[1], " wind speed anomaly "), font=2, cex=2)
        par(fig=c(0,0.33,0.725,0.745), new=TRUE)
        mtext(paste0(regime.title[2], " wind speed anomaly "), font=2, cex=2)
        par(fig=c(0,0.33,0.495,0.515), new=TRUE)
        mtext(paste0(regime.title[3], " wind speed anomaly "), font=2, cex=2)
        par(fig=c(0,0.33,0.265,0.285), new=TRUE)
        mtext(paste0(regime.title[4], " wind speed anomaly "), font=2, cex=2)
        
        par(fig=c(0.03, 0.33, 0.015, 0.06), 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)

        par(fig=c(0.33, 0.34, 0.01, 0.044), new=TRUE)
        mtext("%", cex=1.6)

        ## right figures:             
        par(fig=c(0.34, 0.92, 0.77, 0.97), new=TRUE)
        PlotEquiMap2(psl.test1, lon, lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var2, brks2=my.brks.var2, cols=my.cols.var2, intxlon=10, intylat=10, drawleg=F, contours=t(psl.test1), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=.5)
        par(fig=c(0.34, 0.92, 0.54, 0.74), new=TRUE)
        PlotEquiMap2(psl.test2, lon, lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var2, brks2=my.brks.var2, cols=my.cols.var2, intxlon=10, intylat=10, drawleg=F, contours=t(psl.test2), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=.5)
        par(fig=c(0.34, 0.92, 0.31, 0.51), new=TRUE)
        PlotEquiMap2(psl.test3, lon, lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var2, brks2=my.brks.var2, cols=my.cols.var2, intxlon=10, intylat=10, drawleg=F, contours=t(psl.test3), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=.5)
        par(fig=c(0.34, 0.92, 0.08, 0.28), new=TRUE)
        PlotEquiMap2(psl.test4, lon, lat, filled.continents=FALSE, continents.col="black", brks=my.brks.var2, brks2=my.brks.var2, cols=my.cols.var2, intxlon=10, intylat=10, drawleg=F, contours=t(psl.test4), contours.lty="F1FF1F", cex.lab=1, xlabel.dist=.5)

        par(fig=c(0.34,0.92,0.955,0.975), new=TRUE)
        mtext(paste0(regime.title[1], " SLP anomaly "), font=2, cex=2)
        par(fig=c(0.34,0.92,0.725,0.745), new=TRUE)
        mtext(paste0(regime.title[2], " SLP anomaly "), font=2, cex=2)
        par(fig=c(0.34,0.92,0.495,0.515), new=TRUE)
        mtext(paste0(regime.title[3], " SLP anomaly "), font=2, cex=2)
        par(fig=c(0.34,0.92,0.265,0.285), new=TRUE)
        mtext(paste0(regime.title[4], " SLP anomaly "), font=2, cex=2)
        
        par(fig=c(0.34, 0.93, 0.015, 0.06), new=TRUE)
        ##ColorBar2(my.brks.var2, cols=my.cols.var2, vert=FALSE, my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) #, subsampleg=1, label_scale=1.8) #, subset=my.subset2)
        ColorBar(my.brks.var2[2:(length(my.brks.var2)-1)], cols=my.cols.var2[2:(length(my.cols.var2)-1)], vert=FALSE, label_scale=2, bar_limits=c(my.brks.var2[2],my.brks.var2[l(my.brks.var2)-1]), col_inf=my.cols.var2[1], col_sup=my.cols.var2[l(my.cols.var2)], subsample=1)

        par(fig=c(0.924, 0.930, 0.01, 0.044), new=TRUE)
        mtext("hPa", cex=1.6)
        
        ##par(fig=c(0.627, 0.647, 0, 0.028), new=TRUE)
        ##mtext("0", cex=1.8)

        n.days <- floor(n.days.in.a.period(month.test,1))
        
        par(fig=c(0.93, 0.99, 0.77, 0.87), new=TRUE)
        mtext(paste0(fre.days1," days\n(",round(100*fre.days1/n.days,1),"%)"), cex=2.8)
        par(fig=c(0.93, 0.99, 0.54, 0.64), new=TRUE)
        mtext(paste0(fre.days2," days\n(",round(100*fre.days2/n.days,1),"%)"), cex=2.8)
        par(fig=c(0.93, 0.99, 0.31, 0.41), new=TRUE)
        mtext(paste0(fre.days3," days\n(",round(100*fre.days3/n.days,1),"%)"), cex=2.8)
        par(fig=c(0.93, 0.99, 0.08, 0.18), new=TRUE)
        mtext(paste0(fre.days4," days\n(",round(100*fre.days4/n.days,1),"%)"), cex=2.8)

        dev.off()

        ## add the strip with the regime sequence over the average impact composition:
        fileoutput.temp <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_temp.png")
        fileoutput.both <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_temp2.png")

        system(paste0("convert ",fileoutput.seq," -crop +0-1730 +repage ",fileoutput.temp)) # cut the lower part of the strip
        system(paste0("montage ",fileoutput.temp," ",fileoutput.test," -tile 1x2 -geometry +0+0 ",fileoutput.both))


        ## same image formatted for the catalogue:
        fileoutput2.test <- paste0(workdir,"/",rean.name,"_",my.period[month.test],"_monthly_anomaly_regimes_fig2cat.png")            

        system(paste0("~/scripts/fig2catalog.sh -s 0.8 -m 20 -r 40 -t '",rean.name," / 10m wind speed and sea level pressure / Monthly anomalies \n",month.name[month.test]," / ",year.test,"' -c 'Region: North Atlantic (27°N-81°N, 85.5°W-45°E)\nReference dataset: ",rean.name," reanalysis' ", fileoutput.both," ", fileoutput2.test))

        system(paste0("rm ", fileoutput.temp, " ", fileoutput.both," ", fileoutput.seq," ", fileoutput.test, " ", fileoutput))
        
        
    } # close for on year.test
} # close for on month.test


####################################################################################
#                   Create weather regimes maps for last 37 years                  #
####################################################################################

composition <- "edpr"
ordering <- TRUE    # If TRUE, order the clusters following the regimes listed in the 'orden' vector (set it to TRUE only after you manually inserted the names below).
save.names <- FALSE  # if TRUE, also save the cluster names (i.e: the association between clusters and weather regimes); if FALSE, the cluster names are loaded from a file
as.pdf <- FALSE      # FALSE: save results as one .png file for each season/month, TRUE: save only one .pdf file with all seasons/months
mean.freq <- TRUE   # if TRUE, when composition <- "simple" o 'edpr', it also add the mean frequency value over each frequency plot

for(p in period){
    print(paste("p =",p))
    
    ## load regime data (for forecasts, it load only the data corresponding to the chosen start month p and lead month 'lead.month')
    impact.data <- FALSE
    
    load(file=paste0(workdir,"/",rean.name,"_",my.period[p],"_","psl",".RData"))


    ## load impact data only if it is available, if not it will leave an empty space in the composition:
    if(file.exists(paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],".RData"))){
        impact.data <- TRUE
        print(paste0("Impact data for variable ",var.name[var.num] ," available for reanalysis ", rean.name))
        load(file=paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],".RData"))
    } else {
        impact.data <- FALSE
        print(paste0("Impact data for variable ",var.name[var.num] ," not available for reanalysis ", rean.name))
    }

    
    ## load the cluster names from the file already saved, if regimes come from a reanalysis:
    ClusterName.file <- paste0(workdir,"/",rean.name,"_", 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 
    
    ## assign to each cluster its regime:
    if(ordering == FALSE){
        cluster1 <- 1; cluster2 <- 2; cluster3 <- 3; cluster4 <- 4 # same as: cluster1.name=orden[1], cluster2.name=orden[2], cluster3.name=orden[3], etc.
    } else {
        cluster1 <- which(orden == cluster1.name)
        cluster2 <- which(orden == cluster2.name)
        cluster3 <- which(orden == cluster3.name)
        cluster4 <- which(orden == cluster4.name)
    }
    
    assign(paste0("map",cluster1), pslwr1mean)
    assign(paste0("map",cluster2), pslwr2mean)
    assign(paste0("map",cluster3), pslwr3mean)
    assign(paste0("map",cluster4), pslwr4mean)

    assign(paste0("fre",cluster1), wr1y)
    assign(paste0("fre",cluster2), wr2y)
    assign(paste0("fre",cluster3), wr3y)
    assign(paste0("fre",cluster4), wr4y)
    
    if(impact.data == TRUE){
        assign(paste0("imp",cluster1), varwr1mean)
        assign(paste0("imp",cluster2), varwr2mean)
        assign(paste0("imp",cluster3), varwr3mean)
        assign(paste0("imp",cluster4), varwr4mean)
        
        assign(paste0("sig",cluster1), pvalue1)
        assign(paste0("sig",cluster2), pvalue2)
        assign(paste0("sig",cluster3), pvalue3)
        assign(paste0("sig",cluster4), pvalue4)

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

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

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

    my.cols <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks)-1)    # blue--red colors
    my.cols[floor(length(my.cols)/2)] <- my.cols[floor(length(my.cols)/2)+1] <- "white" # add white in the middle
    
    if(var.name[var.num] == "sfcWind") {
        my.brks.var <- seq(-3,3,0.5)
        values.to.plot2 <- c(-3,-2,-1,0,1,2,3)
    }
    if(var.name[var.num] == "tas") {
        my.brks.var <- seq(-5,5,1) 
        values.to.plot2 <- my.brks.var #c(-5,-3,-1,0,1,3,5)
    }
    
    ##my.cols <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks)-1)  # blue--yellow-red colors
    my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--white--red colors
    ##my.cols.var[floor(length(my.cols.var)/2)] <- my.cols.var[floor(length(my.cols.var)/2)+1] <- "white"

    freq.max <- 100
    fre1.NA <- fre1; fre2.NA <- fre2; fre3.NA <- fre3; fre4.NA <- fre4
    
    ## adjust color legends to include triangles to the extremities increasing by two the number of intervals:
    my.brks.var <- c(-20,seq(-0.6,0.6,0.1),20)
    my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--red colors
    
    ## same but for SLP:
    my.brks <- c(-100,seq(-21,-1,2),0,seq(1,21,2),100)
    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" ## add white in the middle
    
    fileoutput <- paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],"_edpr.png")
    
    png(filename=fileoutput,width=3000,height=3700)
    
    plot.new()

    y1 <- 0.10
    y3 <- 0.315
    y5 <- 0.53
    y7 <- 0.745
    y.width <- 0.18
    
    y2 <- y1 + y.width; y4 <- y3 + y.width; y6 <- y5 + y.width; y8 <- y7 + y.width
    yt1 <- y2+0.003; yt3 <- y4+0.003; yt5 <- y6+0.003; yt7 <- y8+0.003
    yt2 <- yt1 + 0.004; yt4 <- yt3 + 0.005; yt6 <- yt5 + 0.005; yt8 <- yt7 + 0.005
    
    ## Centroid maps:
    map.xpos <- 0.27
    map.width <- 0.46
    par(fig=c(map.xpos + 0.003, map.xpos + map.width - 0.003, y7, y8), new=TRUE)
    PlotEquiMap2(map1, lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map1), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, xlabel.dist=1.5, contours.lty="F1FF1F", continents.col="black")
    
    par(fig=c(map.xpos, map.xpos + map.width, y5, y6), new=TRUE)
    PlotEquiMap2(map2, lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map2), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F", continents.col="black")
    
    par(fig=c(map.xpos, map.xpos + map.width, y3, y4), new=TRUE)
    PlotEquiMap2(map3, lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map3), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F", continents.col="black")
    
    par(fig=c(map.xpos, map.xpos + map.width, y1, y2), new=TRUE)
    PlotEquiMap2(map4, lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map4), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F", continents.col="black")
    
    ## Legend centroid maps:
    legend1.xpos <- 0.30
    legend1.width <- 0.40
    legend1.cex <- 3
    my.subset <- match(values.to.plot, my.brks)    
    par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.045, 0.085), new=TRUE)
    ##ColorBar3(my.brks, cols=my.cols[2:(length(my.cols)-1)], vert=FALSE, cex=legend1.cex, subset=my.subset)
    ColorBar(my.brks[2:(l(my.brks)-1)], cols=my.cols[2:(length(my.cols)-1)], vert=FALSE, label_scale=legend1.cex, 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)

    if(psl=="g500") {mtext(side=4," m", cex=2.5, las=1)} else {mtext(side=4," hPa", cex=legend1.cex, las=1)} ## las=1 is to display in horizontal instead of vert

    ## Title Centroid Maps:
    title1.xpos <- 0.3
    title1.width <- 0.44
    par(fig=c(title1.xpos, title1.xpos + title1.width, yt7+0.0025, yt7+0.0075), new=TRUE)
    mtext(paste0(regime.title[1]," ", psl.name, " anomaly"), font=2, cex=4)
    
    par(fig=c(title1.xpos, title1.xpos + title1.width, yt5+0.0025, yt5+0.0075), new=TRUE)
    mtext(paste0(regime.title[2]," ", psl.name, " anomaly"), font=2, cex=4)
    
    par(fig=c(title1.xpos, title1.xpos + title1.width, yt3+0.0025, yt3+0.0075), new=TRUE)
    mtext(paste0(regime.title[3]," ", psl.name, " anomaly"), font=2, cex=4)
    
    par(fig=c(title1.xpos, title1.xpos + title1.width, yt1+0.0025, yt1+0.0075), new=TRUE)
    mtext(paste0(regime.title[4]," ", psl.name, " anomaly"), font=2, cex=4)
    
    ## Impact maps:
    if(impact.data == TRUE ){ 
        impact.xpos <- 0
        impact.width <- 0.26    
        par(fig=c(impact.xpos, impact.xpos + impact.width, y7, y8), new=TRUE)
        PlotEquiMap2(impRel1[,EU], lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig1[,EU] < 0.05), cex.lab=1.5, continents.col="black")
        
        par(fig=c(impact.xpos, impact.xpos + impact.width, y5, y6), new=TRUE)
        PlotEquiMap2(impRel2[,EU], lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig2[,EU] < 0.05), cex.lab=1.5, continents.col="black")
        
        par(fig=c(impact.xpos, impact.xpos + impact.width, y3, y4), new=TRUE)
        PlotEquiMap2(impRel3[,EU], lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig3[,EU] < 0.05), cex.lab=1.5, continents.col="black")
        
        par(fig=c(impact.xpos, impact.xpos + impact.width, y1, y2), new=TRUE)
        PlotEquiMap2(impRel4[,EU], lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig4[,EU] < 0.05), cex.lab=1.5, continents.col="black")

        
        ## Title impact maps:
        title2.xpos <- 0
        title2.width <- 0.26
        par(fig=c(title2.xpos, title2.xpos + title2.width, yt7, yt8), new=TRUE)
        mtext(paste0(regime.title[1], " impact on ", var.name.full[var.num]), font=2, cex=4)
        
        par(fig=c(title2.xpos, title2.xpos + title2.width, yt5, yt6), new=TRUE)
        mtext(paste0(regime.title[2], " impact on ", var.name.full[var.num]), font=2, cex=4)
        
        par(fig=c(title2.xpos, title2.xpos + title2.width, yt3, yt4), new=TRUE)
        mtext(paste0(regime.title[3], " impact on ", var.name.full[var.num]), font=2, cex=4)
        
        par(fig=c(title2.xpos, title2.xpos + title2.width, yt1, yt2), new=TRUE)
        mtext(paste0(regime.title[4], " impact on ", var.name.full[var.num]), font=2, cex=4)

        ## Legend:
        legend2.xpos <- 0.01
        legend2.width <- 0.25
        legend2.cex <- 3
        
        my.subset2 <- match(values.to.plot2, my.brks.var)
        par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.045, 0.085), new=TRUE)
        
        ColorBar(brks=round(100*my.brks.var[2:(l(my.brks.var)-1)],0), cols=my.cols.var[2:(length(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)
        ##mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex, las=1)  
        mtext(side=4,"%", cex=legend2.cex, las=1)  

    }
    
    ## Frequency plots:
    barplot.xpos <- 0.75
    barplot.width <- 0.25

    par(fig=c(barplot.xpos, barplot.xpos + barplot.width, y7, y8-0.01), new=TRUE)
    barplot.freq(100*fre1.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width, y5, y6-0.01), new=TRUE)
    barplot.freq(100*fre2.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width, y3, y4-0.01), new=TRUE)
    barplot.freq(100*fre3.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width, y1, y2-0.01), new=TRUE)
    barplot.freq(100*fre4.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    
    ## Title Frequency maps:
    title3.xpos <- 0.75
    title3.width <-0.25
    par(fig=c(title3.xpos, title3.xpos + title3.width, yt7, yt8), new=TRUE)
    mtext(paste0(regime.title[1], " Frequency"), font=2, cex=4) # paste0 doesn't work inside an expression!
    par(fig=c(title3.xpos, title3.xpos + title3.width, yt5, yt6), new=TRUE)
    mtext(paste0(regime.title[2], " Frequency"), font=2, cex=4)
    par(fig=c(title3.xpos, title3.xpos + title3.width, yt3, yt4), new=TRUE)
    mtext(paste0(regime.title[3], " Frequency"), font=2, cex=4)
    par(fig=c(title3.xpos, title3.xpos + title3.width, yt1, yt2), new=TRUE)
    mtext(paste0(regime.title[4], " Frequency"), font=2, cex=4)

    ## % on Frequency plots:
    symbol.xpos <- 0.735
    symbol.width <- 0.01
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y4+0.425, y4+0.425+0.01), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y3+0.39, y3+0.39+0.01), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y2+0.21, y2+0.21+0.01), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y1+0.17, y1+0.17+0.01), new=TRUE)
    mtext("%", cex=3.3)

    ## mean frequency on Frequency plots:
    if(mean.freq == TRUE){
        symbol.xpos <- 0.83
        symbol.width <- 0.1
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y7+0.163, y7+0.163+0.01), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre1.NA),1),"%"))),cex=3.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y5+0.163, y5+0.163+0.01), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre2.NA),1),"%"))),cex=3.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y3+0.165, y3+0.165+0.01), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre3.NA),1),"%"))),cex=3.5)
        par(fig=c(symbol.xpos, symbol.xpos + symbol.width, y1+0.163, y1+0.163+0.01), new=TRUE)
        mtext(bquote(bar(nu) == .(paste0(round(mean(100*fre4.NA),1),"%"))),cex=3.5)
    }


    ## Subtitle frequency maps:
    map.title.xpos <- 0.96
    map.title.width <- 0.04
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, y7-0.013, y7-0.013+0.001), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, y5-0.013, y5-0.013+0.001), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, y3-0.013, y3-0.013+0.001), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, y1-0.013, y1-0.013+0.001), new=TRUE)
    mtext("year", cex=3)

    if(!as.pdf) dev.off() # for saving 4 png
    
    ## same image formatted for the catalogue:
    fileoutput2 <- paste0(workdir,"/",rean.name,"_",my.period[p],"_",var.name[var.num],"_edpr_fig2cat.png")            

    system(paste0("~/scripts/fig2catalog.sh -s 0.8 -r 150 -m 150 -t '",rean.name," / 10m wind speed and sea level pressure / Monthly anomalies and frequencies \n",month.name[p]," / ",year.start,"-",year.end,"' -c 'Region: North Atlantic (27°N-81°N, 85.5°W-45°E)\nReference dataset: ",rean.name," reanalysis' ", fileoutput," ", fileoutput2))

    system(paste0("rm ", fileoutput))
    
} # close 'p' on 'period'

print("Finished!")
