module wdfile
  use iso_c_binding
  use mpi
  implicit none
  
contains

  
!function mkdir(path,mode) bind(c,name="mkdir")
!  use iso_c_binding
!  integer(c_int) :: mkdir
!  character(kind=c_char,len=1) :: path(*)
!  integer(c_int16_t), value :: mode
!end function mkdir

  
subroutine fwrite(path, data, nx, ny, nz, comm)

  character*(*) :: path 
  integer :: nx, ny, nz
  double precision, asynchronous, dimension(0:nx,0:ny,0:nz) :: data

  integer :: comm, ierr,  rank, size, rlen, ii
  integer :: iounit = 10
  character(len=6) :: crank
  character(len=50) :: filename
  character(len=6) :: dir
  character(len=MPI_MAX_PROCESSOR_NAME) :: hostname
  real* 8  :: start, finish
  integer :: idir  
  
  call MPI_Comm_size(comm, size, ierr)
  call MPI_Comm_rank(comm, rank, ierr)


  write(crank, "(I0.6)") rank
  dir = crank
  filename = trim(path)//crank
!  filename  = trim(dir)//'/'//filename

  open(file=filename, unit=iounit, asynchronous='yes', access='stream')

  call MPI_Get_processor_name(hostname, rlen, ierr)
  write(*,*) 'node : ', hostname, 'opening  file: ', filename 

  call MPI_Barrier(comm, ierr)  
  
  do ii = 0, size
     if ( rank == ii ) then
        !start= MPI_Wtime()
        write(unit=iounit) data(1:nx, 1:ny, 1:nz)
        close(iounit)        
        !finish = MPI_Wtime()
        !write(6,'(i5,f7.4)') rank, finish - start
     else
     end if
  end do
  
end subroutine fwrite

subroutine fdelete(path, comm)

  implicit none

  character *(*) :: path
  integer, parameter :: iounit = 15
  integer :: comm, ierr, rank, size
  integer :: stat
  character(len=6) :: crank
  character(len=50) :: filename
  real*8    start, finish

  call MPI_Comm_size(comm, size, ierr)
  call MPI_Comm_rank(comm, rank, ierr)

  write(crank, "(I0.6)") rank
  filename = trim(path)//crank

  open(unit=iounit, iostat=stat, file=filename, status='old')
  if (stat.eq.0) close(unit=iounit, status='delete')

end subroutine fdelete

character(len=20) function str(k)
!   "Convert an integer to string."
    integer, intent(in) :: k
    write (str, *) k
    str = adjustl(str)
end function str

end module wdfile 
