subroutine output_kp_matrices(config_label, stem, matrices)
use util_mod, only: int_fmt, get_free_unit
integer, intent(in) :: config_label
character(7), intent(in) :: stem
real(dp), intent(in) :: matrices(:, :, :)
character(25) :: ind1, filename
integer :: i, j, k, temp_unit, nrepeats
write(ind1, '(i15)') config_label
filename = trim(trim(stem)//'.'//trim(adjustl(ind1)))
nrepeats = size(matrices, 3)
temp_unit = get_free_unit()
open(temp_unit, file=trim(filename), status='replace')
! Write all the components of the various estimates of the matrix, above and including the
! diagonal, one after another on separate lines.
do i = 1, size(matrices, 1)
do j = i, size(matrices, 2)
! Write the index of the matrix element.
write(temp_unit, '('//int_fmt(i, 0)//', "," ,'//int_fmt(j, 0)//')', advance='no') i, j
do k = 1, nrepeats
write(temp_unit, '(1x,es19.12)', advance='no') matrices(i, j, k)
end do
write(temp_unit, '()', advance='yes')
end do
end do
close(temp_unit)
end subroutine output_kp_matrices