program IQx
  !! Find eXtreme values in image quality maps
  !! Paul Sava (paul@sep.stanford.edu)
  !! 10/14/02

  !!  input: z-mx-ro (image quality map)
  !! output: z-mx

  use sep
  implicit none

  real, dimension(:,:),   allocatable :: iqmap
  real, dimension(:,:),   allocatable :: extrm,romax

  integer :: nz,nmx,nro
  integer :: iz,imx
  real    ::    omx,oro
  real    ::    dmx,dro
  integer ::        iro
  real    ::         ro

  integer :: xwin,zwin !! total window = 2*n+1
  integer :: option

  call sep_init()

  call from_history("n1",nz )

  call from_history("n2",nmx)
  call from_history("o2",omx,0.)
  call from_history("d2",dmx,1.)

  call from_history("n3",nro)
  call from_history("o3",oro)
  call from_history("d3",dro)

  call   to_history("n3",2)
  call   to_history("o3",0.)
  call   to_history("d3",1.)
  call   to_history("label3"," ")

  call from_param("option",option,1)
  call sep_close()

  allocate(iqmap(nz,nmx)); iqmap=1.
  allocate(extrm(nz,nmx)); extrm=0.
  allocate(romax(nz,nmx)); romax=1.

  write(0,*) option
  if(option==1) then
     extrm=0.
     romax=oro+(nro-1)*dro
  else
     extrm=1.
     romax=oro
  end if

  do iro=1,nro
     ro = oro + (iro-1)*dro
     write (0,*) "ro=",ro
     call sep_read(iqmap)

     if(option==1) then !! find max
        where (iqmap>extrm)
           extrm=iqmap
           romax=ro
        end where
     else               !! find min
        where (iqmap<extrm)
           extrm=iqmap
           romax=ro
        end where
     end if
  end do

  call sep_write(romax)
  call sep_write(extrm)

  deallocate(iqmap,extrm,romax)
  call exit(0)
end program IQX
