!
subroutine t_uvsort (np,nv,vin,vout,inxy,incs,uvmax,uvmin,sort,error)
  use gildas_def 
  use gbl_message
  use mapping_interfaces
  !----------------------------------------------------------------------
  ! UV_MAP
  !     Rotate, Shift and Sort a UV table for map making
  !     Differential precession should have been applied before.
  !----------------------------------------------------------------------
  !
  integer, intent(in) :: np                   ! Size of a visibility
  integer, intent(in) :: nv                   ! Number of visibilities
  real, intent(in) :: vin(np,nv)              ! Input visibilities
  real, intent(out) :: vout(np,nv)            ! Output visibilities
  real(8), intent(in) :: inxy(2)              ! Phase shift
  real(8), intent(in) :: incs(2)              ! Frame Rotation
  real, intent(out) :: uvmax                  ! Max UV value
  real, intent(out) :: uvmin                  ! Min UV value
  logical, intent(inout) :: sort              ! Data has been sorted
  logical, intent(out) :: error
  !
  logical, allocatable :: suv(:) ! Sign
  real, allocatable :: uuv(:) ! U
  real, allocatable :: vuv(:) ! V
  integer, allocatable :: iuv(:) ! Index
  !
  integer ier 
  logical sorted
  real(4) :: xy(2)                   ! Real*4 Phase shift for SortUV
  real(4) :: cs(2)                   ! Real*4 Frame Rotation for LoadUV
  !
  sorted = .false.
  xy = inxy
  cs = incs
  !
  ! Load U,V coordinates, applying possible rotation (CS), and
  ! making all V negative
  allocate (suv(nv),uuv(nv),vuv(nv),iuv(nv),stat=ier)
  if (ier.ne.0) then
    error = .true.
    return
  endif
  call loaduv (vin,np,nv,cs,uuv,vuv,suv,uvmax,uvmin)
  !
  ! Sort if needed
  call chksuv (nv,vuv,iuv,sorted)
  if (.not.sorted) then
     sort = .true.
     call gr4_trie (vuv,iuv,nv,error)
     if (error) return
  endif
  !
  ! Apply phase shift and copy to output visibilities
  call sortuv (vin,vout,np,nv,0,xy,uuv,vuv,suv,iuv) 
  !
  deallocate(suv,uuv,vuv,iuv)
end subroutine t_uvsort

  
