! Copyright (C) GFD Dennou Club, 2000.  All rights reserved.
! gtcopy - 変数複写ツール

! 書式
!   gtcopy 変数名 出力変数名
!   gtcopy 変数名 変数名 ... 出力ファイル名

program gtcopy
    use gtool
    use dc_trace, only: setdebug
    implicit none
    character(string):: source, dest, dest_f, dest_v, arg
    integer:: i, argc
    argc = GtArgCount()

    i = 1
    do, while (i <= argc)
        call GtArgGet(i, arg)
        if (arg == '-debug') then
            call setdebug()
        else
            exit
        endif
        i = i + 1
    enddo

    if (i + 1 > argc) then
        print *, "usage: gtcopy source ... dest"
        stop
    endif

    call GtArgGet(argc, dest)
    if (i + 1 == argc) then
        call GtArgGet(argc - 1, source)
        call do_copy(source, dest)
    else
        call UrlSplit(dest, file=dest_f)
        do, while (i <= argc - 1)
            call GtArgGet(i, source)
            call UrlSplit(source, var=dest_v)
            dest = UrlMerge(file=dest_f, var=dest_v)
            call do_copy(source, dest)
            i = i + 1
        enddo
    endif

contains

    subroutine do_copy(source, dest)
        character(len=*), intent(in):: source
        character(len=*), intent(in):: dest
        type(GT_VARIABLE):: vSource
        type(GT_VARIABLE):: vDest
        call Open(vSource, url=source)
        call Create(vDest, url=dest, copyfrom=vSource, copyvalue=.TRUE.)
        call Close(vSource)
        call Close(vDest)
    end subroutine

end program
