! Copyright (C) TOYODA Eizi, 2000.  All rights reserved.
! gtprint - 󎚃c[

program gtprint
    use gtool
    use dc_trace, only: setdebug
    implicit none
    character(STRING):: argument, attrname, fn, ior, v
    character(STRING):: varname
    character(STRING):: value
    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, trim(varname))
            call put_line(var)
            call Close(var)
        else
            call UrlSplit(argument, file=fn, var=v, iorange=ior)
            varname = UrlMerge(file=fn, var=v, iorange=ior, attr="")
            call Open(var, varname)
            call get_attr(var, trim(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, 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
