subroutine uv_reweight_comm(line,comm,error)
  use gildas_def
  use gkernel_interfaces
  use gbl_message
  use image_def
  use clean_arrays
  use imager_interfaces, except_this => uv_reweight_comm
  !---------------------------------------------------------------------
  ! @ private
  !
  ! IMAGER
  !	  Derive the weights of the UV table from the noise
  !     statistics over many channels
  ! UV_REWEIGHT APPLY Value
  ! UV_REWEIGHT ESTIMATE [Tolerance] [PrintLevel]] [/RANGE Min Max Type] 
  ! UV_REWEIGHT DO [Tolerance] [PrintLevel]] [/RANGE Min Max Type] -
  !     [/FLAG Threshold] [/FILE FileIn FileOut]
  !---------------------------------------------------------------------
  ! Local
  character(len=*), intent(in) :: line
  character(len=*), intent(in) :: comm
  logical :: error
  !
  character(len=*), parameter :: rname='UV_REWEIGHT'
  integer, parameter :: o_file=2
  integer, parameter :: o_flag=1
  integer, parameter :: o_range=3
  integer, parameter :: mranges=10
  integer, parameter :: mmode=4
  character(len=12) :: smode(mmode), argum, mode
  data smode/'APPLY','DO','ESTIMATE','TIME'/
  real, save :: scale=1.0
  !
  type(gildas) :: hiuv, houv
  logical :: flag
  integer :: ishow, irange, n, i, nbad, ier
  integer :: ic, iv
  real, allocatable :: original(:), ratio(:)
  real :: dr, thre, fthre
  integer :: numchan, nc(mranges)
  character(len=256) :: uvchannels, mess
  character(len=24) :: chain
  character(len=12) :: ctype
  character(len=filename_length) :: filein, fileou
  integer :: do_file
  logical :: do_time
  real :: gscale, lscale, diam
  integer(kind=index_length) :: ib, mvisi, nvisi
  !
  ! Code:
  !
  ! Define the mode
  call sic_ke(line,0,1,argum,n,.true.,error)
  if (error) return
  call sic_ambigs (rname,argum,mode,n,smode,mmode,error)
  if (error) return
  !
  do_time = mode.eq.'TIME'
  !
  ! /FILE mode
  if (sic_present(o_file,0)) then
    if (do_time) then
      ! We should be able to do it only if the Output file is specified
      ! In this case, the output file would be Time-Baseline sorted
      ! and there may be memory issues if it uses more than 1/2 of the
      ! available memory - To be seen later
      call map_message(seve%e,rname,'TIME mode not available with /FILE')
      error = .true.
      return
    endif
    do_file = sic_narg(o_file)
    !
    call sic_ch(line,o_file,1,filein,n,.true.,error)
    if (error) return
    call gildas_null(hiuv,type='UVT')
    call sic_parsef (filein,hiuv%file,' ','.uvt')
    call gdf_read_header (hiuv,error)
    if (error) return
    if ((hiuv%gil%nchan.lt.17).and.(mode.ne.'APPLY')) then
      write(mess,'(A,I0,A)') 'UV data has only ',hiuv%gil%nchan, &
        & ' channels, noise estimate impossible'
      call map_message(seve%e,rname,mess,1)
      error = .true.
      return
    endif
    mvisi = space_nitems('SPACE_GILDAS',hiuv,1)
    !
    allocate(hiuv%r2d(hiuv%gil%dim(1),mvisi),stat=ier)
    if (ier.ne.0) then
      call map_message(seve%e,rname,'Memory allocation error')
      error = .true.
      return
    endif
    !
    call gildas_null(houv,type='UVT')
    call gdf_copy_header(hiuv,houv,error)
    !
    if (do_file.gt.1) then
      do_file = 2
      call sic_ch(line,o_file,2,fileou,n,.true.,error)
      if (error) return
      !
      call sic_parsef (fileou,houv%file,' ','.uvt')
    endif
    !
    if (hiuv%gil%nteles.ne.0) then
      diam = hiuv%gil%teles(1)%diam/4
    else
      diam = 3
      call map_message(seve%w,rname,'No Telescope information, UV tolerance set to 3 m by default')
    endif
  else
    ! No /FILE option
    !
    ! Make sure UV data is present 
    if (huv%loca%size.eq.0) then
      call map_message(seve%e,rname,'No UV data',1)
      error = .true.
      return
    endif
    !
    if (huv%gil%nteles.ne.0) then
      diam = huv%gil%teles(1)%diam/4
    else
      diam = 3
      call map_message(seve%w,rname,'No Telescope information, UV tolerance set to 3 m by default')
    endif
    !
    if (mode.eq.'DO' .or. mode.eq.'ESTIMATE') then
      ! Verify if enough channels are present
      if (huv%gil%nchan.lt.17) then
        ! Fall back on Baseline-Time sorted data, to use differences
        ! between adjacent visibilities 
        write(mess,'(A,I0,A)') 'UV data has only ',huv%gil%nchan, &
          & ' channels, falling back on TIME mode'
        call map_message(seve%w,rname,mess,3)
        do_time = .true.
      else if (huv%gil%nchan.lt.33) then
        write(mess,'(A,I0,A)') 'UV data has only ',huv%gil%nchan, &
          & ' channels, noise estimate may be inaccurate'
        call map_message(seve%w,rname,mess)        
      endif
    else if (mode.eq.'TIME') then
      do_time = .true.
    endif
    !
    if (do_time) then
      !
      call gildas_null(houv,type='UVT')
      call gdf_copy_header(huv,houv,error)
      allocate(houv%r2d(houv%gil%dim(1),houv%gil%dim(2)),stat=ier)
      if (ier.ne.0) then
        call map_message(seve%e,rname,'Memory allocation error')
        error = .true.
        return
      endif
      huv%r2d => duv
      error = .false.
      call uvsort_bt (huv,houv,error)
    endif
    if (error) return
    do_file = 0
  endif
  !
  if (mode.eq.'APPLY') then
    if (sic_present(o_flag,0) .or. sic_present(o_range,0)) then
      call map_message(seve%e,rname,'No option allowed for APPLY action')
      error = .true.
    endif
    call sic_ch(line,0,2,argum,n,.true.,error)
    if (error) return
    if (argum.ne.'*') then
      call sic_r4(line,0,2,scale,.true.,error)
      if (error) return
    endif
    if (scale.le.0) then
      call map_message(seve%e,rname,'Scale factor must be > 0')
      error = .true.
      return
    elseif (scale.eq.1.0) then
      call map_message(seve%w,rname,'Scale factor is 1, nothing to do')
      return
    else
      write(mess,*) "Applying scale factor ",scale
      call map_message(seve%i,rname,mess)
    endif
    !
    if (do_file.eq.0) then
      do iv=1,huv%gil%nvisi
        do ic=1,huv%gil%nchan
          duv(3*ic+huv%gil%fcol-1,iv) = scale * duv(3*ic+huv%gil%fcol-1,iv)
        enddo
      enddo
      do_weig = .true.
    else 
      if (do_file.eq.2) then
        call gdf_create_image(houv,error)
        if (error) return
      endif
      !
      ! Work by block. Read in HIUV, Write in HOUV
      do ib=1,hiuv%gil%dim(2),mvisi
        !
        ! Read the data
        write(mess,*) ib,' / ',hiuv%gil%dim(2),mvisi
        call map_message(seve%i,rname,mess)
        hiuv%blc(2) = ib
        hiuv%trc(2) = min(hiuv%gil%dim(2),ib-1+mvisi)
        nvisi = hiuv%trc(2)-hiuv%blc(2)+1
        call gdf_read_data(hiuv,hiuv%r2d,error)
        if (error) return
        !
        do iv=1,nvisi
          do ic=1,huv%gil%nchan
            hiuv%r2d(3*ic+huv%gil%fcol-1,iv) = scale * hiuv%r2d(3*ic+huv%gil%fcol-1,iv)
          enddo
        enddo
        !
        houv%blc = hiuv%blc
        houv%trc = hiuv%trc
        call gdf_write_data (houv,hiuv%r2d,error)
        if (error) return
      enddo
      call gdf_close_image(hiuv,error)
      if (do_file.eq.2) call gdf_close_image(houv,error)
    endif
  else
    ! DO, ESTIMATE or TIME
    !
    ! Arguments with their default
    thre = 1.21
    call sic_r4(line,0,2,thre,.false.,error)
    if (error) return
    ishow = 0
    call sic_i4(line,0,3,ishow,.false.,error)
    if (error) return
    flag = sic_present(o_flag,0)
    if (flag) then
      if (mode.eq.'ESTIMATE' .or. mode.eq.'TIME') then
        call map_message(seve%e,rname,'/FLAG option not valid for ESTIMATE or TIME actions')
        error = .true.
        return
      else 
        fthre = 3.0
        call sic_r4(line,o_flag,1,fthre,.false.,error)
        if (error) return
        if (fthre.lt.1) then
          call map_message(seve%e,rname,'Invalid Threshold, must be > 1')
          error = .true.
          return
        endif
      endif
    endif
    !
    ! Get the selected channel range
    irange = sic_narg(o_range)
    ctype = 'CHANNEL'
    uvchannels = ' '
    if (irange.gt.1) then
      if (mod(irange,2).eq.1) then
        call sic_ke(line,o_range,irange,ctype,n,.true.,error)
        if (error) return
        irange = irange-1
      endif
      !
      irange = min(irange,mranges)
      !
      if (irange.eq.0) then
        uvchannels = ' '
      else
        do i=1,irange
          call sic_r4(line,o_range,i,dr,.true.,error)
          write(chain,*) dr
          uvchannels(n:) = adjustl(chain)
          n = len_trim(uvchannels)+2
        enddo
      endif
      numchan = irange/2
    else
      numchan = 0
    endif
    !
    ! Dispatch according to mode
    if (do_file.eq.0) then
      ! In MEMORY mode
      call get_uvranges(rname,uvchannels,ctype,mranges,numchan,nc,huv,error)
      if (error) return
      !
      allocate(original(huv%gil%nvisi),ratio(huv%gil%nvisi),stat=ier)
      if (ier.ne.0) then
        call map_message(seve%e,rname,'Memory allocation failure')
        error = .true.
        return
      endif
      !
      if (do_time) then
        ! Compute noise from differences between adjacent Visibilities
        call uv_time_reweight(houv,houv%r2d,huv%gil%nvisi,numchan,nc,diam,thre, &
          & original,ratio,scale, error)
      else
        ! Compute noise from statistics on channels
        call uv_get_reweight(huv,duv,huv%gil%nvisi,numchan,nc,ishow,thre, &
          & original,ratio,scale, error)
      endif
      !
      if (mode.eq.'DO') then
        nbad = 0
        write(mess,*) "Applying Median re-scale factor ",scale
        call map_message(seve%i,rname,mess)
        call uv_do_reweight(huv, duv, huv%gil%nvisi, flag, nbad, original, &
          & ratio, scale, fthre)
        do_weig = .true.
        if (nbad.gt.0) then
          write(mess,'(I0,A,I0,A)') nbad,' / ',huv%gil%nvisi, &
            & ' visibilities with non conformant weights'
          call map_message(seve%w,rname,mess)
          scale = 1.0
        endif
      else
        write(mess,*) "Computed Median re-scale factor is ",scale
        call map_message(seve%i,rname,mess)
      endif
    else
      ! on FILE mode
      call get_uvranges(rname,uvchannels,ctype,mranges,numchan,nc,hiuv,error)
      if (error) return
      !
      allocate(original(mvisi),ratio(mvisi),stat=ier)
      if (ier.ne.0) then
        call map_message(seve%e,rname,'Memory allocation failure')
        error = .true.
        return
      endif
      !
      ! Work by Block : scales will be by Block ? or we
      ! must compute the Mean of Medians to be sure ? 
      gscale = 0
      lscale = 0 
      do ib=1,hiuv%gil%nvisi,mvisi
        !
        ! Read the data
        write(mess,*) ib,' / ',hiuv%gil%dim(2),mvisi
        call map_message(seve%i,rname,mess)
        hiuv%blc(2) = ib
        hiuv%trc(2) = min(hiuv%gil%dim(2),ib-1+mvisi)
        nvisi = hiuv%trc(2)-hiuv%blc(2)+1
        call gdf_read_data(hiuv,hiuv%r2d,error)
        if (error) return
        !
        call uv_get_reweight(hiuv,hiuv%r2d,nvisi,numchan,nc,ishow,thre, &
          & original,ratio, lscale, error)
        gscale = gscale + lscale*nvisi
      enddo
      ! Mean of Medians
      scale = gscale/hiuv%gil%nvisi
      !
      if (mode.eq.'DO') then
        ! Create Ouput file if needed
        if (do_file.eq.2) then
          call gdf_create_image(houv,error)
          if (error) return
        endif
        !
        nbad = 0
        write(mess,*) "Applying Median re-scale factor ",scale
        call map_message(seve%i,rname,mess)
        do ib=1,hiuv%gil%nvisi,mvisi
          !
          ! Read the data
          write(mess,*) ib,' / ',hiuv%gil%dim(2),mvisi
          call map_message(seve%i,rname,mess)
          hiuv%blc(2) = ib
          hiuv%trc(2) = min(hiuv%gil%dim(2),ib-1+mvisi)
          nvisi = hiuv%trc(2)-hiuv%blc(2)+1
          call gdf_read_data(hiuv,hiuv%r2d,error)
          if (error) return
          !
          call uv_do_reweight(huv, duv, huv%gil%nvisi, flag, nbad, original, &
            & ratio, scale, fthre)
          houv%blc = hiuv%blc
          houv%trc = hiuv%trc
          call gdf_write_data (houv,hiuv%r2d,error)
          if (error) return
        enddo
        if (nbad.gt.0) then
          write(mess,'(I0,A,I0,A)') nbad,' / ',huv%gil%nvisi, &
            & ' visibilities with non conformant weights'
          call map_message(seve%w,rname,mess)
          scale = 1.0
        endif
        if (do_file.eq.2) call gdf_close_image(houv,error)
      else
        write(mess,*) "Median re-scale factor is ",scale
        call map_message(seve%i,rname,mess)
      endif
      call gdf_close_image(hiuv,error)
    endif ! do_file # 0
  endif   ! APPLY
  !
