program blkio
  call test1
  call test2
end program

subroutine test2
  use n3blkio
  use n3error, only: die
  implicit none
  integer:: h, ios, buf(8), i

  print *, '--- test 2: BLOCK write, BLOCK read ---'

  do, i = 1, 8
    buf(i) = i * 7 + 1
  enddo

  call blkio_open(file='zzz.dat', flags=O_RDWR, blkl=8, handle=h)
  if (h < 0) call die
  call blkio_write(handle=h, blk=1, buf=buf, iostat=ios)
  if (ios /= 0) call die
  call blkio_close(handle=h, iostat=ios)
  if (ios /= 0) call die

  buf(:) = 0

  call blkio_open(file='zzz.dat', flags=O_RDONLY, blkl=5, handle=h)
  if (h < 0) call die
  print *, 'handle=', h
  call blkio_read(handle=h, blk=1, buf=buf, iostat=ios)
  print *, 'blk=1, iostat=', ios
  if (ios /= 0) call die
  if (any(buf(1:5) /= (/8, 15, 22, 29, 36/))) then
    print *, 'roundtrip value error :', buf(1:5)
    stop 16
  endif
  call blkio_read(handle=h, blk=2, buf=buf, iostat=ios)
  print *, 'blk=2, iostat=', ios
  if (ios /= 2) call die
  if (any(buf(1:3) /= (/43, 50, 57/))) then
    print *, 'roundtrip value error :', buf(1:5)
    stop 16
  endif
  call blkio_close(handle=h, iostat=ios)
  if (ios /= 0) call die

  open(10, file='zzz.dat', form='UNFORMATTED', access='DIRECT', recl=1)
  close(10, status='DELETE')

end subroutine

subroutine test1
  use n3blkio
  use n3error, only: die
  implicit none
  integer:: h, ios, buf(5)

  print *, '--- test 1: SEQUENTIAL write, BLOCK read ---'

  open(10, file='zzz.dat', form='UNFORMATTED', access='SEQUENTIAL')
  write(10) (/1, 2, 3, 4/)
  close(10)

  call blkio_open(file='zzz.dat', flags=O_RDONLY, blkl=5, handle=h)
  if (h < 0) call die
  print *, 'handle=', h
  call blkio_read(handle=h, blk=1, buf=buf, iostat=ios)
  print *, 'blk=1, iostat=', ios
  if (ios /= 0) call die
  call blkio_read(handle=h, blk=2, buf=buf, iostat=ios)
  print *, 'blk=2, iostat=', ios
  if (ios /= 2 .and. ios /= 4) call die
  call blkio_close(handle=h, iostat=ios)
  if (ios < 0) call die

  open(10, file='zzz.dat', form='UNFORMATTED', access='SEQUENTIAL')
  close(10, status='DELETE')

end subroutine
