rm(list = ls(all = TRUE))

#libraries
library('TeachingDemos')
library(ncdf4)
library(maps)
source('./function.R')

#prendre en compte les arguments
args<-commandArgs(TRUE)

#Tests
if (length(args) != 3){
print("Il manque des arguments : ")
print(paste('inputfile ',args[1],sep=""))
print(paste('level ',args[2],sep=""))
print(paste('date ',args[3],sep=""))
}

#attribution des argument aux variables
inputfile<-args[1]
level<-as.integer(args[2])
date<-args[3]


#Ouverture netcdf
in.file <- nc_open(inputfile)
#Variable
winz<-ncvar_get(in.file,"winz")
winm<-ncvar_get(in.file,"winm")
lat <- ncvar_get(in.file,"lat")
lon <- ncvar_get(in.file,"lon")
time <- ncvar_get(in.file,"Times")
#fermeture
nc_close(in.file)


#chercher la date
for(i in seq(from=1,to=dim(time),by=1)){
if(date==substr(time[i],1,13)){
itime<-i
break
}
}

#tables
nzonal<-dim(winm)[1]
nmerid<-dim(winm)[2]
speed<-numeric(nzonal*nmerid)
dim(speed)<-c(nzonal,nmerid)
dir<-numeric(nzonal*nmerid)
dim(dir)<-c(nzonal,nmerid)

#calcul

speed[,]<-sqrt(winz[,,level,itime]*winz[,,level,itime]+winm[,,level,itime]*winm[,,level,itime])
dir[,]<-atan2(winz[,,level,itime],winm[,,level,itime])



#pour le plot
mini<-0
maxi<-max(speed)
legendlab<-expression(m%.%s^{-1},sep=" ")

#scale 
M.cols=colorRampPalette(c("blue","cyan", "yellow", "red"),space="rgb")
my_col=M.cols(100)
#transformation en valeur/couleur
colorvalues<-val2col(speed,col=my_col,zlim=c(0,maxi))

col_value_tab<-character(nzonal*nmerid)
dim(col_value_tab)<-c(nzonal,nmerid)

indic<-0
for (ime in seq(from=1,to=nmerid,by=1)){
for (izo in seq(from=1,to=nzonal,by=1)){
indic<-indic+1
col_value_tab[izo,ime]<-colorvalues[indic]
}}


#arguments png
heights=c(7)
widths=c(7,1)
res=150

outfile <- paste("map_wind_",date,".png", sep="")

#creation du png
png(filename = outfile, res=res,width = sum(widths), height = sum(heights), units="in")
par(omi=c(0.1, 0.1, 0.1, 0.1), ps=18,cex=3)
layout(matrix(c(1,2,3),nrow=1,ncol=3,byrow=TRUE), widths = widths, heights = heights, respect=TRUE)
plot(lon,lat,type='n',xlab='Longitude',ylab='latitude')
for (izo in seq(from=1,to=nzonal,by=2)){
for (ime in seq(from=1,to=nmerid,by=2)){
my.symbols(lon[izo,ime],lat[izo,ime],ms.arrows,angle=dir[izo,ime],r=0.2,add=TRUE,col=col_value_tab[izo,ime],length=0.05)
}}
map(add=T)
title(main=paste('wind_',level,'_',substr(time[itime],1,13),sep=""))
box()
#add scale
par(mai=c(0.2, 0, 0.2, 0.6))
image.scale(speed[,], col=my_col, horiz=FALSE, yaxt="n",zlim=c(0,maxi),cex=1)
axis(4,las=1)
box()
par(mai=c(0.2, 0, 0.2, 0.1))
mtext(legendlab, side=4, line=2.5)
dev.off()