end subroutine uv_reweight_comm
!
subroutine uv_get_reweight (out,dout,nvisi,numchan,nc,ishow,thre, &
    & original,ratio,scale,error)
  use image_def
  use gkernel_interfaces, only : gr4_median
  !---------------------------------------------------------------------
  ! @ private-mandatory
  !
  ! IMAGER
  !	  Support for 
  ! UV_REWEIGHT [PrintLevel] /RANGE  [/NOFLAG]
  !   Derive the weights of the UV table from the noise
  !   statistic over many channels
  !---------------------------------------------------------------------
  type (gildas), intent(in) :: out       ! Visibility header
  real, intent(in) :: dout(:,:)          ! Visibilities
  integer(kind=size_length), intent(in) :: nvisi ! Number of visibilities
  integer, intent(in) :: numchan         ! Number of windows 
  integer, intent(in) :: nc(2*numchan)   ! Channel windows
  integer, intent(in) :: ishow           ! Show changes period
  real, intent(in) :: thre               ! Threshold for choice of noise estimate
  real, intent(out) :: original(nvisi)   ! Original weights
  real, intent(out) :: ratio(nvisi)      ! Ratio of weights
  real, intent(out) :: scale             ! Global scale factor
  logical, intent(out) :: error          ! Error flag
  ! Local
  integer :: i,j,k,l,fc,nd,nk, kk, ll
  real :: rms, rmsr, rmsi, reel, imag, arms, awei
  real :: xxr, xmr, xxi, xmi
  !
  nk = (nc(1)+nc(2))/2
  if (ishow.gt.0) then
    write(*,*) 'Visibility           New          Original       N_Valid_Channels '
  endif 
  fc = out%gil%fcol-1
  error = .false.
  k = 0
  kk = 0
  ll = 0
  !  
  do j=1,nvisi
    !
    ! Compute rms on "Good" channels
    xxr = 0.
    xxi = 0
    xmr = 0.
    xmi = 0.
    nd = 0
    do l=1,numchan
      do i=nc(2*l-1),nc(2*l)
        if (dout(fc+3*i,j).gt.0)  then
          reel = dout(fc+3*i-2,j)
          imag = dout(fc+3*i-1,j)
          xxr = xxr + reel**2
          xmr = xmr + reel
          xxi = xxi + imag**2
          xmi = xmi + imag
          nd = nd+1
        endif
      enddo
    enddo
    !
    if (nd.le.1) cycle
    !
    ! This is the weight on the REAL or IMAGinary part
    k = k+1
    rmsr = (xxr-xmr/nd)
    rmsi = (xxi-xmi/nd)
    rms = (rmsr+rmsi)*0.5
    if (rms.gt.thre*rmsi) then
      rms = thre*rmsi
      kk = kk+1
    else if (rms.gt.thre*rmsr) then
      rms = thre*rmsr
      ll = ll+1
    endif
    if (ishow.gt.0) then
      if (mod(k,ishow).eq.1) then
        arms = sqrt(rms/float(nd-1))
        awei = 1.0/sqrt(dout(fc+3*nk,j)*1e6) 
        write(6,*) j,arms,awei,nd ! +ivisi if in Loop
      endif
    endif
    original(j) = dout(fc+3*nk,j)
    ratio(j) = float(nd-1)/rms*1e-6
    ratio(j) = ratio(j)/original(j)
    !
  enddo
  !
  call gr4_median(ratio,nvisi,0.0,-1.0,scale,error)
