function mand(z0,n)
  complex (kind=kind(1d0)) :: z,z0
  integer i,n,mand

  z=z0
  do i=1,n
    z=z*z+z0
    if (abs(z).gt.4d0) exit
  enddo

  mand=512-512*(log(real(i))/log(real(n)))
end function

module pnm
contains
  subroutine ppm_write(set,unit,name)
  integer :: i,j,k,resx,resy,unit
  integer, allocatable :: set (:,:,:)
  character(*) :: name
  character, allocatable :: line(:)

  resx=size(set,2)
  resy=size(set,3)
  allocate(line(3*resx))

  open(unit,file=name)
! NB First two bytes must be "P6"
! having an initial space will not do, so
! write(unit,*)'P3',resx,resy  is wrong 
  write(unit,'(''P6'')')
  write(unit,*) resx,resy
  write(unit,*) 255
  close(unit)

  open(unit,file=name,access='stream',position='append')
  do i=resy-1,0,-1
    do j=0,resx-1
      do k=1,3
        line(3*j+k)=char(set(k,j,i))
      enddo
    enddo
    write(unit) line
  enddo
  close(unit)

  end subroutine
end module

program mandel
  use pnm
  use mpi_f08
  implicit none

  complex (kind=kind(1d0)) :: z
  real (kind=kind(1d0)) :: x,y
  integer :: ix,iy,res,i
  integer :: pallette(3,0:512)
  integer, allocatable :: set(:,:,:)
  integer npe,mype,mand

  call mpi_init()

  call mpi_comm_rank(mpi_comm_world, mype)
  call mpi_comm_size(mpi_comm_world, npe)

  if (mype.eq.0) then
    write(*,*)'Please input resolution'
    read(*,*) res
  end if

  call mpi_bcast(res,1,MPI_INTEGER,0,MPI_COMM_WORLD)

  allocate(set(3,0:res-1,0:res-1))

  pallette(:,0)=0
  do i=1,256
    pallette(1,i)=256-i
    pallette(2,i)=256-i
    pallette(3,i)=i
  enddo
  do i=1,256
    pallette(1,256+i)=i
    pallette(2,256+i)=0
    pallette(3,256+i)=256-i
  enddo

  do ix=0,res-1
    x=-2d0+ix*3d0/(res-1)
    do iy=mype,res-1,npe
      y=-1.5d0+iy*3d0/(res-1)
      set(:,ix,iy)=pallette(:,mand(cmplx(x,y,kind(1d0)),1024))
    enddo
  enddo

  do iy=0,res-1,npe
      call mpi_gather(set(1,0,iy+mype),3*res,MPI_INTEGER, &
                      set(1,0,iy),3*res,MPI_INTEGER, &
                      0,MPI_COMM_WORLD)
  enddo

  call mpi_barrier(MPI_COMM_WORLD)

  if (mype.eq.0 ) call ppm_write(set,10,"m.ppm")

  call MPI_FINALIZE()

end
