rm(list = ls(all = TRUE))

#libraries
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=""))
stop("complete le script")
}


#Ouverture ASCII
COORD <- read.table(inputfile)

indic<-COORD[1,1]
nzonal<-1
for (line in seq(from=2,to=dim(COORD)[1],by=1)){
if(COORD[line,1] > indic){
nzonal<-nzonal+1
}else
break
}
nmerid<-dim(COORD)[1]/nzonal

#tableau
null<-numeric(nzonal*nmerid)
dim(null)<-c(nzonal,nmerid)
lon<-numeric(nzonal*nmerid)
lat<-numeric(nzonal*nmerid)
dim(lon)<-c(nzonal,nmerid)
dim(lat)<-c(nzonal,nmerid)


#calcul lon et lat
k<-0
for (j in seq(from=1,to=nmerid,by=1)){
for (i in seq(from=1,to=nzonal,by=1)){
k<-k+1
lon[i,j]<-COORD[k,1]
lat[i,j]<-COORD[k,2]
}}


#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(lonc)[1],j]
}
#####################

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

null[,]<-0
#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))

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

png(filename = outfile, width=900, height=900, pointsize=14, bg = "white", res = NA,type="cairo")
poly.image(lon,lat,null,xlab="Longitude",ylab="Latitude",col=my_col,zlim=c(-1,1))
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()
