###########################################################################################
#                  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

# 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

# choose one or more skills scores to visualize between EnsCorr, FairRPSS, FairCRPSS and/or RelDiagr:
my.score.name <- c('FairRpss','FairCrpss','EnsCorr','RelDiagr')  

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

##########################################################################################
#                 visualize worldwide monthly maps of skill scores                       #
##########################################################################################

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

    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='EnsCorr'  # 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)

	my.brk<-brk.rpss # at present all breaks and colors are the same, so there is no need to differenciate between indexes
	my.col<-col.rpss

	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"){

	      #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_',lead,'.png')
              my.file2 <-  paste0(work.dir,'/',var.name,'/formatted/',var.name,'_',my.score.name.map,'_',my.month[month],'_leadtime_',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))
              
              if(my.score.name.map=="EnsCorr") 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.81,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-S4 / ", var.name.map, " / ", my.score.name.map, "\n", my.month[month], " / 1994-2013")
	      mtext(my.title, cex=2.2)

              # Color legend:
              par(fig=c(0.92,1,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)
              
              ### 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 'Reference dataset: ERA-Interim \nLead time: ", leadtime.week[lead], " days' ", my.file," ", my.file2))
              
	  } # close if on !RelDiagr

	  if(my.score.name.map == "RelDiagr") {
              
              my.file <- paste0(work.dir,'/',var.name,'/RelDiagr_',my.month[month],'_Forecast_time_',leadtime.week[lead],'_',var.name,'.png')
              my.file2 <- paste0(work.dir,'/',var.name,'/formatted/','/RelDiagr_',my.month[month],'_Forecast_time_',leadtime.week[lead],'_',var.name,'.png')

	      png(file=my.file,width=600,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-S4 / ", var.name.map, " / Reliability Diagram \n", my.month[month], " / 1994-2013")

	      plot(c(0,1),c(0,1),type="l",xlab="Forecast Frequency",ylab="Observed Frequency", col='gray30', main=my.title, cex.main=1.6)
	      lines(my.score[[lead]]$p.avgs[!is.na(my.score[[lead]]$p.avgs)],my.score[[lead]]$cond.prob[!is.na(my.score[[lead]]$cond.prob)],type="o", pch=16, col="blue")
	      #lines(my.score[[n.leadtimes+lead]]$p.avgs[!is.na(my.score[[n.leadtimes+lead]]$p.avgs)],my.score[[n.leadtimes+lead]]$cond.prob[!is.na(my.score[[n.leadtimes+lead]]$cond.prob)],type="o",pch=16,col="darkgreen")
	      lines(my.score[[2*n.leadtimes+lead]]$p.avgs[!is.na(my.score[[2*n.leadtimes+lead]]$p.avgs)], my.score[[2*n.leadtimes+lead]]$cond.prob[!is.na(my.score[[2*n.leadtimes+lead]]$cond.prob)],type="o", pch=16, col="red")
	      legend("bottomright", legend=c('Lower Tercile','Upper Tercile'), lty=c(1,1), lwd=c(2.5,2.5), col=c('blue','red'))
    
	      dev.off()

              system(paste0("~/scripts/fig2catalog.sh -c 'Reference dataset: ERA-Interim \nLead time: ", leadtime.week[lead], " days' ", my.file," ", my.file2))
           }
          
	} # next lead

    } # next score

} # next month


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

# DY European areas: (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)

# all the World:
area0 <- c(-180,180,-90,90)
# Northern Europe:
area1 <- c(-15,45,45,75)
# Southwestern Europe:
area2 <- c(-15,20,35,45)
# Southeastern Europe:
area3 <- c(20,45,35,45)
# All Europe:
area4 <- c(-15,45,35,75)
# North America:
area5<-c(-130,-60,30,50)

# Choose one region between those defined above:
area <- area4

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

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

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

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

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

# 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'))
    
   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)  
   }
}


#png(filename=paste0(work.dir,"/",forecast.name,"_summary_impact_",var.name[var.num],".png"), width=550, height=400)
png(file=paste0(work.dir,'/',var.name,'/Summary_',var.name,'.png'),width=700,height=500)  

my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))
my.seq <- c(-1,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,1)

# 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,4,0), fig=c(0.07, 0.27, 0.80, 1), new=TRUE) 
mtext("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 = "Leadtime", line = 3.5, cex=1.2)
mtext(side = 2, text = "Startdate", 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=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+p, 0.5+p, 0.5+p, -0.5+p), col=array.colors[p,1+l]) }}