end subroutine uv_get_reweight
!
subroutine uv_do_reweight(out, dout, nvisi, flag, nbad, original, & 
  & ratio, scale, fthre)
  use image_def
  !---------------------------------------------------------------------
  ! @ private-mandatory
  !   Support routine for command
  ! UV_REWEIGHT DO [/FLAG Threshold]
  !
  ! Apply scaling factor which has been derived, and return the
  ! number of "anomalous" visibilities.
  !---------------------------------------------------------------------  
  type (gildas), intent(inout) :: out    ! Visibility header
  real, intent(inout) :: dout(:,:)       ! Visibilities
  integer(kind=size_length), intent(in) :: nvisi   ! Number of visibilities
  logical, intent(in) :: flag            ! Flag anomalous re-scale ?
  integer, intent(inout) :: nbad         ! Number of potentially "bad" visibilities
  real, intent(in) :: original(nvisi)    ! Original weights
  real, intent(in) :: ratio(nvisi)       ! Ratio of weights
  real, intent(in) :: scale              ! Global scale factor
  real, intent(in) :: fthre              ! Worry factor
  !
  integer(kind=index_length) :: j
  integer :: fc, ic
  real :: wei
  !
  fc = out%gil%fcol-1
  !
  do j=1,nvisi
    if (flag) then
      if ( (ratio(j).gt.fthre*scale).or.(ratio(j)*fthre.lt.scale) ) then
        wei = -abs(scale*original(j))
        nbad = nbad+1
      else
        wei = scale*original(j)
      endif
    else
      wei = scale*original(j)
    endif
    !
    do ic = 1,out%gil%nchan
      if (dout(fc+3*ic,j).gt.0) then
        dout(fc+3*ic,j) = wei
      else if (dout(fc+3*ic,j).lt.0) then
        dout(fc+3*ic,j) = -abs(wei)      
      endif
    enddo
  enddo 
