program stereogrammi
  implicit none

  integer,allocatable,dimension(:,:) :: pixmapR,pixmapG,pixmapB
  integer :: x,y,k,nx,ny
  real(kind(0.d0))::xR,xG,xB

  nx=600;ny=400  ! numero dei pixel orizzontali e verticali
  allocate(pixmapR(nx,ny),pixmapG(nx,ny),pixmapB(nx,ny))

  crea_pixmap: do x=1,100
     do y=1,400
        call RANDOM_NUMBER(xR)
        call RANDOM_NUMBER(xG)
        call RANDOM_NUMBER(xB)
        do k=0,5
           pixmapR(x+100*k,y)=int(xR*65000)
           pixmapG(x+100*k,y)=int(xG*65000)
           pixmapB(x+100*k,y)=int(xB*65000)
        end do
     end do
  end do crea_pixmap

  crea_quadrato: do x=240,280
     do y=100,140
        xR=0;xG=0;xB=0
        do k=240/100,0,-1
           pixmapR(x-100*k,y)=pixmapR(x+99,y)
           pixmapG(x-100*k,y)=pixmapG(x+99,y)
           pixmapB(x-100*k,y)=pixmapB(x+99,y)
        end do
!        do k=0,5
!           pixmapR(x+100*k,y)=int(xR*10000)
!           pixmapG(x+100*k,y)=int(xG*10000)
!           pixmapB(x+100*k,y)=int(xB*10000)
!        end do
     end do
  end do crea_quadrato

  call crea_immagine(nx,ny,pixmapR,pixmapG,pixmapB)
  write (*,*) "Ho creato il file oggetto.pnm"

end program stereogrammi

subroutine crea_immagine(r,c,pixmapR,pixmapG,pixmapB)
  ! Scrive su un file la pixelmap 
  implicit none

  integer :: r,c,ios
  integer,dimension(r,c) :: pixmapR,pixmapG,pixmapB
  integer :: x,y

  open(unit=1,iostat=ios,file="oggetto.pnm",action="write")
  if (ios/=0) then
     write(*,*) "Impossibile creare il file" 
     stop
  endif

  write(1,'(a)') "P3"
  write(1,*) r,c
  write(1,*) 255
  do y=1,c
     do x=1,r
        write(1,*) pixmapR(x,y), pixmapG(x,y), pixmapB(x,y)
     end do
  end do

end subroutine crea_immagine

