;
; Reads in IPCC gridded temperatures (monthly) and converts it to netCDF format,
; with all metadata there, and with time extendable.
;
;--------------------------------------------------------------------------
;
; Define files
;
fnin='/dave3/f055/detect/obsdat/tair_monthly.dat'
fnout='/dave3/f055/detect/obsdat/tair_monthly.nc'
;
; Specify times
;
mintime=1856
maxtime=1994
nyear=maxtime-mintime+1
nmon=12
ntime=nyear*nmon
xtime=findgen(ntime)/float(nmon)+mintime      ; time in years+months/12
timey=float(indgen(ntime)/nmon + mintime)
timem=float(indgen(ntime) mod nmon)
;
; Define grid
;
g=def_grid(/ipcc)
;
; Define arrays
;
temperature=fltarr(g.nx,g.ny,ntime)
;
; Read data
;
print,'Reading data'
openr,1,fnin
for i = 0 , ntime-1 do begin
;  print,timey(i),timem(i),xtime(i)
  indat=rdtair(g.nx,g.ny,lun=1)
  temperature(*,*,i)=indat(*,*)
endfor
close,1
;
; Convert missing data back to -999.
;
print,'Converting missing data'
missval=-999.
misslist=where(finite(temperature) eq 0,nmiss)
if nmiss gt 0 then temperature(misslist)=missval
;
; Create new netCDF file
;
print,'Creating netCDF file'
ncid=ncdf_create(fnout)
;
; Define dimensions
;
lonid=ncdf_dimdef(ncid,'longitude',g.nx)
latid=ncdf_dimdef(ncid,'latitude',g.ny)
timid=ncdf_dimdef(ncid,'time',/unlimited)    ; but ntime at the mo'
;
; Define variables and their attributes
;
vlonid=ncdf_vardef(ncid,'longitude',[lonid])
ncdf_attput,ncid,vlonid,'Unit','Degrees of grid-box centres (+ve E, -ve W)'
;
vlatid=ncdf_vardef(ncid,'latitude',[latid])
ncdf_attput,ncid,vlatid,'Unit','Degrees of grid-box centres (+ve N, -ve S)'
;
vtimid=ncdf_vardef(ncid,'time',[timid])
ncdf_attput,ncid,vtimid,'Unit','Years plus month/12'
;
yrid=ncdf_vardef(ncid,'year',[timid])
monid=ncdf_vardef(ncid,'month',[timid])
;
tempid=ncdf_vardef(ncid,'temperature',[lonid,latid,timid])
ncdf_attput,ncid,tempid,'Source','IPCC 5 by 5 gridded surface temperatures'
ncdf_attput,ncid,tempid,'Title','Temperature anomalies wrt. 1961-1990 mean'
ncdf_attput,ncid,tempid,'Unit','degrees C'
ncdf_attput,ncid,tempid,'missing_value',missval
;
; Switch from define mode to data mode
;
ncdf_control,ncid,/endef
;
; Output the variables
;
print,'Filling netCDF file'
ncdf_varput,ncid,vlonid,g.x
ncdf_varput,ncid,vlatid,g.y
ncdf_varput,ncid,vtimid,xtime
ncdf_varput,ncid,yrid,timey
ncdf_varput,ncid,monid,timem
ncdf_varput,ncid,tempid,temperature
;
; Close the netCDF file
;
ncdf_close,ncid
;
end
