subroutine mx_uvsort (x,y,uvtable,new,shift,uvmax,uvmin,error)
  use gildas_def
  use gkernel_interfaces
  use gbl_format
  use image_def
  !---------------------------------------------------------------------
  ! GILDAS
  !   Sort an input UV table
  !---------------------------------------------------------------------
  type(gildas), intent(inout) :: x            ! Unsorted UV table
  type(gildas), intent(inout) :: y            ! Sorted UV table
  character(len=*), intent(in) :: uvtable     ! Table name
  real(8), intent(inout) :: new(3)            ! New phase center
  logical, intent(inout) :: shift             ! Shift phase center ?
  real(4), intent(inout) :: uvmax             !
  real(4), intent(inout) :: uvmin             !
  logical, intent(out) :: error               ! Error flag
  !
  ! Local
  real(8) :: freq, off(3), dcol
  ! PI is defined with more digits than necessary to avoid losing
  ! the last few bits in the decimal to binary conversion
  real(8), parameter :: pi=3.14159265358979323846d0
  real(8), parameter :: f_to_k = 2.d0*pi/299792458.d-6
  real :: cs(2),pos(2)
  integer :: ier, nx, ny
  !
  error = .false.
  Print *,'MX_UVSORT shift ',shift
  !
  ! Set parameters
  call gildas_null(x, type = 'UVT')
  call gdf_copy_header (y, x, error)
  call sic_parse_file (uvtable, ' ', '.uvt-mx', x%file)
  !
  ! Correct for new phase center if required
  if (shift) then
    if (x%gil%ptyp.ne.p_azimuthal) then
      x%gil%a0 = x%gil%ra
      x%gil%d0 = x%gil%dec
      x%gil%pang = 0.
      x%gil%ptyp = p_azimuthal
    endif
    call uv_shift (new,x%gil%a0,x%gil%d0,x%gil%pang,off,shift)
    x%gil%posi_words = 12
    x%gil%proj_words = 9
    if (shift) then
      x%gil%a0 = new(1)
      x%gil%d0 = new(2)
      x%gil%pang = new(3)
    endif
  endif
  call gdf_create_image(x, error)
  if (error) return
  !
  ! Get visibilities
  allocate (x%r2d(x%gil%dim(1),x%gil%dim(2)), &
    & y%r2d(y%gil%dim(1),y%gil%dim(2)), stat=ier)
  Print *,'MX_UVSORT Allocate ',ier
  if (ier.ne.0) then
    error = .true.
    return
  endif
  !
  call gdf_read_uvall(y,y%r2d,error)
  Print *,'MX_UVSORT Readall ',error
  !
  ! Compute observing frequency, and new phase center in wavelengths
  if (shift) then
    dcol = (x%gil%nchan+1)*0.5d0
    freq = gdf_uv_frequency(x,dcol)
    cs(1)  =  cos(off(3))
    cs(2)  = -sin(off(3))
    ! Note that the new phase center is counter-rotated because rotations
    ! are applied before phase shift.
    ! Corrected sign 4-Apr-1993
    pos(1) = - freq * f_to_k * ( off(1)*cs(1) - off(2)*cs(2) )
    pos(2) = - freq * f_to_k * ( off(2)*cs(1) + off(1)*cs(2) )
  else
    pos(1) = 0.0
    pos(2) = 0.0
    cs(1) = 1.0
    cs(2) = 0.0
  endif
  !
  nx = x%gil%dim(1)
  ny = x%gil%dim(2)
  call uvsort_uv (nx,ny,x%gil%ntrail, &
     &    y%r2d, x%r2d, pos,cs,uvmax,uvmin,error)
     Print *,'Done uvsortuv'
  if (.not.error) then
    call gdf_close_image(y, error)
    call gdf_write_uvall(x, x%r2d, error)
  endif
end subroutine mx_uvsort
