rm(list = ls(all = TRUE))

#libraries
library('ncdf4')
library(fields)
library(maps)

#prendre en compte les arguments
args<-commandArgs(TRUE)
#attribution des argument aux variables
inputfile<-args[1]
spec<-args[2]
level<-as.integer(args[3])
date<-args[4]

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

#creation d'un fonction
dmean <- function (x) {
return(mean(x))
}

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

#pour le plot
mini<-0
maxi<-180
legendlab<-paste(spec,'daily mean',sep=" ")
outfile <- paste("map_mean_",date,".png", sep="")

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

#calcmean
#avec fonction c'est + rapide
meand<-apply(var[,,level,itime:(itime+24)],1:2,dmean)

#sans fonction c'est
#meand<-numeric(dim(var)[1]*dim(var)[2])
#dim(meand)<-c(dim(var)[1],dim(var)[2])
#for(izo in seq(from=1,to=dim(var)[1],by=1)){
#for(ime in seq(from=1,to=dim(var)[2],by=1)){
#meand[izo,ime]<-mean(var[izo,ime,level,itime:(itime+24)])
#}}


#creation du png
png(filename = outfile, width=700, height=700, pointsize=14, bg = "white", res = NA,type="cairo")
par(oma=c(0,0,0,2))
image.plot(lon,lat,meand[,],zlim=c(mini,maxi),xlab='Longitude',ylab='Latitude',legend.lab=legendlab,axis.args=list(at=seq(from=mini,to=maxi,by=10),labels=(seq(from=mini,to=maxi,by=10))))
map(add=T)
title(main=paste(substr(time[itime],1,13),sep=" "))
dev.off()
