! Copyright (C) TOYODA Eizi, 2000.  All rights reserved.
! gtprint - °õ»ú¥Ä¡¼¥ë

program gtprint
    use gtool
    use dc_trace, only: setdebug
    implicit none
    type(VSTRING):: argument
    type(VSTRING):: attrname, fn, ior, v
    character(STRING):: value
    character(STRING):: varname
    type(GT_VARIABLE):: var
    integer:: i
    integer:: showcount = 0
continue
    do, i = 1, GtArgCount()
        call GtArgGet(i, argument)
	if (argument == "-debug") then
	    call setdebug
	    cycle
	endif
        call UrlSplit(argument, attr=attrname)
        if (attrname == '') then
            varname = argument
            call Open(var, varname)
            call put_line(var)
            call Close(var)
        else
            call UrlSplit(argument, file=fn, var=v, iorange=ior)
            varname = UrlMerge(fn, v, iorange=ior)
            call Open(var, varname)
            call get_attr(var, vchar(attrname, len(attrname)), value)
            call printq(value)
            call Close(var)
        endif
        showcount = showcount + 1
    enddo
    if (showcount == 0) then
        write(*, *) 'usage: gtprint [varname|attrname] ...'
    endif
contains

    subroutine printq(str)
        character(*), intent(in):: str
        character(len(str) * 3):: buf
        integer:: i, j, imax, c
        character(*), parameter:: escape = "0123456abtnvfr"
        j = 1
        do, i = 1, len_trim(str)
            select case(iachar(str(i:i)))
            case(0:13)
                c = iachar(str(i:i)) + 1
                buf(j: j+1) = achar(92) // escape(c:c)
                j = j + 2
            case(27)
                buf(j: j+1) = achar(92) // 'e'
                j = j + 2
            case(34, 39, 92)
                buf(j: j+1) = achar(92) // str(i:i)
                j = j + 2
            case (14:26, 28:31, 127:)
                buf(j: j+1) = achar(92) // 'x'
		write(buf(j+2: j+2), "(Z2)") iachar(str(i:i))
                if (buf(j+2: j+2) == ' ') &
                    buf(j+2: j+2) = '0'
		j = j + 4
            case default
                buf(j:j) = str(i:i)
                j = j + 1
            end select
        enddo
        write(*, '(A)') buf(1: j-1)
    end subroutine

end program
