subroutine MAPL_GetImsJms(Imins,Imaxs,Jmins,Jmaxs,Ims,Jms,rc)
! Given lists of the min and max Is and Js in each processor
! in a rectangular layout, it computes the number of elements
! in each of the I columns and the number in each of the j
! rows of the layout. Pointers Ims and Jms are allocated with the i and j
! sizes of the layout (nx and ny) and filled with the IMs and JMs.
! The four input lists must be in the same order, but the order
! is arbitrary. Nx and Ny can be obtained from the sizes of
! Ims and Jms, respectively
use MAPL_SortMod
integer, dimension(:), intent(IN ) :: Imins,Imaxs,Jmins,Jmaxs
integer, pointer :: Ims(:),Jms(:)
integer, optional, intent(out) :: rc
integer :: nx, ny, nx0, ny0, nde, k
integer, allocatable :: Im0(:), Jm0(:)
integer :: minI,minJ ! in case the starting index is zero
integer :: status
_ASSERT(.not.associated(Ims), 'Ims is associated and should not be.')
_ASSERT(.not.associated(Jms), 'Jms is associated and should not be.')
! The original minI and minJ are assumed to be 1
! The index of EASE grid is starting from 0
minI = minval(Imins,DIM=1)
minJ = minval(Jmins,DIM=1)
nx = count(Jmins==minJ)
ny = count(Imins==minI)
allocate(Ims(nx),Jms(ny), __STAT__)
allocate(Im0(nx),Jm0(ny), __STAT__)
nde = size(Imins)
nx0 = 1
ny0 = 1
do k=1,nde
if(Imins(k)==minI) then
Jms(ny0) = Jmaxs(k)-Jmins(k) + 1
Jm0(ny0) = Jmins(k)
if(ny0==ny) then
exit
else
ny0 = ny0 + 1
end if
end if
end do
do k=1,nde
if(Jmins(k)==minJ) then
Ims(nx0) = Imaxs(k)-Imins(k) + 1
Im0(nx0) = Imins(k)
if(nx0==nx) then
exit
else
nx0 = nx0 + 1
end if
end if
end do
call MAPL_Sort(Im0,Ims)
call MAPL_Sort(Jm0,Jms)
deallocate(Im0,Jm0,__STAT__)
_RETURN(ESMF_SUCCESS)
end subroutine MAPL_GetImsJms