!  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 ChemShellLSDaltonModule

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

    private

    public register_lsdalton, interface_lsdalton, lsdalton_wrap
    public PyFrag, PyShells, nshells

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

    integer(c_int) :: c_debug
    integer(c_int) :: lsdalton_handle
    integer        :: lsdalton_task

    contains

      
    subroutine register_lsdalton(debug) bind(c, name="f_register_lsdalton")

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

        type(c_funptr) :: lsdalton_pointer

        c_debug = debug

        lsdalton_pointer = c_funloc(lsdalton_wrap)
        lsdalton_handle = chemsh_parallel%get_function_handle(lsdalton_pointer)

    endsubroutine register_lsdalton

    ! called by master process only
    subroutine interface_lsdalton(fragPtr) bind(c)
 
        implicit none
 
        type(PyType)  , intent(in) :: fragPtr
 
        integer                    :: ierror
        type(PyType)  , pointer    :: shellsPtr
 
        lsdalton_task = 0 !task 
 
        ! 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(lsdalton_handle, c_debug)
        else
           ierror = lsdalton_wrap()
        endif
 
        deallocate(PyFrag, PyShells)
 
    endsubroutine interface_lsdalton

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

        call lsdalton()

!TWKDEBUG
        ierror = 0

    endfunction lsdalton_wrap

endmodule ChemShellLSDaltonModule

