! $Id$
module nf95_get_att_m

  implicit none

  interface nf95_get_att
     module procedure nf95_get_att_text
  end interface

  private
  public nf95_get_att

contains

  subroutine nf95_get_att_text(ncid, varid, name, values, ncerr)

    use netcdf, only: nf90_get_att, nf90_inquire_attribute, nf90_noerr
    use handle_err_m, only: handle_err

    integer,                          intent( in) :: ncid, varid
    character(len = *),               intent( in) :: name
    character(len = *),               intent(out) :: values
    integer, intent(out), optional:: ncerr

    ! Variable local to the procedure:
    integer ncerr_not_opt
    integer att_len

    !-------------------

    ! Check that the length of "values" is large enough:
    ncerr_not_opt = nf90_inquire_attribute(ncid, varid, name, len=att_len)
    call handle_err("nf95_get_att_text nf90_inquire_attribute " &
         // trim(name), ncerr_not_opt, ncid, varid)
    if (len(values) < att_len) then
       print *, "nf95_get_att_text"
       print *, "varid = ", varid
       print *, "attribute name: ", name
       print *, 'length of "values" is not large enough'
       print *, "len(values) = ", len(values)
       print *, "number of characters in attribute: ", att_len
       stop 1
    end if

    values = "" ! useless in NetCDF version 3.6.2 or better
    ncerr_not_opt = nf90_get_att(ncid, varid, name, values)
    if (present(ncerr)) then
       ncerr = ncerr_not_opt
    else
       call handle_err("nf95_get_att_text", ncerr_not_opt, ncid, varid)
    end if

    if (att_len >= 1 .and. ncerr_not_opt == nf90_noerr) then
       ! Remove null terminator, if any:
       if (iachar(values(att_len:att_len)) == 0) values(att_len:att_len) = " "
    end if

  end subroutine nf95_get_att_text

end module nf95_get_att_m