end subroutine uv_do_reweight
!
subroutine get_uvranges(pname,uvchannel,ctype,mranges,numchan,nc,y,error)
  use image_def
  use gbl_message
  use gkernel_interfaces
  use imager_interfaces, only : map_message
  !---------------------------------------------------------------------
  ! @ private
  !   Convert ranges defined in a String to (integer) Channel ranges
  !   for a UV data.
  !---------------------------------------------------------------------
  character(len=*), intent(in) :: pname     ! Caller name
  character(len=*), intent(in) :: uvchannel ! String to be decoded
  character(len=*), intent(inout) :: ctype  ! Type of values
  integer, intent(in) :: mranges            ! Maximum Number of ranges
  integer, intent(out) :: numchan           ! Actual number of ranges
  integer, intent(out) :: nc(mranges)       ! Channel ranges
  type(gildas), intent(in) :: y             ! Header of UV data
  logical, intent(out) :: error             ! Error flag
  !
  integer(4) :: ier, i, ntmp, nmin, nmax, inext
  real(8), parameter :: rnone=-1D9 ! Impossible velocity, frequency or channel number 
  real(kind=8) :: drange(mranges)
  character(len=256) :: chain
  integer(kind=4), parameter :: mtype=3
  integer :: itype
  character(len=12) :: types(mtype),mytype
  data types /'CHANNEL','VELOCITY','FREQUENCY'/
  !
  call sic_upper(ctype)
  error = .false.
  call sic_ambigs(pname,ctype,mytype,itype,types,mtype,error)
  if (error)  return
  !
  drange = rnone    ! Impossible velocity, frequency or channel number 
  nc = 0            ! This initialization is essential...
  read (uvchannel,*,iostat=ier) drange
  if (ier.gt.0) then
    call map_message(seve%e,pname,'Error reading '//trim(uvchannel))
    error = .true.
    return
  endif
  ! 
  numchan = 0
  i = 2
  do while (i.lt.mranges)
    if (drange(i).ne.rnone.and.drange(i-1).ne.rnone) numchan = numchan+2
    i = i+2
  enddo
  !
  ! Convert to channels
  if (numchan.eq.0) then
    numchan = 2
    nc(1) = 1
    nc(2) = y%gil%nchan 
  else if (mytype.eq.'CHANNEL') then
    nc(1:numchan) = nint(drange(1:numchan))
    do i=1,numchan
      if (nc(i).lt.0) nc(i) = y%gil%nchan+nc(i)
    enddo
  else if (mytype.eq.'VELOCITY') then
    ! drange = nc - y%gil%ref(y%gil%faxi) ) * y%gil%vres + y%gil%voff 
    nc(1:numchan) = (drange(1:numchan) - y%gil%voff) / y%gil%vres + y%gil%ref(y%gil%faxi)
  else if (mytype.eq.'FREQUENCY') then
    ! drange = nc - y%gil%ref(y%gil%faxi) ) * y%gil%vres + y%gil%voff 
    nc(1:numchan) = (drange(1:numchan) - y%gil%freq) / y%gil%fres + y%gil%ref(y%gil%faxi)
  else
    call map_message(seve%e,pname,"Type of value '"//trim(mytype)//"' not supported")
    error = .true.
    return
  endif
  !
  ! Set channel order to have increasing values in each pair
  inext = 1
  do i=2,numchan,2
    if (nc(i).lt.nc(i-1)) then
      ntmp = nc(i)
      nc(i) = nc(i-1)
      nc(i-1) = ntmp
    endif    
    nmax = min(nc(i),y%gil%nchan)
    nmin = max(nc(i-1),1)
    !
    if (nmin.gt.nmax) then
      call map_message(seve%e,pname,"Range out of bounds")
      error = .true.
      return
    endif
    !
    nc(i-1) = nmin
    nc(i) = nmax
    write(chain(inext:),'(A,I0,A,I0,A)') '[',nmin,'-',nmax,']'
    inext = len_trim(chain)+3
  enddo
  !
  call map_message(seve%i,pname,'Using channel ranges '//chain)
  numchan = numchan/2     ! This must be the number of ranges
end subroutine get_uvranges
!
subroutine uv_time_reweight (out,dout,nvisi,numchan,nc,diam,thre, &
    & original,ratio,scale,error)
  use image_def
  use gkernel_interfaces, only : gr4_median
  !---------------------------------------------------------------------
  ! @ private-mandatory
  !
  ! IMAGER
  !	  Support for 
  ! UV_REWEIGHT TIME [PrintLevel] /RANGE  [/NOFLAG]
  !   Derive the weights of the UV table from the noise
  !   statistic over many consecutive visibilities 
  !
  ! This assumes that Visibilities are sufficiently well sampled so
  ! that the differences between adjacent ones (in time) only differ
  ! by the noise, not by the source structure.
  !---------------------------------------------------------------------
  type (gildas), intent(in) :: out       ! Visibility header
  real, intent(in) :: dout(:,:)          ! Visibilities
  integer(kind=size_length), intent(in) :: nvisi ! Number of visibilities
  integer, intent(in) :: numchan         ! Number of windows 
  integer, intent(in) :: nc(2*numchan)   ! Channel windows
  real, intent(in) :: diam               ! Tolerance radius in UV space
  real, intent(in) :: thre               ! Threshold for choice of noise estimate
  real, intent(out) :: original(nvisi)   ! Original weights
  real, intent(out) :: ratio(nvisi)      ! Ratio of weights
  real, intent(out) :: scale             ! Global scale factor
  logical, intent(out) :: error          ! Error flag
  ! Local
  integer :: i,k,l,fc,nd,nk, kk, ll
  integer(kind=size_length) :: jlast, j
  real :: rms, rmsr, rmsi, reel, imag, arms, awei
  real :: xxr, xmr, xxi, xmi, duvstep, deltauv, weight
  integer :: iant,jant,ibase,jbase, jmax
  !
  duvstep = diam**2   ! Nyquist sampling passed as argument...
  !
  nk = (nc(1)+nc(2))/2      ! An average channel
  fc = out%gil%fcol-1       ! First column
  error = .false.
  k = 0
  kk = 0
  ll = 0
  !
  iant = 6      ! Iant Pointer
  jant = 7      ! Jant Pointer
  !  
  ibase = 0
  xxr = 0.
  xxi = 0
  xmr = 0.
  xmi = 0.
  nd = 0
  nd = 0
  deltauv = 0.
  !
  original(1) = dout(fc+3*nk,1)
  jlast = 1
  j = 2     ! Start at the 2nd visibility
  do 
    !
    if (j.lt.nvisi) then
      jbase = 1024*dout(iant,j) + dout(jant,j)
    else
      jbase = 0
    endif
    deltauv = (dout(1,j)-dout(1,j-1))**2 + (dout(2,j)-dout(2,j-1))**2
    original(j) = dout(fc+3*nk,j)   ! Representative Weight
    !
    ! If UV track has changed, compute the statistic on the last UV track
    if ((ibase.ne.jbase).or.(deltauv.gt.duvstep)) then
      if (nd.gt.1) then
        !
        rmsr =  (xxr-xmr/nd)   ! Store the  noise level
        rmsi =  (xxi-xmi/nd)
        rms = (rmsr+rmsi)*0.5
        if (rms.gt.thre*rmsi) then
          rms = thre*rmsi
          kk = kk+1
        else if (rms.gt.thre*rmsr) then
          rms = thre*rmsr
          ll = ll+1
        endif
        ratio(jlast:j) = float(nd)/rms*1e-6
        jlast = j
        j = j+1 ! Skip 1 Visi
        if (j.gt.nvisi) exit
      endif        
      xxr = 0.
      xxi = 0
      xmr = 0.
      xmi = 0.
      nd = 0
      ibase = jbase
    endif
    !
    ! Accumulate Differences
    do i=nc(1),nc(2)  
      weight = max(0.,dout(fc+3*i,j))*max(0.,dout(fc+3*i,j-1))
      if (weight.gt.0) then
        weight = sqrt(weight)
        reel = dout(fc+3*i-2,j) - dout(fc+3*i-2,j-1)
        imag = dout(fc+3*i-1,j) - dout(fc+3*i-1,j-1)
        xxr = xxr + reel**2*weight
        xxi = xxi + imag**2*weight
        nd = nd+1
      endif
    enddo
    ! Next visibility
    j = j+1
    !
  enddo
  !
  call gr4_median(ratio,nvisi,0.0,-1.0,scale,error)
  scale = scale*2   ! We have evaluated the difference
end subroutine uv_time_reweight
