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
inputfile1<-args[1]
inputfile2<-args[2]
spec<-args[3]
level<-as.integer(args[4])
date<-args[5]


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

#Ouverture netcdf
in.file <- nc_open(inputfile1)
#Variable
var1 <- 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)
#input2
in.file <- nc_open(inputfile2)
var2 <- ncvar_get(in.file,spec)
nc_close(in.file)

#pour le plot
legendlab<-paste(spec,'difference',sep=" ")
outfile <- paste("map_diff_",date,".png", sep="")

#creation d'un tableau
diff<-numeric(dim(var1)[1]*dim(var1)[2])
dim(diff)<-c(dim(var1)[1],dim(var1)[2])

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

#calcul diff
diff[,]<-var1[,,level,itime]-var2[,,level,itime]

#min max 
mini<-as.integer(min(diff,0)-1)
maxi<-as.integer(max(diff,-mini)+1)
mini<--maxi


#scale color
my_col <- numeric(20*3)
dim(my_col) <- c(20,3)
my_col[1:10,1] <- seq(from=0,to=1,length.out=10)
my_col[1:10,2] <- seq(from=0,to=1,length.out=10)
my_col[1:10,3] <- seq(from=1,to=1,length.out=10)
my_col[11:20,1] <- seq(from=1,to=1,length.out=10)
my_col[11:20,2] <- seq(from=1,to=0,length.out=10)
my_col[11:20,3] <- seq(from=1,to=0,length.out=10)
my_col <- rgb((my_col))


#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,diff[,],zlim=c(mini,maxi),xlab='Longitude',ylab='Latitude',legend.lab=legendlab,axis.args=list(at=seq(from=mini,to=maxi,by=1),labels=(seq(from=mini,to=maxi,by=1))),col=my_col)
map(add=T)
title(main=paste(substr(time[itime],1,13),sep=" "))
dev.off()
