!  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/>.

module ChemShellGULPModule

    use, intrinsic :: iso_c_binding
    use DL_PY2F
    use ChemShellParallelModule, only : chemsh_parallel

    private

    public register_gulp, interface_gulp, gulp_wrap
    public PyFrag, PyShells, nshells

    type(dictType) , pointer :: PyFrag, PyShells
    integer                  :: nshells

    integer(c_int) :: c_debug
    integer(c_int) :: gulp_handle

    contains

      
    subroutine register_gulp(debug) bind(c, name="f_register_gulp")

        integer(c_int), intent(in) :: debug

        type(c_funptr) :: gulp_pointer

        c_debug = debug

        gulp_pointer = c_funloc(gulp_wrap)
        gulp_handle = chemsh_parallel%get_function_handle(gulp_pointer)

    endsubroutine register_gulp
    ! called by master process only
    integer(c_int) function interface_gulp(fragPtr) result(ierror) bind(c)
 
        implicit none
 
        type(PyType)  , intent(in) :: fragPtr
 
        type(PyType)  , pointer    :: shellsPtr

        ierror = 1
 
        ! set up dict of fragObj
        allocate(PyFrag, source=ptr2dict(fragPtr))
        call PyFrag%get('shells', shellsPtr)
 
        ! set up dict of shellsObj and save nshells
        allocate(PyShells, source=ptr2dict(shellsPtr))
        call PyShells%get('npts', nshells)
 
        if (chemsh_parallel%is_parallel()) then
            ierror = chemsh_parallel%exec_function(gulp_handle, c_debug)
        else
            ierror = gulp_wrap()
        endif
 
        call PyFrag%finalise()
        call PyShells%finalise()
        deallocate(PyFrag, PyShells)

    endfunction interface_gulp
    ! also called by replica processes
    integer(kind=4) function gulp_wrap() result(ierror)

        use ChemShellParallelModule, only : chemsh_parallel

        integer(kind=4) :: gulp_linked, communicator

        gulp_linked = 1

        communicator = chemsh_parallel%comm_subset

        ! YL 24/04/2020: can't catch ierror because GULP "stop"s when there's an error
        if(chemsh_parallel%is_subset()) then
            call gulpmain(ierror, gulp_linked, communicator)
        endif

    endfunction gulp_wrap

endmodule ChemShellGULPModule

