! Copyright (C) GFD Dennou Club, 2000.  All rights reserved

subroutine ANVarGetAttrSC(var, name, value, default)
    use dc_string
    use an_types, only: AN_VARIABLE
    use netcdf_f77
    use dc_url, only: GT_PLUS
    use dc_error
    implicit none
    type(AN_VARIABLE), intent(in):: var
    character(len = *), intent(in):: name
    type(VSTRING), intent(out):: value
    character(len = *), intent(in), optional:: default
    character(len = 64):: buffer
    double precision, allocatable:: dbuf(:)
    integer, allocatable:: ibuf(:)
    character, allocatable:: cbuf(:)
    integer:: xtype, stat, attrlen, i
continue
    if (name(1:1) == GT_PLUS) then
        stat = nf_inq_att(var%fileid, NF_GLOBAL, name(2:), xtype=xtype, len=attrlen)
    else
        stat = nf_inq_att(var%fileid, var%varid, name, xtype=xtype, len=attrlen)
    endif
    if (stat /= NF_NOERR) goto 800
    if (xtype == NF_CHAR .and. attrlen <= len(buffer)) then
        if (name(1:1) == GT_PLUS) then
            stat = nf_get_att_text(var%fileid, NF_GLOBAL, name(2:), buffer)
        else
            stat = nf_get_att_text(var%fileid, var%varid, name, buffer)
        endif
        if (stat /= NF_NOERR) goto 800
        value = buffer(1: attrlen)
    else if (xtype == NF_CHAR) then
        ! UNIDATA NetCDF ライブラリでは文字列引数の長さを
        ! まったく取得していないので先頭が結合していれば OK のはず
        allocate(cbuf(attrlen))
        if (name(1:1) == GT_PLUS) then
            stat = nf_get_att_text(var%fileid, NF_GLOBAL, name(2:), cbuf(1))
        else
            stat = nf_get_att_text(var%fileid, var%varid, name, cbuf(1))
        endif
        if (stat /= NF_NOERR) goto 800
        value = ""
        do, i = 1, attrlen
            value = value // cbuf(i)
        enddo
        value = value // cbuf(i)
        deallocate(cbuf)
    else if (xtype == NF_DOUBLE .or. xtype == NF_FLOAT) then
        allocate(dbuf(attrlen))
        if (name(1:1) == GT_PLUS) then
            stat = nf_get_att_double(var%fileid, NF_GLOBAL, name(2:), dbuf)
        else
            stat = nf_get_att_double(var%fileid, var%varid, name, dbuf)
        endif
        if (stat /= NF_NOERR) goto 800
        value = toString(dbuf)
        deallocate(dbuf)
    else
        allocate(ibuf(attrlen))
        if (name(1:1) == GT_PLUS) then
            stat = nf_get_att_int(var%fileid, NF_GLOBAL, name(2:), ibuf)
        else
            stat = nf_get_att_int(var%fileid, var%varid, name, ibuf)
        endif
        if (stat /= NF_NOERR) goto 800
        value = toString(ibuf)
        deallocate(ibuf)
    endif
    return
    ! デフォルト処理
800 continue
    value = ""
    if (present(default)) value = default
    return
end subroutine
