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])
day<-as.integer(args[4])
hour<-as.integer(args[5])

#Tests
if (length(args) != 5){
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('day ',args[4],sep=""))
print(paste('hour ',args[5],sep=""))
}

#creation d'un fonction
log_em <- function (x) {
return(log(max(x,1),base=10))
}

#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")
#fermeture
nc_close(in.file)

#pour le plot
mini<-6
legendlab<-expression(molec%.%cm^{-2}%.%s^{-1},sep=" ")

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


#calcmax
em_log<-apply(var[,,level,day,hour],1:2,log_em)
maxi<-as.integer(max(em_log[,]))+1

#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,em_log[,],zlim=c(mini,maxi),xlab='Longitude',ylab='Latitude',legend.lab=legendlab,axis.args=list(at=seq(from=mini,to=maxi,by=1),labels=(10^seq(from=mini,to=maxi,by=1))))
map(add=T)
title(spec)
dev.off()