par(mar=c(0,0,4,0), fig=c(0.32, 0.57, 0.8, 1), new=TRUE) 
mtext("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 = "Leadtime", line = 3.5, cex=1.2)
mtext(side = 2, text = "Startdate", 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=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+p, 0.5+p, 0.5+p, -0.5+p), col=array.colors[p,1+l]) }}

par(mar=c(0,0,4,0), fig=c(0.62, 0.87, 0.8, 1), new=TRUE) 
mtext("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 = "Leadtime", line = 3.5, cex=1.2)
mtext(side = 2, text = "Startdate", 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=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+p, 0.5+p, 0.5+p, -0.5+p), col=array.colors[p,1+l]) }}
#for(p in 1:12){ for(l in 0:3){ polygon(c(0.5+p-1, 0.5+p-1, 1.5+p-1, 1.5+p-1), c(-0.5+l, 0.5+l, 0.5+l, -0.5+l), 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)

dev.off()




##############################################################
# Only monthly reliability diagrams, all over the same graph #
##############################################################

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

    n.lonr <- n.lon - ceiling(length(lons[lons>0 & lons < 180])) # count the number of longitude values between 180 and 360 degrees longitud
    
    my.score.name.map == "RelDiagr"
	#my.score.name.map='EnsCorr'  # for the debug

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

	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)

	my.brk<-brk.rpss # at present all breaks and colors are the same, so there is no need to differenciate between indexes
	my.col<-col.rpss

	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"){

	      #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_',lead,'.png')
              my.file2 <-  paste0(work.dir,'/',var.name,'/formatted/',var.name,'_',my.score.name.map,'_',my.month[month],'_leadtime_',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))
              
              if(my.score.name.map=="EnsCorr") 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.81,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-S4 / ", var.name.map, " / ", my.score.name.map, "\n", my.month[month], " / 1994-2013")
	      mtext(my.title, cex=2.2)

              # Color legend:
              par(fig=c(0.92,1,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)
              
              ### 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 'Reference dataset: ERA-Interim \nLead time: ", leadtime.week[lead], " days' ", my.file," ", my.file2))
              
	  } # close if on !RelDiagr

	  if(my.score.name.map == "RelDiagr") {
              
              my.file <- paste0(work.dir,'/',var.name,'/RelDiagr_',my.month[month],'_Forecast_time_',leadtime.week[lead],'_',var.name,'.png')
              my.file2 <- paste0(work.dir,'/',var.name,'/formatted/','/RelDiagr_',my.month[month],'_Forecast_time_',leadtime.week[lead],'_',var.name,'.png')

	      png(file=my.file,width=600,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-S4 / ", var.name.map, " / Reliability Diagram \n", my.month[month], " / 1994-2013")

	      plot(c(0,1),c(0,1),type="l",xlab="Forecast Frequency",ylab="Observed Frequency", col='gray30', main=my.title, cex.main=1.6)
	      lines(my.score[[lead]]$p.avgs[!is.na(my.score[[lead]]$p.avgs)],my.score[[lead]]$cond.prob[!is.na(my.score[[lead]]$cond.prob)],type="o", pch=16, col="blue")
	      #lines(my.score[[n.leadtimes+lead]]$p.avgs[!is.na(my.score[[n.leadtimes+lead]]$p.avgs)],my.score[[n.leadtimes+lead]]$cond.prob[!is.na(my.score[[n.leadtimes+lead]]$cond.prob)],type="o",pch=16,col="darkgreen")
	      lines(my.score[[2*n.leadtimes+lead]]$p.avgs[!is.na(my.score[[2*n.leadtimes+lead]]$p.avgs)], my.score[[2*n.leadtimes+lead]]$cond.prob[!is.na(my.score[[2*n.leadtimes+lead]]$cond.prob)],type="o", pch=16, col="red")
	      legend("bottomright", legend=c('Lower Tercile','Upper Tercile'), lty=c(1,1), lwd=c(2.5,2.5), col=c('blue','red'))
    
	      dev.off()

              system(paste0("~/scripts/fig2catalog.sh -c 'Reference dataset: ERA-Interim \nLead time: ", leadtime.week[lead], " days' ", my.file," ", my.file2))
           }
          
	} # next lead

} # next month








