!  Copyright (C) 2020 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 ChemShellDLMONTEModule

    use, intrinsic :: iso_c_binding
    use DL_PY2F 
    use ChemShellParallelModule
    use DLMONTEModule

    implicit none
    private

    public register_dl_monte, interface_dl_monte, dl_monte_wrap
    public PyFrag, PyShells, nshells

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

    integer :: dl_monte_task
    integer(c_int) :: c_debug
    integer(c_int) :: dl_monte_handle

    contains

      
    subroutine register_dl_monte(debug) bind(c, name="f_register_dl_monte")

        use ChemShellParallelModule, only : chemsh_parallel

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

        type(c_funptr) :: dl_monte_pointer

        c_debug = debug

        dl_monte_pointer = c_funloc(dl_monte_wrap)
        dl_monte_handle = chemsh_parallel%get_function_handle(dl_monte_pointer)

    endsubroutine register_dl_monte
    ! called by master process only
    subroutine interface_dl_monte(fragPtr, resultPtr) bind(c)
 
        use ChemShellParallelModule, only : chemsh_parallel

        implicit none
 
        type(PyType)  , intent(in) :: fragPtr
        type(PyType)  , intent(in) :: resultPtr
 
        integer                    :: ierror
        type(PyType)  , pointer    :: shellsPtr

        ! set up dict of fragObj
        allocate(PyFrag, source=ptr2dict(fragPtr))
        call PyFrag%get('npts', natoms)
        call PyFrag%get('shells', shellsPtr)
        allocate(PyResult, source=ptr2dict(resultPtr))

        ! 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(dl_monte_handle, c_debug)
        else
           ierror = dl_monte_wrap()
        endif
 
        deallocate(PyFrag, PyShells)
 
    endsubroutine interface_dl_monte


    ! also called by slave processes
    integer function dl_monte_wrap() result(ierror)

        use ChemShellParallelModule, only : chemsh_parallel

        integer                  :: itype, lenbuf, ifrom, itag
        logical                  :: opened
        integer                  :: i, shapebuff(2), nnodes, node
        integer(kind=4), pointer :: natoms_per_domain(:), global_indices_per_node(:)
        real(kind=8)   , pointer :: gradients(:,:), gbuff(:,:)

        ! size of int for GULP
        lenbuf = 4
        ifrom  = 0
        itag   = 66

        ! number of nodes per subset (rather than workgroup!)
        nnodes = chemsh_parallel%nnodes_subset
        node   = chemsh_parallel%node_subset

        ierror = chemsh_parallel%broadcast(natoms, lenbuf, ifrom)

!        allocate(gradients(3,natoms))
!        allocate(gbuff(3,natoms))
!        allocate(global_indices_per_node(natoms))
!        allocate(natoms_per_domain(nnodes))
!        gradients = 0.0
!        natoms_per_domain = 0
        
        ! share task control flag
        itype = 402

        if(chemsh_parallel%is_subset()) then
            ! cast to system integer kind
            call dl_monte(int(chemsh_parallel%comm_subset))
        endif

!        if(chemsh_parallel%is_root()) then
!            natoms_per_domain(1) = shapebuff(2)
!            do i = 1, nnodes-1
!                ierror = chemsh_parallel%receive(natoms_per_domain(i+1), lenbuf, i, itag)
!            enddo
!        else
!            ierror = chemsh_parallel%send(shapebuff(2), lenbuf, 0, itag)
!        endif
!
!        ! get the whole array of indices per node
!        if(chemsh_parallel%is_root()) then
!            do i = 1, nnodes-1
!                ierror = chemsh_parallel%receive(global_indices_per_node(sum(natoms_per_domain(1:i))+1:sum(natoms_per_domain(1:i+1))), 4*natoms_per_domain(i+1), i, itag)
!            enddo
!        endif
!
!        ierror = chemsh_parallel%broadcast(natoms_per_domain, lenbuf*nnodes, 0)
!
!        ! the root gathers the gradients
!        if(chemsh_parallel%is_root()) then
!            do i = 1, nnodes-1
!                ierror = chemsh_parallel%receive(gbuff(1:3,sum(natoms_per_domain(1:i))+1:sum(natoms_per_domain(1:i+1))), 8*3*natoms_per_domain(i+1), i, itag)
!            enddo
!        endif
!
!        ! sort the gradients according to the global indices
!        if(chemsh_parallel%is_root()) then
!            do i = 1, nnodes-1
!                gradients(1:3,global_indices_per_node(sum(natoms_per_domain(1:i))+1:sum(natoms_per_domain(1:i+1)))) = gbuff(1:3,sum(natoms_per_domain(1:i))+1:sum(natoms_per_domain(1:i+1)))
!            enddo
!        endif
!
!        if(chemsh_parallel%is_root()) then
!            call PyResult%set('gradients', gradients)
!        endif
        
!        deallocate(gradients, gbuff, natoms_per_domain, global_indices_per_node)

    endfunction dl_monte_wrap

endmodule ChemShellDLMONTEModule

