# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module R_write_mod

use R_mod
implicit none

contains

!----------------------------------------------------------------
! Write out image
  subroutine image_write(X,k,zz)
    type(imag), intent(in) :: X
    integer, intent(in) :: k,zz
    integer:: i1,i2,i3,i4,i5,ierr,n_dim_cube,n
    integer,dimension(5)::n_cube,n_wind,f_wind,j_wind




    if(down%image_freqs) return

    n=zz
    n_dim_cube=5
    n_cube=(/ X%amx%n, X%amy%n,X%ahx%n,X%ahy%n,X%az%n /)
    j_wind=(/1 ,1 ,1 ,1 ,1 /)
    n_wind=(/down%ax%n,down%ay%n,1 ,1 ,1 /)
    if (X%esize==4)then
       do i5=1,n
          do i4=1,X%ahy%n
             do i3=1,X%ahx%n
                do i2=1,down%ay%n
                   do i1=1,down%ax%n
                      tmpr(i1,i2)=real(X%bin(i1,i2,i3,i4,i5))
                   end do
                end do
                f_wind=(/X%indx -1,X%indy -1,i3-1,i4-1,i5-1+k /)
                ierr=srite_window(X%tag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,X%esize,tmpr(1,1))
                if (ierr.lt.0) then
                   write(run%io,*) 'srite_window return value=',ierr
                   call seperr("Baddness in image_write (real)")
                end if
             end do
          end do
       end do
    else
       do i5=1,n
          do i4=1,X%ahy%n
             do i3=1,X%ahx%n
                do i2=1,down%ay%n
                   do i1=1,down%ax%n
                      tmpc(i1,i2)=(X%bin(i1,i2,i3,i4,i5))
                   end do
                end do
                f_wind=(/X%indx -1, X%indy -1, i3-1, i4-1, i5-1+k/)
                ierr=srite_window(X%tag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,X%esize,tmpc(1,1))
                if (ierr.lt.0) then
                   write(run%io,*) 'srite_window return value=',ierr
                   call seperr("Baddness in image_write (complex)")
                end if
             end do
          end do
       end do
    end if




  end subroutine image_write

end module R_write_mod
