!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module minmax_tool
  public :: maxmap,maxlst
  private
  !
contains
  !
subroutine maxmap(ary,nx,ny,box,amax,imax,jmax,amin,imin,jmin)
  !--------------------------------------------------------------------
  ! Find max and min in specified region of real array
  !--------------------------------------------------------------------
  integer, intent(in) :: nx, ny         ! X,Y size
  real, intent(in) :: ary(nx,ny)        ! Array of values
  integer, intent(in) :: box(4)         ! Search box
  integer, intent(out) :: imax, jmax    ! Position of Max
  integer, intent(out) :: imin, jmin    ! Position of Min
  real, intent(out) :: amax, amin       ! Max and Min
  !
  integer i, j
  real a
  !
  amax = ary(box(1),box(2))
  amin = amax
  imax = box(1)
  jmax = box(2)
  imin = box(1)
  jmin = box(2)
  !
  do j = box(2), box(4)
    do i = box(1), box(3)
      a = ary(i,j)
      if (a .gt. amax) then
        amax = a
        imax = i
        jmax = j
      elseif (a .lt. amin) then
        amin = a
        imin = i
        jmin = j
      endif
    enddo
  enddo
end subroutine maxmap
!
subroutine maxlst(ary,nx,ny,list,nl,amax,imax,jmax,amin,imin,jmin)
  !--------------------------------------------------------------------
  ! Find max and min in specified region of real array using a list of
  ! valid pixels
  !--------------------------------------------------------------------
  integer, intent(in) :: nx, ny         ! X,Y size
  real, intent(in) :: ary(nx*ny)        ! Array of values
  integer, intent(in) :: nl             ! List size
  integer, intent(in) :: list(nl)       ! Search list 
  integer, intent(out) :: imax, jmax    ! Position of Max
  integer, intent(out) :: imin, jmin    ! Position of Min
  real, intent(out) :: amax, amin       ! Max and Min
  !
  integer i, k, kmin, kmax
  !
  amax = ary(list(1))
  amin = ary(list(1))
  kmin = list(1)
  kmax = list(1)
  !
  do i = 2,nl
    k = list(i)
    if (ary(k).gt.amax) then
      amax = ary(k)
      kmax = k
    elseif (ary(k).lt.amin) then
      amin = ary(k)
      kmin = k
    endif
  enddo
  !
  jmax = (kmax-1)/nx+1
  imax = kmax-(jmax-1)*nx
  jmin = (kmin-1)/nx+1
  imin = kmin-(jmin-1)*nx
end subroutine maxlst
end module minmax_tool
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
