rm(list=ls())

library("rstudioapi") 

setwd(dirname(getActiveDocumentContext()$path)) 

fileName="F:/AlgoT_data/WaveAugustBig.grib"
workDir="G:/temp/"

#imax=17280
imax=17856
#imax=2
i=1
while(i<imax) {
  wg.str <- paste0("wgrib -V -text -d ",i," -o ",workDir,"tmp.txt ", fileName)
  wg.out <- system(wg.str)
  valuesAbs <- scan(paste0(workDir,"tmp.txt"), skip = 1, quiet = TRUE)
  if (i==1) {
    valuesAbsMax=valuesAbs
  } else {
    valuesAbsMax=pmax(valuesAbsMax,valuesAbs)
  }
  i=i+1
}

#limit values
values12m=rep(12.0,length(valuesAbsMax))
valuesAbsMaxLimited12m=pmin(valuesAbsMax,values12m)
valuesAbsMaxLimited12m[1]=12.0
valuesAbsMaxLimited12m[2]=0.0

nx=181
ny=141
#human readable matrix orientetion
#grid = matrix(nrow=ny, ncol=nx)
#for (i in 1:ny){
#  for (j in 1:nx) {
#    grid[i,j]=valuesAbsMaxLimited[(i-1)*nx+j]
#    #grid[i,j]=(i-1)*nx+j
#  }
#}

#matrix orientation for the R studio image function
grid = matrix(nrow=nx, ncol=ny)
for (j in 1:ny){
  for (i in 1:nx) {
    grid[i,(ny-j+1)]=valuesAbsMaxLimited12m[(j-1)*nx+i]
    #grid[i,(ny-j+1)]=(j-1)*nx+i
  }
}

n.colors <- 100
color.fun <- colorRampPalette(colors = c("deepskyblue","green","yellow","orange","red","orange4","darkmagenta","darkorchid","magenta","pink","gray","darkgray","black"))
col.key <- list("color" = color.fun(n = n.colors),
                      "value" = seq(from = min(grid), to = max(grid), along.with = 1:n.colors))

xlabels=seq(from = -90, to = 0, by = 0.5)
ylabels=seq(from = 0, to = 70, by = 0.5)
#xlabels=(1:nrow(grid))
#ylabels=(1:ncol(grid))
par(fig = c(0,.9,0,1), mar = c(2,2,2,0))
image(xlabels,ylabels,grid,col=col.key$color)

# add the legend
par(fig = c(.9,1,.3,.7), mar = c(1,1,1,2.5), new = T)
plot(x = rep(1,length(col.key$value)), y = col.key$value, xlim = c(0,1), col = col.key$color, type = "n", xaxs = "i", yaxs = "i", ann = F, axes = F)
segments(x0 = 0, x1 = 1, y0 = col.key$value, y1 = col.key$value, col = col.key$color, lwd = 5)
axis(side = 4,lwd = 0, las = 2, line = -.75)
mtext(text = "Legend", adj = 0, line = 1, cex = 1.2)


