###########################################################################################
#                  Visualize and save the score maps for one score and period             #
###########################################################################################
# run it only after computing and saving all the skill score data:

rm(list=ls())

##########################################################################################
#                            Load functions and libraries                                #
##########################################################################################

library(SpecsVerification) # for skill scores
library(s2dverification)   # for Load() function
library(abind)             # for merging arrays
source('/home/Earth/ncortesi/scripts/Rfunctions.R')
source('/home/Earth/ncortesi/Downloads/ESS/general/hatching.R')
##########################################################################################
#                                     User's settings                                    #
##########################################################################################
#if(!mare) {source('/home/Earth/ncortesi/Downloads/scripts/Rfunctions.R')} else {source('/gpfs/projects/bsc32/bsc32842/scripts/Rfunctions.R')}

# working dir where to put the output maps and files in the /Data and /Maps subdirs:
work.dir <- "/scratch/Earth/ncortesi/RESILIENCE/Subestacional"

var.name <- 'sfcWind'                    # forecast variable. It is the name used inside the netCDF files and as suffix in map filenames, i.e: 'sfcWind' or 'psl'

my.pvalue <- 0.05          # in case of computing the EnsCorr, set the p_value level to show in the ensemble mean correlation maps
n.intervals <- 12          # in case of computing the Reliabilty Diagram, set the number of intervals of the forecasted frequency (X axis). It is convenient to set it to
                           # the number of ensemble member + 1

# Choose one or more regions between those defined below for the reliability diagrams and for the summary tables (0=World, 1=Northern europe, etc.)
areas <- 1:9
    
land.only <- FALSE  # set it to true if you want to average only over land, FALSE otherwise [warning: the reliability diagram is computed ONLY over land+sea ]

# coordinates of a chosen point in the world to plot the time series over the 52 maps (they must be the same values in objects la y lo)
#my.lat <- 55.3197120 
#my.lon <- 0.5625

my.months=1:12 #9:12  # choose the month(s) to plot and save

# Define regions for averaging skill scores: (in the format: lon.min /lon.max / lat.min /lat.max. lon.min MUST be a NEGATIVE number, long values MUST be from 0 and 360, and
# lat values MUST be from 90 to -90 degrees)
area0.name <- "World"
area0 <- c(-180,180,-90,90)
area1.name <- "Northern_Europe"
area1 <- c(-15,45,45,75)
area2.name <- "Southern_Europe"
area2 <- c(-15,45,35,45)
area3.name <- "Southwestern_Europe"
area3 <- c(-15,20,35,45)
area4.name <- "Southeastern_Europe"
area4 <- c(20,45,35,45)
area5.name <- "Europe"
area5 <- c(-15,45,35,75)
area6.name <- "North_America"
area6 <- c(-130,-60,30,50)
area7.name <- "North_Sea"
area7 <- c(-4, 15, 50, 65)
area8.name <- "Iberian_Peninsula"
area8 <- c(-10, 4, 36, 44)
area9.name <- "Canadian region"
area9 <- c(-114, -111.8, 49.6, 51.7)

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

col <- c("#0C046E", "#1914BE", "#2341F7", "#2F55FB", "#3E64FF", "#528CFF", "#64AAFF", "#82C8FF", "#A0DCFF", "#B4F0FF", "#FFFBAF", "#FFDD9A", "#FFBF87", "#FFA173", "#FF7055", "#FE6346", "#F7403B", "#E92D36", "#C80F1E", "#A50519")

# line color of Reliability Diagram summaries:
col.month <- c('#e41a1c','#e41a1c','#e41a1c','#377eb8','#377eb8','#377eb8','#4daf4a','#4daf4a','#4daf4a','#984ea3','#984ea3','#984ea3')
                
dir.create(path=paste0(work.dir,"/",var.name), showWarnings=FALSE) # if directory already exists, this function doesn't create it again
dir.create(path=paste0(work.dir,"/",var.name,"/formatted"), showWarnings=FALSE) # if directory already exists, this function doesn't create it again

##########################################################################################
#                 visualize worldwide monthly maps of skill scores                       #
##########################################################################################
# choose one or more skills scores to visualize between ACC (EnsCorr), FairRPSS, FairCRPSS and/or RelDiagr:
my.score.name <- c('FairRpss','FairCrpss','EnsCorr','RelDiagr')
my.score.name.title <-  c('FairRpss','FairCrpss','Correlation of the ensemble mean','Reliability Diagram') # names to be visualized in the graph titles  

