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

! 外部型表現が存在する処理系に関しては型を示す文字列を、
! そうでない処理系に関しては空文字列を返す。

subroutine GTVarInquireV(var, xtype, ndims, alldims, name, url, allcount, size)
    use gtdata_types, only: GT_VARIABLE
    use dc_string, only: VSTRING
    use an_generic, only: inquire
    type(GT_VARIABLE), intent(in):: var
    type(VSTRING), intent(out), optional:: xtype, name, url
    integer, intent(out), optional:: ndims, alldims, size, allcount
    if (associated(var%an)) then
        call inquire(var%an, xtype=xtype, ndims=ndims, alldims=alldims, &
            & name=name, url=url, allcount=allcount)
        if (present(size)) size = GTVarSize(var)
    endif
contains

    integer function GTVarSize(var) result(result)
        use gtdata_types, only: GT_VARIABLE
        use gtdata_generic, only: Inquire, Get_Slice
        implicit none
        type(GT_VARIABLE), intent(in):: var
        integer, allocatable:: ctr(:)
        integer:: ndims, i
        call inquire(var, alldims=ndims)
        if (ndims >= 1) then
            allocate(ctr(ndims))
            do, i = 1, ndims
                call get_slice(var, i, count=ctr(i))
            end do
            ctr = max(ctr, 1)
            result = product(ctr(:))
            deallocate(ctr)
        else if (ndims == 1) then
            result = 1
        else
            result = 1
        endif
    end function
end subroutine

! 文字数が合わなければ当然変なことが起こるが、気にしない。
subroutine GTVarInquire(var, xtype, name, url)
    use gtdata_types, only: GT_VARIABLE
    use dc_string, only: VSTRING, assignment(=)
    use gtdata_generic, only: inquire
    type(GT_VARIABLE), intent(in):: var
    character(len=*), intent(out), optional:: xtype, name, url
    type(VSTRING):: s_xtype, s_name, s_url
    if (present(xtype)) then
        call inquire(var, xtype=s_xtype)
        xtype = s_xtype
    endif
    if (present(name)) then
        call inquire(var, name=s_name)
        name = s_name
    endif
    if (present(url)) then
        call inquire(var, url=s_url)
        url = s_url
    endif
end subroutine

subroutine GTVarInquireAV(var, attrname, xtype)
    use gtdata_types, only: GT_VARIABLE
    use dc_string, only: VSTRING
    use an_generic, only: inquire
    type(GT_VARIABLE), intent(in):: var
    character(len=*), intent(in):: attrname
    type(VSTRING), intent(out), optional:: xtype
    if (associated(var%an)) then
        call inquire(var%an, attrname, xtype=xtype)
    endif
end subroutine

! 文字数が合わなければ当然変なことが起こるが、気にしない。
subroutine GTVarInquireA(var, attrname, xtype)
    use gtdata_types, only: GT_VARIABLE
    use dc_string, only: VSTRING, assignment(=)
    use gtdata_generic, only: inquire
    type(GT_VARIABLE), intent(in):: var
    character(len=*), intent(in):: attrname
    character(len=*), intent(out), optional:: xtype
    type(VSTRING):: s_xtype
    if (present(xtype)) then
        call inquire(var, attrname, xtype=s_xtype)
        xtype = s_xtype
    endif
end subroutine
