subroutine output_array_to_csv(file_id, array, space_ix, time_label, space_label)
! Write 2D real array to csv in file_id with a space and time index
! Both space_ix and time_label must be either the same length as array or of length 1
! to repeat over all rows.
integer, intent(in) :: file_id
real, intent(in) :: array(:, :)
integer, intent(in), optional :: space_ix(:)
character(len=*), intent(in) :: time_label(:)
character(len=*), intent(in), optional :: space_label(:)
character(len=identifier_max_length) :: tsfmt
integer :: sh(2), i, ii, lens, lent
! Check input
if (rank(array) /= 2) call log_error("output_array_to_csv", &
"output_array_to_csv array is not 2D.")
sh = shape(array)
lens = 1
if (present(space_ix)) then
lens = size(space_ix)
if (lens /= sh(2) .and. lens /= 1) call log_error("output_array_to_csv", &
"space_ix not the right length.")
else if (present(space_label)) then
lens = size(space_label)
if (lens /= sh(2) .and. lens /= 1) &
call log_error("output_array_to_csv", "space_label not the right length.")
else
call log_error("output_array_to_csv", "space_ix or space_label have to be given.")
end if
lent = size(time_label)
if (lent /= sh(2) .and. lent /= 1) &
call log_error("output_array_to_csv", "time_label not the right length or 1.")
! Time, space format
tsfmt = "(a, ',', "//trim(output_space_index_format)//", ',')"
do i = 1, sh(2)
! Time, space indeces
if (present(space_ix)) then
write(file_id, tsfmt, advance="no") time_label(min(i, lent)), &
space_ix(min(i, lens))
else
write(file_id, "(a, ', ', a, ', ')", advance="no") time_label(min(i, lent)), &
trim(space_label(min(i, lens)))
end if
do ii = 1, sh(1)-1
write(file_id, "("//trim(output_float_format)//", ',')", advance="no") &
array(ii, i)
end do
! Last column without ,
write(file_id, "("//trim(output_float_format)//")") array(sh(1), i)
end do
end subroutine output_array_to_csv