[135] | 1 | subroutine def_var(nid,name,title,units,nbdim,dimids,nvarid,ierr) |
---|
| 2 | |
---|
| 3 | ! This subroutine defines variable 'name' in a (pre-existing and opened) |
---|
| 4 | ! NetCDF file (known from its NetCDF ID 'nid'). |
---|
| 5 | ! The number of dimensions 'nbdim' of the variable, as well as the IDs of |
---|
| 6 | ! corresponding dimensions must be set (in array 'dimids'). |
---|
| 7 | ! Upon successfull definition of the variable, 'nvarid' contains the |
---|
| 8 | ! NetCDF ID of the variable. |
---|
| 9 | ! The variables' attributes 'title' (Note that 'long_name' would be more |
---|
| 10 | ! appropriate) and 'units' are also set. |
---|
| 11 | |
---|
| 12 | implicit none |
---|
| 13 | |
---|
| 14 | #include "netcdf.inc" |
---|
| 15 | |
---|
| 16 | integer,intent(in) :: nid ! NetCDF file ID |
---|
| 17 | character(len=*),intent(in) :: name ! the variable's name |
---|
| 18 | character(len=*),intent(in) :: title ! 'title' attribute of variable |
---|
| 19 | character(len=*),intent(in) :: units ! 'units' attribute of variable |
---|
| 20 | integer,intent(in) :: nbdim ! number of dimensions of the variable |
---|
| 21 | integer,dimension(nbdim),intent(in) :: dimids ! NetCDF IDs of the dimensions |
---|
| 22 | ! the variable is defined along |
---|
| 23 | integer,intent(out) :: nvarid ! NetCDF ID of the variable |
---|
| 24 | integer,intent(out) :: ierr ! returned NetCDF staus code |
---|
| 25 | |
---|
| 26 | ! 1. Switch to NetCDF define mode |
---|
| 27 | ierr=NF_REDEF(nid) |
---|
| 28 | |
---|
| 29 | print*,'in def_var.F90, dimids=' |
---|
| 30 | print*,dimids |
---|
| 31 | |
---|
| 32 | ! 2. Define the variable |
---|
| 33 | #ifdef NC_DOUBLE |
---|
| 34 | ierr = NF_DEF_VAR (nid,adjustl(name),NF_DOUBLE,nbdim,dimids,nvarid) |
---|
| 35 | #else |
---|
| 36 | ierr = NF_DEF_VAR (nid,adjustl(name),NF_FLOAT,nbdim,dimids,nvarid) |
---|
| 37 | #endif |
---|
| 38 | if(ierr/=NF_NOERR) then |
---|
| 39 | write(*,*) "def_var: Failed defining variable "//trim(name) |
---|
| 40 | write(*,*) NF_STRERROR(ierr) |
---|
| 41 | stop "" |
---|
| 42 | endif |
---|
| 43 | |
---|
| 44 | ! 3. Write attributes |
---|
| 45 | ierr=NF_PUT_ATT_TEXT(nid,nvarid,"title",& |
---|
| 46 | len_trim(adjustl(title)),adjustl(title)) |
---|
| 47 | if(ierr/=NF_NOERR) then |
---|
| 48 | write(*,*) "def_var: Failed writing title attribute for "//trim(name) |
---|
| 49 | write(*,*) NF_STRERROR(ierr) |
---|
| 50 | stop "" |
---|
| 51 | endif |
---|
| 52 | |
---|
| 53 | ierr=NF_PUT_ATT_TEXT(nid,nvarid,"units",& |
---|
| 54 | len_trim(adjustl(units)),adjustl(units)) |
---|
| 55 | if(ierr/=NF_NOERR) then |
---|
| 56 | write(*,*) "def_var: Failed writing units attribute for "//trim(name) |
---|
| 57 | write(*,*) NF_STRERROR(ierr) |
---|
| 58 | stop "" |
---|
| 59 | endif |
---|
| 60 | |
---|
| 61 | ! 4. Switch out of NetCDF define mode |
---|
| 62 | ierr = NF_ENDDEF(nid) |
---|
| 63 | |
---|
| 64 | end |
---|