for(area.num in areas){
    ## replace old command area.name <- area0.name:
    area <- eval(parse(text=paste0("area", area.num)))
    area.name <- eval(parse(text=paste0("area", area.num,".name")))
    
    print(paste0("Area: ",area.name))
    
    ## position of max and min long and lat values the chosen region:
    lon.min <- 360 + area[1]
    lon.max <- area[2]
    lat.min <- area[3]
    lat.max <- area[4]

    for(month in my.months){
        ## month=1  # for the debug
        print(paste0("Month=",month))

        ## Load data:
        load(file=paste0(work.dir,'/',var.name,'_',my.month[month],'.RData'))

        sdates.seq <- weekly.seq(forecast.year,mes,day)  # sequence of dates corresponding to all the thursday of the year
        my.startdates.days <- as.integer(substr(sdates.seq[which(as.integer(substr(sdates.seq,5,6)) == month)],7,8)) #startdates.monthly[[month]] #c(1:5)
        stringa <- paste0(my.startdates.days,collapse=",")

        if(lon.min < 360) area.lon <- c(1:(which(lons >= lon.max)[1]), (which(lons >= lon.min)[1]:length(lons)))  # restrict area to chosen one
        if(lon.min > 360) area.lon <- (which(lons >= lon.min-360)[1]):(which(lons >= lon.max)[1]-1)

        ##if(area.name != "World") area.lat <- c(which(lats <= lat.max)[1]:(which(lats <= lat.min)[1]-1))  # restrict area to chosen one
        ##if(area.name == "World"){ area.lat <- 1:length(lats); area.lon <- 1:length(lons) }

        area.lat <- 1:length(lats)
        area.lon <- 1:length(lons)
        
        n.lonr <- n.lon - ceiling(length(lons[lons>0 & lons < 180])) # count the number of longitude values between 180 and 360 degrees longitud
        
        for(my.score.name.map in my.score.name){
            ##my.score.name.map='Acc'  # for the debug

            print(paste0("Score=",my.score.name.map))

            if(my.score.name.map=='FairRpss') my.score <- my.FairRpss.chunk
            if(my.score.name.map=='FairCrpss') my.score <- my.FairCrpss.chunk
            if(my.score.name.map=="EnsCorr") my.score <- my.EnsCorr.chunk
            ##if(my.score.name.map=="RelDiagr") my.score <- my.RelDiagr

            ## old green-red palette:
            ## brk.rpss<-c(-1,seq(0,1,by=0.05))
            ## col.rpss<-c("darkred",colorRampPalette(c("red","white","darkgreen"))(length(brk.rpss)-2))
            ## brk.rps<-c(seq(0,1,by=0.1),10)
            ## col.rps<-c(colorRampPalette(c("darkgreen","white","red"))(length(brk.rps)-2),"darkred")
            ## if(my.score.name.map==my.Rps | my.score==my.Rps.clim) {my.brk<-brk.rps} else {my.brk<-brk.rpss}
            ## if(my.score.name.map==my.Rps | my.score==my.Rps.clim) {my.col<-col.rps} else {my.col<-col.rpss}

            brk.rpss <- c(seq(-1,1,by=0.1))
            col.rpss <- colorRampPalette(col)(length(brk.rpss)-1)

            ## at present all breaks and colors are the same, so there is no need to differenciate between indexes, aside the two Fair scores whose range is [-inf,0]
            my.brk <- brk.rpss 
            my.col <- col.rpss
            my.brk.labels <- my.brk
            if(my.score.name.map == 'FairRpss' | my.score.name.map=='FairCrpss') my.brk.labels <- c(expression(-infinity), my.brk[-1])
            
            my.RelDiagr<-list()

            for(lead in 1:n.leadtimes){
                print(paste0("Leadtime=",lead))

                ##my.title<-paste0(my.score.name.map,' of ',cfs.name,' 
                ##10m Wind Speed for ',startdate.name.map,'. Forecast time ',leadtime.week[lead],'.') 

                if(my.score.name.map != "RelDiagr" && area.name == "World"){

                    ##postscript(file=paste0(workdir,'/Maps_',var.name,'/',my.score.name.map,'_',startdate.name.map,'_Forecast_time_',leadtime.week[lead],'_',var.name,'.ps'),
                    ##           paper="special",width=12,height=7,horizontal=F)

                    ##layout(matrix(c(1,2), 1, 2, byrow = TRUE),widths=c(11,1.5))
                    ##par(oma=c(0,0,4,0),mar=c(0,0,0,0))

                    ##n.lonr <- n.lon - ceiling(length(lons[lons<180 & lons > 0]))
                    ##hatching(latsr,c(lons[c((nlonr+1):nlon)]-360,lons[1:nlonr]), my.Pvalue.rev, dens = 12, ang = 45, col_line = '#252525', lwd_size = 0.5, crosshatching = FALSE)
                    ##hatching(lats,c(lons[c((n.lonr+1):n.lon)]-360,lons[1:n.lonr]), my.Pvalue.rev, dens = 12, ang = 45, col_line = '#252525', lwd_size = 0.5, crosshatching = FALSE)
                    ##n.lonr <- n.lon - ceiling(length(lons[lons<180 & lons > 0])) 
                    ##PlotEquiMap(my.score[lead,,][n.lat:1,c((n.lonr+1):n.lon,1:n.lonr)], lons,lats ,title_scale=0.8, brks=my.brk, cols=my.col ,axelab=F, filled.continents=FALSE, drawleg=F)
                    ## lat values must be in decreasing order from +90 to -90 degrees and long from 0 to 360 degrees:

                    my.file <- paste0(work.dir,'/',var.name,'/',var.name,'_',my.score.name.map,'_',my.month[month],'_leadtime_',leadtime.week[lead],'.png')
                    my.file2 <-  paste0(work.dir,'/',var.name,'/formatted/',var.name,'_',my.score.name.map,'_',my.month[month],'_leadtime_',leadtime.week[lead],'.png')
                    png(file=my.file,width=1000,height=600)

                    ## Map:
                    par(fig=c(0,0.92,0,0.89), new=TRUE)
                    
                    PlotEquiMap(my.score[lead,,c((n.lonr+1):n.lon,1:n.lonr)], c(lons[c((n.lonr+1):n.lon)]-360, lons[1:n.lonr]), lats ,title_scale=0.8, brks=my.brk, cols=my.col ,axelab=F, filled.continents=FALSE, drawleg=F)
                    
                    if(my.score.name.map=="EnsCorr") my.PValue.rev <- my.EnsCorr.pvalue < 0.05
                    if(my.score.name.map=="FairRpss") my.PValue.rev <- my.FairRpss.pvalue < 0.05
                    if(my.score.name.map=="FairCrpss") my.PValue.rev <- my.FairCrpss.pvalue < 0.05
                    
                    ## Draw the significance diagonal lines:
                    pv <- aperm(my.PValue.rev, c(1,3,2))
                    
                    hatching(lats, c(lons[c((n.lonr+1):n.lon)]-360, lons[1:n.lonr]), pv[lead,,], dens = 12, ang = 45, col_line = '#252525', lwd_size = 0.5, crosshatching = FALSE)

                    ## Map title:
                    par(fig=c(0,1,0.82,0.91), new=TRUE)
                    ##my.title <- paste0(my.score.name.map,' of ',cfs.name,'\n ', var.name.map,' for ',my.month[month],'. Forecast time ',leadtime.week[lead],'.')
                    my.title <- paste0("ECMWF-MPS / ", var.name.map, " / ", my.score.name.title[which(my.score.name == my.score.name.map)], "\n", my.month[month], " (",leadtime.week[lead]," days lead time)/ 1994-2013")
                    mtext(my.title, cex=2.4, font=2)

                    ## Color legend:
                    par(fig=c(0.92,1,0,0.9), new=TRUE)
                    ##par(fig=c(0.52,0.82,0,0.9), new=TRUE)

                    ColorBar2(my.brk, cols=my.col, vert=T, my.ticks=-0.5 + 1:length(my.brk), my.labels=my.brk.labels)
                    
                    ## arrange lat/ lon in my.PValue (a second variable in the EnsCorr file) to start from +90 degr. (lat) and from 0 degr (lon):
                    ## my.PValue.rev[lead,,] <- my.PValue[i,n.lat:1,c((n.lonr+1):n.lon,1:n.lonr)]
                    
                    dev.off()
                    
                    system(paste0("~/scripts/fig2catalog.sh -s 0.8 -c 'Start dates: ", stringa," of ",my.month[month],"\nLead time: ", leadtime.week[lead], " days\nReference dataset: ERA-Interim\nBias correction: none\nHatched area: significant from a bootstrapping test (p_value=0.05)' ", my.file," ", my.file2))


                } # close if on !RelDiagr

                gc()
                
                if(my.score.name.map == "RelDiagr") {

                    ## Note that bins should correspond to the number of hindcast members + 1, for systems with a low number of members (below ~20)
                    ## Warning: if the bootstrap show a gray point instead of a gray bar, decrease the number of bins!
                    my.RelDiagr[[lead]] <- ReliabilityDiagramHist(ens.chunk.prob[[lead]][int1,area.lat,area.lon], obs.chunk.prob[[lead]][int1,area.lat,area.lon], bins=n.intervals, nboot=500, plot=FALSE, plot.refin=TRUE) # Below normal tercile

                    ##my.RelDiagr[[n.leadtimes+lead]] <- ReliabilityDiagramHist(ens.chunk.prob[[lead]][int2,,], obs.chunk.prob[[lead]][int2,,], bins=5, nboot=0, plot=FALSE, plot.refin=F)
                    my.RelDiagr[[2*n.leadtimes+lead]] <- ReliabilityDiagramHist(ens.chunk.prob[[lead]][int3,area.lat,area.lon], obs.chunk.prob[[lead]][int3,area.lat,area.lon], bins=n.intervals, nboot=500, plot=FALSE, plot.refin=TRUE) # Above Normale tercile

                    
                    my.file <- paste0(work.dir,'/', var.name,'/', var.name,'_RelDiagr_', area.name,'_', my.month[month],'_leadtime_', leadtime.week[lead],'_', var.name,'.png')
                    my.file2 <- paste0(work.dir,'/', var.name,'/formatted/', var.name,'_RelDiagr_', area.name, '_', my.month[month],'_leadtime_', leadtime.week[lead],'_', var.name,'.png')

                    png(file=my.file,width=650,height=600)  

                    ##my.title <- paste0('Reliability Diagram of ',cfs.name,'\n ',var.name.map,' for ',my.month[month],'. Forecast time ',leadtime.week[lead],'.')
                    my.title <- paste0("ECMWF-MPS / ", var.name.map, " / Reliability Diagram \n", my.month[month], " (", leadtime.week[lead]," days lead time) / 1994-2013")
                    
                    par(fig=c(0, 0.83, 0, 1), new=TRUE)

                    plot(c(0,1),c(0,1),type="l",xlab="Forecast probability (%)",ylab="Observed frequency (%)", xaxt='n', yaxt='n',col='gray30', main=my.title, cex.main=1.6)

                    middle <- 100*round(my.RelDiagr[[lead]]$p.avgs,2)
                    interval <- (middle/2)[2]
                    left <- round(middle - interval,0)
                    left[1] <- 0
                    right <- round(middle + interval,0)
                    right[l(right)] <- 100
                    bins.label <- paste0(paste0(left,"-"),right)
                    
                    axis(1, at=my.RelDiagr[[lead]]$p.avgs, labels=FALSE)
                    text(x=my.RelDiagr[[lead]]$p.avgs, par("usr")[3]-0.03, labels=bins.label, srt=45, pos=1, xpd=TRUE)
                    axis(2, at=(0:10)/10, labels=10*(0:10), cex.axis=1)

                    no_res <- 1/3 #sum(my.RelDiagr[[lead]]$obs.counts)/sum(my.RelDiagr[[lead]]$hist.counts)
                    numb <- c(seq(0,1,by=0.1))
                    no_skill <- (numb+no_res)/2
                    lines(c(0,1), c(no_res,no_res), col="gray", lty=3)
                    lines(c(1/3,1/3), c(0,1), col="gray", lty=3)
                    lines(c(0,1), c(no_skill[1],no_skill[11]), col="black", lty=3)
                    
                    ##lines(my.RelDiagr[[lead]]$p.avgs[!is.na(my.RelDiagr[[lead]]$p.avgs)],my.RelDiagr[[lead]]$cond.prob[!is.na(my.RelDiagr[[lead]]$cond.prob)],type="o", pch=16, col="blue")            
                    for (i in 1:n.intervals){ 
                        lines(rep(my.RelDiagr[[lead]]$p.avgs[i], 2), c(my.RelDiagr[[lead]]$cbar.lo[i],my.RelDiagr[[lead]]$cbar.hi[i]), col="pink", lwd=2) 
                        lines(0.005+rep(my.RelDiagr[[2*n.leadtimes+lead]]$p.avgs[i], 2), c(my.RelDiagr[[2*n.leadtimes+lead]]$cbar.lo[i],my.RelDiagr[[2*n.leadtimes+lead]]$cbar.hi[i]), col="lightblue", lwd=2)
                    }
                    
                    
                    points(my.RelDiagr[[lead]]$p.avgs[!is.na(my.RelDiagr[[lead]]$p.avgs)],my.RelDiagr[[lead]]$cond.prob[!is.na(my.RelDiagr[[lead]]$cond.prob)],type="b", pch=1, col="red", cex=1.5, lwd=5)

                    ##points(my.RelDiagr[[n.leadtimes+lead]]$p.avgs[!is.na(my.RelDiagr[[n.leadtimes+lead]]$p.avgs)],my.RelDiagr[[n.leadtimes+lead]]$cond.prob[!is.na(my.RelDiagr[[n.leadtimes+lead]]$cond.prob)],type="b", pch=11, col="gold", cex=1.5, lwd=5) # col="darkgreen"
                    
                    points(0.005+my.RelDiagr[[2*n.leadtimes+lead]]$p.avgs[!is.na(my.RelDiagr[[2*n.leadtimes+lead]]$p.avgs)], my.RelDiagr[[2*n.leadtimes+lead]]$cond.prob[!is.na(my.RelDiagr[[2*n.leadtimes+lead]]$cond.prob)],type="b", pch=1, col="blue", cex=1.5, lwd=5)
                    
                    legend("bottomright", legend=c('Above Normal','Below Normal'), lty=c(1,1), lwd=c(2.5,2.5), col=c('blue','red'))

                    par(fig=c(0.75, 1, 0, 0.35), new=TRUE)
                    perc1 <- 100*my.RelDiagr[[lead]]$hist.counts/sum(my.RelDiagr[[lead]]$hist.counts)
                    barplot(perc1, beside=T,space=c(0,1.2), axes = T, axis.lty=T, axisnames = T, col = "red", ylim=c(0,max(perc1)+5), main="Below Normal")
                    par(fig=c(0.75, 1, 0.34, 0.36), new=TRUE)
                    mtext("% of forecasts for bin")

                    par(fig=c(0.75, 1, 0.25, 0.6), new=TRUE)
                    perc2 <- 100*my.RelDiagr[[2*n.leadtimes+lead]]$hist.counts/sum(my.RelDiagr[[2*n.leadtimes+lead]]$hist.counts)
                    barplot(perc2, beside=T, space=c(0,1.2), axes = T, axis.lty=T, axisnames = T, col = "blue", ylim=c(0,max(perc2)+5), main="Above Normal") 
                    par(fig=c(0.75, 1, 0.59, 0.61), new=TRUE)
                    mtext("% of forecasts for bin")
                    dev.off()

                    system(paste0("~/scripts/fig2catalog.sh -c 'Start dates: ", stringa," of ",my.month[month],"\nLead time: ", leadtime.week[lead], " days\nRegion: ", area.name,"\nReference dataset: ERA-Interim \nBias correction: none' ", my.file," ", my.file2))
                }

                gc()
            } # next lead

            gc()
        } # next score

        gc()
    } # next month


    #############################################################################
    #                Visualize summary tables for a region                      #
    #############################################################################

    ## If you use a mask, load it to average only over land and check that it has the same lat and lon positions of the score maps:
    if(land.only == TRUE){
        load(paste0('/shared/earth/EarthSystemServices/TOOLS/Topography_bathymetry_and_masks/Seamask.', n.lon, '.', n.lat,'.50m','.RData'))
        mask <- Seamask.512.256.50m
        ##Coordinates repositioning and mask conditioning
        mask <- mask[c((n.lonr+1):n.lon,1:n.lonr),n.lat:1]
        mask <- ifelse(mask == 1, 0, 1) ## assign 1 to land and 0 to sea to plot the mask
        mask <- t(mask)
        myImagePlot(mask)
        myImagePlot(my.FairRpss.chunk[1,,])
        mask <- ifelse(mask == 0, NA, 1) ## assign 1 to land and NA to sea to multiply it for the score values later
    }

    ## plot a box with the chosen area (do it only once):
    ##
    ##png(file=paste0(work.dir,'/',var.name,'/Box_',area.name,'.png'),width=1400,height=800)  
    ##PlotEquiMap(my.FairRpss.chunk[1,,c((n.lonr+1):n.lon,1:n.lonr)], c(lons[c((n.lonr+1):n.lon)]-360, lons[1:n.lonr]), lats, brks=c(-1000,1000), cols="lightblue" , axelab=F, filled.continents=TRUE, drawleg=F, boxlim=c(area[1],area[3],area[2],area[4]), boxcol="black", boxlwd=.7)
    ##dev.off()


    array.EnsCorr <- array.FairRpss <- array.FairCrpss <- array(NA,c(12,4))

    ## Load one file, just to take the lat and lon values:
    load(file=paste0(work.dir,'/',var.name,'_',my.month[1],'.RData'))

    if(lon.min < 360) area.lon <- c(1:(which(lons >= lon.max)[1]), (which(lons >= lon.min)[1]:length(lons)))  # restrict area to chosen one
    if(lon.min > 360) area.lon <-  (which(lons >= lon.min-360)[1]):(which(lons >= lon.max)[1]-1)

    if(area.name != "World") area.lat <- c(which(lats <= lat.max)[1]:(which(lats <= lat.min)[1]-1))  # restrict area to chosen one
    if(area.name == "World"){ area.lat <- 1:length(lats); area.lon <- 1:length(lons) }

    ## Load all data and average it over the chosen region:
    for(month in 1:12){

        load(file=paste0(work.dir,'/',var.name,'_',my.month[month],'.RData'))

        if(land.only == TRUE){
            ## remove sea values:
            for(i in 1:4) my.EnsCorr.chunk[i,,] <-  my.EnsCorr.chunk[i,,]*mask
            for(i in 1:4) my.FairRpss.chunk[i,,] <-  my.FairRpss.chunk[i,,]*mask
            for(i in 1:4) my.FairCrpss.chunk[i,,] <-  my.FairCrpss.chunk[i,,]*mask
        }
        
        for(l in 0:3){
            ##load(file=paste0(work.dir,"/",fields.name,"_",my.period[p],"_leadmonth_",l,"_","ClusterNames",".RData"))  # load cluster names and summarized data
            array.EnsCorr[month, 1+l] <- mean(my.EnsCorr.chunk[1+l, area.lat, area.lon], na.rm=T)
            array.FairRpss[month, 1+l] <- mean(my.FairRpss.chunk[1+l, area.lat, area.lon], na.rm=T)  
            array.FairCrpss[month, 1+l] <- mean(my.FairCrpss.chunk[1+l, area.lat, area.lon], na.rm=T)  
        }
    }


    if(land.only == TRUE) { mod.filename <- "_land" } else { mod.filename <- "" }

    my.file <- paste0(work.dir,'/',var.name,'/Summary_',var.name,'_', area.name, mod.filename,'_with_letras.png')
    my.file2 <- paste0(work.dir,'/',var.name,'/formatted/Summary_',var.name,'_', area.name, mod.filename,'_with_letras.png')

    png(file=my.file,width=700,height=500)  

    ##my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
    ##my.cols <- c('#0570b0','#bdc9e1', '#fff7ec', '#fee8c8','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f','#990000')
    ##my.cols <- c('#0570b0','#bdc9e1','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#ef6548','#d7301f','#990000')
    ##my.cols <- c('#74a9cf','#bdc9e1','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000')
    my.cols <- c('#bdc9e1','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')

    ##my.seq <- c(-1,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,1)
    ##my.seq <- c(-0.2,-0.1,0,0.1,0.2,0.3,0.4,0.5,0.6)
    my.seq <- c(-0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    plot.new()

    ##par(mar=c(0,0,2,0), fig=c(0, 1, 0.9, 1), new=TRUE) 
    ##mtext("Subseasonal sfcWind 1994-2013", cex=1.8)

    par(mar=c(0,0,2,0), fig=c(0.07, 0.27, 0.9, 1), new=TRUE) 
    mtext("(a)   EnsCorr", cex=1.5)

    par(mar=c(1,4,1,0), fig=c(0.02, 0.27, 0.1, 0.9), new=TRUE)
    plot(1,1, type="n", xaxt="n", yaxt="n", ylim=c(1,12.04), xlim=c(-0.23,3.2), ann=F)
    mtext(side = 1, text = "Lead time (days)", line = 3.5, cex=1.2)
    mtext(side = 2, text = "Start date", line = 3, cex=1.2)
    axis(1, at=seq(0,3), las=3, cex.axis=1, labels=c("5-11","12-18","19-25","26-32"), mgp=c(3,0.7,0))
    axis(2, at=seq(1,12), las=2, labels=rev(my.month.short), cex.axis=1)

    array.colors <- array(my.cols[8],c(12,4))
    array.colors[array.EnsCorr < my.seq[8]] <- my.cols[7]
    array.colors[array.EnsCorr < my.seq[7]] <- my.cols[6]
    array.colors[array.EnsCorr < my.seq[6]] <- my.cols[5]
    array.colors[array.EnsCorr < my.seq[5]] <- my.cols[4]
    array.colors[array.EnsCorr < my.seq[4]] <- my.cols[3]
    array.colors[array.EnsCorr < my.seq[3]] <- my.cols[2]
    array.colors[array.EnsCorr < my.seq[2]] <- my.cols[1]

    for(p in 1:12){ for(l in 0:3){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+13-p, 0.5+13-p, 0.5+13-p, -0.5+13-p), col=array.colors[p,1+l]) }}

    par(mar=c(0,0,2,0), fig=c(0.32, 0.57, 0.9, 1), new=TRUE) 
    mtext("(b)  FairRPSS", cex=1.5)

    par(mar=c(1,4,1,0), fig=c(0.32, 0.57, 0.1, 0.9), new=TRUE)
    plot(1,1, type="n", xaxt="n", yaxt="n", ylim=c(1,12.04), xlim=c(-0.23,3.2), ann=F)
    mtext(side = 1, text = "Lead time (days)", line = 3.5, cex=1.2)
    mtext(side = 2, text = "Start date", line = 3, cex=1.2)
    axis(1, at=seq(0,3), las=3, cex.axis=1, labels=c("5-11","12-18","19-25","26-32"), mgp=c(3,0.7,0))
    axis(2, at=seq(1,12), las=2, labels=rev(my.month.short), cex.axis=1)

    array.colors <- array(my.cols[8],c(12,4))
    array.colors[array.FairRpss < my.seq[8]] <- my.cols[7]
    array.colors[array.FairRpss < my.seq[7]] <- my.cols[6]
    array.colors[array.FairRpss < my.seq[6]] <- my.cols[5]
    array.colors[array.FairRpss < my.seq[5]] <- my.cols[4]
    array.colors[array.FairRpss < my.seq[4]] <- my.cols[3]
    array.colors[array.FairRpss < my.seq[3]] <- my.cols[2]
    array.colors[array.FairRpss < my.seq[2]] <- my.cols[1]

    for(p in 1:12){ for(l in 0:3){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+13-p, 0.5+13-p, 0.5+13-p, -0.5+13-p), col=array.colors[p,1+l]) }}

    par(mar=c(0,0,2,0), fig=c(0.62, 0.87, 0.9, 1), new=TRUE) 
    mtext("(c) FairCRPSS", cex=1.5)

    par(mar=c(1,4,1,0), fig=c(0.62, 0.87, 0.1, 0.9), new=TRUE)
    plot(1,1, type="n", xaxt="n", yaxt="n", ylim=c(1,12.04), xlim=c(-0.23,3.2), ann=F)
    mtext(side = 1, text = "Lead time (days)", line = 3.5, cex=1.2)
    mtext(side = 2, text = "Start date", line = 3, cex=1.2)
    axis(1, at=seq(0,3), las=3, cex.axis=1, labels=c("5-11","12-18","19-25","26-32"), mgp=c(3,0.7,0))
    axis(2, at=seq(1,12), las=2, labels=rev(my.month.short), cex.axis=1)

    array.colors <- array(my.cols[8],c(12,4))
    array.colors[array.FairCrpss < my.seq[8]] <- my.cols[7]
    array.colors[array.FairCrpss < my.seq[7]] <- my.cols[6]
    array.colors[array.FairCrpss < my.seq[6]] <- my.cols[5]
    array.colors[array.FairCrpss < my.seq[5]] <- my.cols[4]
    array.colors[array.FairCrpss < my.seq[4]] <- my.cols[3]
    array.colors[array.FairCrpss < my.seq[3]] <- my.cols[2]
    array.colors[array.FairCrpss < my.seq[2]] <- my.cols[1]

    for(p in 1:12){ for(l in 0:3){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+13-p, 0.5+13-p, 0.5+13-p, -0.5+13-p), col=array.colors[p,1+l]) }}

    par(fig=c(0.89, 1, 0.1, 0.9), new=TRUE) 
    ##ColorBar2(brks=my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, label.dist=2, my.ticks=-0.5 + 1:length(my.brks), my.labels=my.brks)
    ColorBar2(brks = my.seq, cols = my.cols, vert=T, draw.ticks=F, label.dist=0.3, my.ticks=-0.5 + 1:length(my.seq), my.labels=my.seq)
    gc()

    dev.off()

    ## Not checked but whould work:
    ##system(paste0("~/scripts/fig2catalog.sh -r 50 -c 'Region: ", area.name, "\nReference dataset: ERA-Interim' ", my.file," ", my.file2))




    ## Monthly reliability diagrams, all over the same graph #
    ## ONLY FOR SEA+LAND!!!!

    my.RelDiagr<-list()

    my.file <- paste0(work.dir,'/',var.name,'/Summary_RelDiagr_', area.name,'.png')
    my.file2 <- paste0(work.dir,'/',var.name,'/formatted/','/Summary_RelDiagr_', area.name,'.png')

    ##n.lonr <- n.lon - ceiling(length(lons[lons>0 & lons < 180])) # count the number of longitude values between 180 and 360 degrees longitud

    png(file=my.file, width=1000, height=700)
    plot(0, type = "n", axes = FALSE, ann = FALSE)
    mtext(side = 3, text = "ECMWF-MFS / Reliability Diagram\nJanuary to December / 1994-2013", line = -1, cex=2.4, font=2)
    par(mar=c(0,0,0,0) , fig=c(0, 1, 0, 0.4), new=TRUE)
    legend(0.8,-0.8,0,0,legend=my.month[c(1,4,7,10)], lty=c(1,1), lwd=c(2.5,2.5), col=col.month[c(1,4,7,10)], ncol=4)

    par(mar=c(4.8,3.8,3.8,3.8) , fig=c(0, 1, 0, 0.4), new=TRUE)

    for(tercile in c(1,3)){
        print(paste0("Tercile: ",tercile))

        my.lead <- (1:n.leadtimes) + (tercile-1) * 4
        
        for(lead2 in my.lead){
            print(paste0("Lead time: ",lead2))

            xmin <- 0.25 * ((lead2-1) %% 4)
            xmax <- xmin + 0.25
            ymin <- 0.10 + 0.38 * (tercile-1)/2
            ymax <- ymin + 0.38

            ##my.title <- paste0('Reliability Diagram of ',cfs.name,'\n ',var.name.map,' for ',my.month[month],'. Forecast time ',leadtime.week[lead],'.')
            ##my.title <- paste0("ECMWF-S4 / ", var.name.map, " / Reliability Diagram \nJanuary to December / 1994-2013")
            my.title <- paste0("Lead time: ", leadtime.week[1+((lead2-1) %% 4)], " days")

            par(fig=c(xmin, xmax, ymin, ymax), new=TRUE)
            mod.subtitle <- ifelse(tercile == 1, "lower","upper")
            plot(c(0,1),c(0,1),type="l",xlab=paste0("Forecast frequency ", mod.subtitle," tercile"),ylab="Observed frequency", col='gray30', main=my.title, cex.main=1.4)

            no_res <- 1/3 #sum(my.RelDiagr[[lead]]$obs.counts)/sum(my.RelDiagr[[lead]]$hist.counts)
            numb <- c(seq(0,1,by=0.1))
            no_skill <- (numb+no_res)/2
            lines(c(0,1), c(no_res,no_res), col="gray", lty=3)
            lines(c(1/3,1/3), c(0,1), col="gray", lty=3)
            lines(c(0,1), c(no_skill[1],no_skill[11]), col="black", lty=3)
            
            for(month in c(1,4,7,10)){ #my.months){
                ##month=1  # for the debug
                ##print(paste0("Month=",month))
                
                ## Load data:
                load(file=paste0(work.dir,'/',var.name,'_',my.month[month],'.RData'))
                
                cat(paste0('Computing the Reliability Diagram for month ', month,'. Please wait... \n'))

                lead <- 1 + (lead2-1) %% 4
                
                if(tercile == 1) my.RelDiagr[[lead]] <- ReliabilityDiagram(ens.chunk.prob[[lead]][int1,area.lat,area.lon], obs.chunk.prob[[lead]][int1,area.lat,area.lon], bins=n.intervals, nboot=0, plot=FALSE, plot.refin=F) #tercile 1
                
                ##my.RelDiagr[[n.leadtimes+lead]] <- ReliabilityDiagram(ens.chunk.prob[[lead]][int2,area.lat,area.lon], obs.chunk.prob[[lead]][int2,area.lat,area.lon], bins=5, nboot=0, plot=FALSE, plot.refin=F)
                
                if(tercile == 3) my.RelDiagr[[2*n.leadtimes+lead]] <- ReliabilityDiagram(ens.chunk.prob[[lead]][int3,area.lat,area.lon], obs.chunk.prob[[lead]][int3,area.lat,area.lon], bins=n.intervals, nboot=0, plot=FALSE, plot.refin=F)

                
                if(tercile == 1) points(my.RelDiagr[[lead]]$p.avgs[!is.na(my.RelDiagr[[lead]]$p.avgs)],my.RelDiagr[[lead]]$cond.prob[!is.na(my.RelDiagr[[lead]]$cond.prob)],type="o", pch=16, col=col.month[month], cex=.8, lwd=2)

                if(tercile == 3) points(my.RelDiagr[[2*n.leadtimes+lead]]$p.avgs[!is.na(my.RelDiagr[[2*n.leadtimes+lead]]$p.avgs)], my.RelDiagr[[2*n.leadtimes+lead]]$cond.prob[!is.na(my.RelDiagr[[2*n.leadtimes+lead]]$cond.prob)],type="o", pch=16, col=col.month[month], cex=.8, lwd=2)

                rm(obs.chunk.prob, ens.chunk.prob)
                gc()
            } # next month

        } # next lead 
    } # next tercile


    dev.off()



} # close for on area.num

