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]
date<-args[3]
lonp<- args[4]
latp<- args[5]


#Ouverture netcdf
in.file <- nc_open(inputfile)
#Variable
hlay<-ncvar_get(in.file,'hlay')
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)


#recalcul milieux boites
thlay<-dim(hlay)[3]

#

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

#chercher les lon lat
#chercher la date
for(izo in seq(from=1,to=dim(lon)[1],by=1)){
if(lonp==lon[izo,1]){
ilon<-izo
break
}
}
for(ime in seq(from=1,to=dim(lon)[2],by=1)){
if(latp==lat[1,ime]){
ilat<-ime
break
}
}

thlay[1]<-hlay[1]/2
for (ilev in seq(2,dim(hlay)[3])){
    thlay[ilev]<-(hlay[ilon,ilat,ilev,itime]+hlay[ilon,ilat,(ilev-1),itime])/2
}

legendlab<-paste('Concentration ppb',sep=" ")
if(substr(spec,1,1)=='p'){
legendlab<-expression("Concentration "(µg%.%cm^{-3}),sep="")
}

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

#creation du png
png(filename = outfile, width=500, height=700, pointsize=14, bg = "white", res = NA,type="cairo")
par(oma=c(0,0,0,2))
plot(var[ilon,ilat,,itime],thlay,ylab='Altitude (m)',xlab=legendlab,type='l')
title(main=paste(substr(time[itime],1,13),sep=" "),spec)
dev.off()
