! Pass command-line arguments from Fortran to C

!  Copyright (C) 2017 The authors of Py-ChemShell
!
!  This file is part of Py-ChemShell.
!
!  Py-ChemShell is free software: you can redistribute it and/or modify
!  it under the terms of the GNU Lesser General Public License as
!  published by the Free Software Foundation, either version 3 of the
!  License, or (at your option) any later version.
!
!  Py-ChemShell is distributed in the hope that it will be useful,
!  but WITHOUT ANY WARRANTY; without even the implied warranty of
!  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!  GNU Lesser General Public License for more details.
!
!  You should have received a copy of the GNU Lesser General Public
!  License along with Py-ChemShell.  If not, see
!  <http://www.gnu.org/licenses/>.

subroutine f_iargc(num) bind(c, name="f_iargc")

    use iso_c_binding

    implicit none

    integer(c_int), intent(out) :: num
    num = command_argument_count()
    ! Argument 0 is counted in argc
    num = num + 1

endsubroutine f_iargc
integer(c_int) function getNumArgs() result(argc) bind(c, name="chemsh_f_get_argc")

    use iso_c_binding

    implicit none

    argc = command_argument_count() + 1

endfunction getNumArgs
subroutine getArgs(iarg, maxlen, arglen, c_arg) bind(c, name="chemsh_f_get_argv")

    use iso_c_binding

    implicit none

    integer(c_int)   , intent(in)  :: iarg
    integer(c_int)   , intent(in)  :: maxlen
    integer(c_int)   , intent(out) :: arglen
    character(c_char), intent(out) :: c_arg(maxlen)

    integer                        :: i, f_iarg, f_arglen
    character(len=maxlen)          :: f_arg
  
    f_iarg = iarg
    call get_command_argument(f_iarg, f_arg, f_arglen)
    arglen = f_arglen

    do i = 1, arglen
        c_arg(i) = f_arg(i:i)
    enddo
    ! c_arg(i + 1) = c_null_char

endsubroutine getArgs

