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=""))
}

#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,'concentration',sep=" ")
outfile <- paste("map_chim_",date,".png", sep="")

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

#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,var[,,level,itime],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()
