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]


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

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


#tableau pour les grilles
latc <- numeric((dim(lat)[1]+1)*(dim(lat)[2]+1))
lonc <- numeric((dim(lon)[1]+1)*(dim(lon)[2]+1))
dim(latc) <- c((dim(lat)[1]+1),(dim(lat)[2]+1))
dim(lonc) <- c((dim(lon)[1]+1),(dim(lon)[2]+1))
#calcul pour la grille 
for (j in seq(from=2,to=dim(lat)[1],by=1)){
for (k in seq(from=1,to=dim(lat)[2],by=1)){
lonc[j,k] <- lon[j,k]+((lon[j-1,k]-lon[j,k])/2)
}
}
for (k in seq(from=1,to=dim(lat)[2],by=1)){
lonc[1,k] <- lon[1,k]+((lon[1,k]-lon[2,k])/2)
lonc[dim(lonc)[1],k] <- lon[dim(lat)[1],k]-((lon[1,k]-lon[2,k])/2)
}

for (j in seq(from=1,to=dim(lonc)[1],by=1)){
lonc[j,dim(lonc)[2]] <- lonc[j,dim(lon)[2]]
}


for (k in seq(from=2,to=dim(lat)[2],by=1)){
for (j in seq(from=1,to=dim(lat)[1],by=1)){
latc[j,k] <- lat[j,k]+((lat[j,k-1]-lat[j,k])/2)
}
}
for (k in seq(from=1,to=dim(lat)[1],by=1)){
latc[k,1] <- lat[k,1]+((lat[k,1]-lat[k,2])/2)
latc[k,dim(lonc)[2]] <- lat[k,dim(lat)[2]]-((lat[k,1]-lat[k,2])/2)
}

for (j in seq(from=1,to=dim(lonc)[2],by=1)){
latc[dim(lonc)[1],j] <- latc[dim(lat)[1],j]
}
#####################

null <- numeric((dim(lon)[1])*(dim(lon)[2]))
dim(null) <- c((dim(lat)[1]),(dim(lat)[2]))

null[,]<-0

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

png(filename = outfile, width=700, height=700, pointsize=14, bg = "white", res = NA,type="cairo")
poly.image(lon,lat,null,xlab="Longitude",ylab="Latitude")
title('GRID')
map(add=T)
#GRID
for (j in seq(from=1,to=dim(latc)[1],by=1)){
lines(lonc[j,],latc[j,],col="black",lwd=0.3)
}

for (j in seq(from=1,to=dim(latc)[2],by=1)){
lines(lonc[,j],latc[,j],col="black",lwd=0.3)
}
dev.off()
