!> @file
!!  Routines which handles the structure DFT_wavefunction related to the Kohn-Sham wavefunctions
!! @author
!!    Copyright (C) 2013-2015 BigDFT group
!!    This file is distributed under the terms of the
!!    GNU General Public License, see ~/COPYING file
!!    or http://www.gnu.org/copyleft/gpl.txt .
!!    For the list of contributors, see ~/AUTHORS


subroutine kswfn_free_scf_data(KSwfn, freePsit)
  use module_types
  use memory_profiling
  use diis_sd_optimization, only: deallocate_diis_objects
  use module_bigdft_arrays
  implicit none
  !Arguments
  type(DFT_wavefunction), intent(inout) :: KSwfn
  logical, intent(in) :: freePsit
  !Local variables
  character(len = *), parameter :: subname = "kswfn_free_scf_data"

  ! Clean KSwfn parts only needed in the SCF loop.
  call deallocate_diis_objects(KSwfn%diis)
  call f_free_ptr(KSwfn%hpsi)
  if (freePsit) then
     call f_free_ptr(KSwfn%psit)
  else
     nullify(KSwfn%psit)
  end if
end subroutine kswfn_free_scf_data

subroutine kswfn_init_comm(wfn, dpbox, iproc, nproc, nspin, imethod_overlap)
  use module_dpbox, only: denspot_distribution
  use module_bigdft_profiling
  use module_types
  !use module_interfaces, except_this_one => kswfn_init_comm
  use communications_base, only: comms_linear_null
  use communications_init, only: init_comms_linear, init_comms_linear_sumrho, &
                                 initialize_communication_potential
  use yaml_output
  implicit none
  integer, intent(in) :: iproc, nproc, nspin, imethod_overlap
  type(DFT_wavefunction), intent(inout) :: wfn
  type(denspot_distribution), intent(in) :: dpbox

  call f_routine(id='kswfn_init_comm')

  ! Nullify all pointers
  nullify(wfn%psi)
  nullify(wfn%hpsi)
  nullify(wfn%psit)
  nullify(wfn%psit_c)
  nullify(wfn%psit_f)
  nullify(wfn%gaucoeffs)

  call nullify_paw_objects(wfn%paw)

  call initialize_communication_potential(iproc, nproc, dpbox%nscatterarr, &
       & wfn%orbs, wfn%lzd, dpbox%nrhodim, wfn%comgp)

  !call nullify_comms_linear(wfn%collcom)
  !call nullify_comms_linear(wfn%collcom_sr)
  wfn%collcom=comms_linear_null()
  wfn%collcom_sr=comms_linear_null()

  call init_comms_linear(iproc, nproc, imethod_overlap, wfn%npsidim_orbs, wfn%orbs, wfn%lzd, nspin, wfn%collcom)
  if (iproc==0) then
      call yaml_map('Normal locregs communication initialized',.true.)
  end if

  call init_comms_linear_sumrho(iproc, nproc, wfn%lzd, wfn%orbs, nspin, dpbox%nscatterarr, wfn%collcom_sr)
  if (iproc==0) then
      call yaml_map('Normal locregs sumrho communication initialized',.true.)
  end if

  call f_release_routine()

END SUBROUTINE kswfn_init_comm
