! See copyright notice in the COPYRIGHT file.
!******************************************************************************!
!> In this module we collect routines  and type definitions related to 
!! statistics for the runtime of the code. 
!!
!!
module mus_statistics_module
  ! include treelm modules
  use mpi
  use tem_logging_module,  only: logUnit

  implicit none
  private

  public :: mus_statistics_type
  public :: mus_calc_commAmount

  !> runtime statistics
  !! this includes memory consumption, amount of data to communciate, 
  !! runtimes etc.
  type mus_statistics_type

    !> number of links to communicate
    !! Subset of nLinks_total
    integer :: nLinks_comm = 0

    !> number of total links available which theoretically can be communciated
    integer :: nLinks_total = 0

    !> Mean number of neighbor processes to which one process needs to send
    integer :: nProcs_send = 0

  end type mus_statistics_type

contains

! ****************************************************************************** !
  !> Calculate the number of links to be communicated
  !!
  subroutine mus_calc_commAmount( stat, comm, nProcs )
    ! ---------------------------------------------------------------------------
    !> runtime statistic
    type( mus_statistics_type), intent(inout) :: stat
    !>
    integer, intent(in) :: comm, nProcs
    ! ---------------------------------------------------------------------------
    integer :: iErr
    integer :: nLinks_comm, nLinks_total
    ! ---------------------------------------------------------------------------

    if ( nProcs > 1 ) then
      call mpi_reduce( stat%nLinks_comm, nLinks_comm, 1, mpi_integer,   &
        &              mpi_sum, 0, comm, iErr )
      call mpi_reduce( stat%nLinks_total, nLinks_total, 1, mpi_integer, &
        &              mpi_sum, 0, comm, iErr )
      stat%nLinks_comm  = nLinks_comm
      stat%nLinks_total = nLinks_total

      if( nLinks_total > 0 ) then
        write(logUnit(3),"(A,I0)") "Amount of message per proc: ", nLinks_comm/nProcs
        write(logUnit(1),"(A,F6.2)") 'Communication amount compressed to [%]:',&
          &          real( nLinks_comm )/real( nLinks_total ) * 100.0
      endif
    endif

  end subroutine mus_calc_commAmount
! ****************************************************************************** !



end module mus_statistics_module
! ****************************************************************************** !
