
module toolbox

  integer, parameter, private :: kind = selected_real_kind(15)

contains

  function arith(x)

    real(kind) :: arith
    real(kind), dimension(:), intent(in) :: x

    arith = sum(x) / size(x)

  end function arith

  function stddev(r)

    real(kind) :: stddev
    real(kind), dimension(:), intent(in) :: r
    integer :: n

    n = size(r)
    if( n > 1 ) then
       stddev = sqrt(sum(r**2) / (n - 1))
    else
       stddev = 0
    end if

  end function stddev

  subroutine histogram(x, xmin, xmax, nbines, filename)

    real(kind), dimension(:), intent(in) :: x
    real(kind), intent(in) :: xmin, xmax
    integer, intent(in) :: nbines
    character(len=*), intent(in) :: filename
    integer, dimension(:), allocatable :: hist
    real(kind) :: d,t,s
    integer :: n,l,nbins

    if( nbines < 1 ) then
       nbins = int(log(real(size(x)))/0.7) + 1
    else
       nbins = nbines
    end if
    nbins = nbins / 2

    allocate(hist(-nbins:nbins))

    d = (xmax - xmin) / (2*nbins + 1)
    t = (xmax + xmin) / 2
    hist = 0
    do l = 1, size(x)
       n = nint((x(l) - t) / d)
       if( -nbins <= n .and. n <= nbins ) then
          hist(n) = hist(n) + 1
       end if
    end do

    s = sum(hist) * d
    open(1,file=filename)
    do n = -nbins,nbins
       write(1,*) (n*d + t), hist(n)/s
    end do
    close(1)

    deallocate(hist)

  end subroutine histogram

end module toolbox
