subroutine write_esri_ascii_3d_file(filename_ascii_sub, ncols_sub, nrows_sub, nblocks_sub, cellsize_sub, val_array, x_array, y_array)
character(*) :: filename_ascii_sub
integer :: ncols_sub, nrows_sub, nblocks_sub
real :: cellsize_sub
real :: val_array(ncols_sub,nrows_sub,nblocks_sub)
real :: x_array(ncols_sub,nrows_sub)
real :: y_array(ncols_sub,nrows_sub)
! Local variables
integer :: ii, jj, tt
real :: xllcorner
real :: yllcorner
real :: NODATA_value = -999.0
integer :: unit_in = 20
character(len=:), allocatable :: fmt
xllcorner = x_array(1,1) - cellsize_sub/2.0
yllcorner = y_array(1,1) - cellsize_sub/2.0
open(unit_in, file=filename_ascii_sub, access='sequential', form='formatted', status='unknown')
write(unit_in,*) 'ncols', ncols_sub
write(unit_in,*) 'nrows', nrows_sub
if (nblocks_sub .gt. 1) write(unit_in,*) 'nblocks', nblocks_sub
write(unit_in,*) 'xllcorner', xllcorner
write(unit_in,*) 'yllcorner', yllcorner
write(unit_in,*) 'cellsize', cellsize_sub
write(unit_in,*) 'NODATA_val', NODATA_value
do tt = 1, nblocks_sub
do jj = nrows_sub, 1, -1
write(fmt,'(A,I0,A)') '(', ncols_sub, 'es12.3)'
write(unit_in,fmt) (val_array(ii,jj,tt), ii = 1, ncols_sub)
end do
end do
close(unit_in)
end subroutine write_esri_ascii_3d_file