subroutine set_scaling (error)
  use gildas_def
  use classic_api  
  !---------------------------------------------------------------------
  ! Compute the scaling factors for a given scan.
  !---------------------------------------------------------------------
  logical :: error                  !
  ! Global
  include 'clic_parameter.inc'
  include 'clic_clic.inc'
  include 'clic_number.inc'
  include 'clic_par.inc'
  include 'clic_dheader.inc'
  include 'clic_display.inc'
  include 'gbl_pi.inc'
  ! Local
  complex :: zscale(mrlband,2,mnbat)  ! subband, U/L, base
  real :: ascale(mrlband,mnant)
  common /clicscale/ zscale, ascale
  save /clicscale/
  integer :: isb, iba, ic, ip, jp, is
  integer :: ia, ja, it, ib, i
  real :: af, phase, amp, faz
  integer :: flux_scan,flux_type,known_flux
  real*8 :: a_flux(2),le_flux,le_flux_zero,fnu,size(3), fbeam,lim_flux
  logical :: down_baseline
  !
  data flux_scan /0/
  !
  ! Fraction of zero flux down which source is considered "too" resolved
  data lim_flux /0.001/    
  save flux_scan,a_flux,size
  !------------------------------------------------------------------------
  ! Code:
  error = .false.
  ! for auto correlations, only  raw, kelvin, jansky
  do ia=1, r_nant
    do is=1, r_lband
      ic = r_bb(is)
      ip = r_lpolentry(ia,is)
      amp = 1.0
      !
      ! Take out atmospheric calibration
      if (do_raw) then
        af = dh_atfac(ic,1,ia)
        if (af.gt.0) amp = amp * af
      ! convert to Janskys
      elseif (do_flux) then
        amp = amp * r_jykel(ip,ia)
      endif
      ascale(is,ia) = 1/amp
    enddo
  enddo
  do iba = 1, r_nbas
    do isb = 1, 2
      do is=1, r_lband
        ia = r_iant(iba)
        ja = r_jant(iba)
        ip = r_lpolentry(ia,is)
        jp = r_lpolentry(ja,is)
        ic = r_bb(is)
        phase = 0
        amp = 1.0
        ! amplitude calibration
        if (do_amplitude) then
          if (do_amplitude_antenna) then
            amp =exp(r_aicamp(jp,isb,ja,0)   &
              +r_aicamp(ip,isb,ia,0))
          else
            if (r_lpolmode(is).eq.1) then
               amp = r_icamp(ip,isb,iba,0)
            else
               call message(6,3,'SET_SCALING','Cannot compute' &
     &            //'baseline scaling factor with mixed polarization')
            endif
            if (amp.lt.1e-20) then
              if (dh_infac(isb,iba).eq.0) then
                amp = 0
              else
                amp = 1./abs(dh_infac(isb,iba))
              endif
            endif
          endif
        endif
        !     phase calibration
        !     use phase slot 0
        if (do_phase .and. .not.do_phase_ext) then
          if (do_phase_antenna) then
            phase = phase+r_aicpha(jp,isb,ja,0)   &
              -r_aicpha(ip,isb,ia,0)
          else
            if (r_lpolmode(is).eq.1) then
              phase = phase+r_icpha(ip,isb,iba,0)
            else
               call message(6,3,'SET_SCALING','Cannot compute' &
     &            //'baseline scaling factor with mixed polarization')
            endif
            if (phase.eq.0) then
              phase = -faz(dh_infac(isb,iba))
            endif
          endif
        ! use slot 1 if external, optionally add slot 2 if relative.
        elseif (do_phase_ext) then
          if (do_phase_antenna) then
            phase = phase+r_aicpha(jp,isb,ja,1)   &
              -r_aicpha(ip,isb,ia,1)
          else
            phase = phase+r_icpha(ip,isb,iba,1)
          endif
          if (do_phase) then
            if (do_phase_antenna) then
              phase = phase+r_aicpha(jp,isb,ja,2)   &
                -r_aicpha(ip,isb,ia,2)
            else
              phase = phase+r_icpha(ip,isb,iba,2)
            endif
          endif
        endif
        !
        ! Take out atmospheric calibration
        if (do_raw) then
          af = sqrt(dh_atfac(ic,isb,ia)*   &
            dh_atfac(ic,isb,ja))
          if (af.gt.0) amp = amp * af
        endif
        ! convert to Kelvin
        if (do_amplitude .and. .not.do_flux) then
          amp = amp * sqrt(r_jykel(ip,ia)*r_jykel(jp,ja))
        endif
        ! convert to Janskys
        if (.not.do_amplitude .and. do_flux) then
          amp = amp / sqrt(r_jykel(ip,ia)*r_jykel(jp,ja))
        endif
        !
        ! Scale by calibrator flux  (Will crash here if r_flux is NaN)
        ! Or by calibrator size                           
        if (do_scale.or.do_size) then
          le_flux = max(min (r_flux, 1e12),-1e12)
          flux_type = known_flux(r_sourc,le_flux)
          if (flux_type.ne.0) then
            !
            ! Compute zero spacing flux if needed
            if (flux_scan.ne.r_scan) then
              call message(6,1,'SCALING',&
                r_sourc//' has known structure')
              if (flux_type.eq.-1) then
                fnu = (r_flo1 + r_fif1) * 1d-3
                call planet_flux (r_sourc,r_dobs,r_ut,   &
                  fnu,a_flux(1),fbeam,size,error)
                fnu = (r_flo1 - r_fif1) * 1d-3
                call planet_flux (r_sourc,r_dobs,r_ut,   &
                  fnu,a_flux(2),fbeam,size,error)
              else
                a_flux(1) = le_flux
                a_flux(2) = le_flux
                fnu = (r_flo1 + r_fif1) * 1d-3
                call get_flux (fnu,flux_type,a_flux(1),size)
                fnu = (r_flo1 - r_fif1) * 1d-3
                call get_flux (fnu,flux_type,a_flux(2),size)
              endif
              flux_scan = r_scan
            endif
            !
            ! Compute frequency from R_FLO1 and R_FIF1 and ISB
            ! (1=Upper, 2=Lower, 3=Average)
            if (isb.eq.1) then
              fnu = r_flo1 + r_fif1
              le_flux = a_flux(1)
            elseif (isb.eq.2) then
              fnu = r_flo1 - r_fif1
              le_flux = a_flux(2)
            endif
            fnu = fnu*1.0d-3 ! Use it in GHz for fluxes
            le_flux_zero = le_flux
            call apparent_flux (fnu,le_flux,size,flux_type,   &
              dh_uvm(1,iba))
            if (do_size) then
              if (le_flux_zero.eq.0) then
                call message(8,2,'SCALING', &
                 'Zero flux for source '//r_sourc)
                 error = .true.
                 return
              else
                le_flux = le_flux/le_flux_zero
              endif
              if (abs(le_flux).lt.lim_flux) then
                print *,"le_flux",le_flux,"lim_flux",lim_flux
                call message(8,2,'SCALING', &
                r_sourc//' is too resolved on baseline '//cbas(iba))
                error = .true.
                return
              endif
            endif     
            amp = amp *  abs(le_flux)
            ! Special case for Jupiter
            if (flux_type.eq.-3) then
              if (le_flux.lt.0) phase = phase + pi
            endif
          !     IF (FLUX_TYPE.EQ.-3) THEN
          !     Z = Z / LE_FLUX  ! Special case for Jupiter
          !     if (le_flux.lt.0) phase = phase + pi
          !     ELSE
          !     Z = Z / ABS(LE_FLUX)
          !     ENDIF
          elseif (le_flux.ne.0) then
            amp = amp * abs(le_flux)
          endif
        endif
        !
        if (amp.ne.0) then
          zscale(is,isb,iba) = cmplx(cos(phase),   &
            -sin(phase))   &
            / amp
        elseif (.not. down_baseline(iba)) then
          call message(8,2,'SCALING',   &
            'Zero amplitude calibration factor base. '   &
            //cbas(iba)//' '//cband(isb))
          error = .true.
          zscale(is,isb,iba) = cmplx(cos(phase),   &
            -sin(phase))
        endif
      enddo
    enddo
  enddo
  !
  ! Triangles needed (?)
  if (r_ntri.gt.0) then
    do isb = 1, 2
      do it = 1, r_ntri
        do is = 1, r_lband
          iba = mnbas+it
          zscale(is,isb,iba) = 1.0
          do i=1, 3
            ib = bastri(i,it)
            if (i.eq.2) then
              zscale(is,isb,iba) =   &
                zscale(is,isb,iba)   &
                *conjg(zscale(is,isb,ib))
            else
              zscale(is,isb,iba) =   &
                zscale(is,isb,iba)   &
                *zscale(is,isb,ib)
            endif
          enddo
        enddo
      enddo
    enddo
  endif
  return
end subroutine set_scaling
!
subroutine scaling (is,isb,iba,z,a,error)
  use classic_api  
  integer :: is                     ! subband
  integer :: isb                    ! side band
  integer :: iba                    ! baseline
  complex :: z                      ! complex amplitude
  real :: a                         ! amplitude factor
  logical :: error                  !
  ! Global
  include 'clic_parameter.inc'
  include 'clic_dheader.inc'
  include 'clic_par.inc'
  include 'clic_clic.inc'
  ! Local
  complex :: zscale(mrlband,2,mnbat)
  real :: ascale(mrlband,mnant)
  common /clicscale/ zscale, ascale
  save /clicscale/
  integer :: ia, ja, ic
  complex :: zs                ! complex amplitude
  real :: phase,phase_tmp
  !------------------------------------------------------------------------
  ! Code:
  error = .false.
  a = abs(z)
  if (a.eq.0) then
    a = 1
    return
  endif
  zs = zscale(is,isb,iba)
  !
  ! ATMOSPHERIC CORRECTION
  !   needed here, since it changes at every record
  !   do_phase_mon: use total power monitor correction
  !   do_phase_wvr: use wvr correction (note dpath is in micrometers)
  !
  ia = r_iant(iba)
  ja = r_jant(iba)
  !
  ! total power correction
  !      IF (DO_PHASE_ATM .AND.
  !     $((R_NREC_MON.GT.0).OR.DO_PHASE_NOFILE)) THEN
  if (do_phase_mon(ia) .and. do_phase_mon(ja)) then
    phase =   &
      - phase_corr(isb,ja)*(dh_test1(2,ja)-r_csky_mon(ja))   &
      + phase_corr(isb,ia)*(dh_test1(2,ia)-r_csky_mon(ia))
    zs = zs * cmplx(cos(phase),-sin(phase))
  endif
  !
  ! wvr correction
  if (do_phase_wvr(ia) .and. do_phase_wvr(ja) ) then
    phase_tmp = 0.0
    do ic=1,mwvrch
      phase_tmp = phase_tmp + (dh_wvr(ic,ja)-r_wvrref(ic,ja))   &
        *r_wvrtcal(ic,ja)*r_wvrdpath(ic,ja)/1000.
    enddo
    if (do_phase_wvr_e(ja)) then
      phase_tmp=phase_tmp*r_wvrfpath(1,ja)
    endif
    phase = - phase_corr(isb,ja)*phase_tmp
    phase_tmp = 0.0
    do ic=1,mwvrch
      phase_tmp = phase_tmp + (dh_wvr(ic,ia)-r_wvrref(ic,ia))   &
        *r_wvrtcal(ic,ia)*r_wvrdpath(ic,ia)/1000.
    enddo
    if (do_phase_wvr_e(ia)) then
      phase_tmp=phase_tmp*r_wvrfpath(1,ia)
    endif
    phase = phase + phase_corr(isb,ia)*phase_tmp
    zs = zs * cmplx(cos(phase),-sin(phase))
  endif
  !
  ! tot.power and wvr correction
  if (do_phase_mon(ia) .and. do_phase_wvr(ja)) then
    phase_tmp = 0.0
    do ic=1,mwvrch
      phase_tmp = phase_tmp + (dh_wvr(ic,ja)-r_wvrref(ic,ja))   &
        *r_wvrtcal(ic,ja)*r_wvrdpath(ic,ja)/1000.
    enddo
    if (do_phase_wvr_e(ja)) then
      phase_tmp=phase_tmp*r_wvrfpath(1,ja)
    endif
    phase = - phase_corr(isb,ja)*phase_tmp   &
      + phase_corr(isb,ia)*(dh_test1(2,ia)-r_csky_mon(ia))
    zs = zs * cmplx(cos(phase),-sin(phase))
  endif
  !
  ! wvr and tot.power correction
  if (do_phase_mon(ja) .and. do_phase_wvr(ia)) then
    phase_tmp = 0.0
    do ic=1,mwvrch
      phase_tmp = phase_tmp + (dh_wvr(ic,ia)-r_wvrref(ic,ia))   &
        *r_wvrtcal(ic,ia)*r_wvrdpath(ic,ia)/1000.
    enddo
    if (do_phase_wvr_e(ia)) then
      phase_tmp=phase_tmp*r_wvrfpath(1,ia)
    endif
    phase = phase_corr(isb,ia)*phase_tmp   &
      - phase_corr(isb,ja)*(dh_test1(2,ja)-r_csky_mon(ja))
    zs = zs * cmplx(cos(phase),-sin(phase))
  endif
  !
  z = z * zs
  if (z.ne.0) then
    a = abs(z)/a
  else
    a = 1
  endif
  return
end subroutine scaling
!
subroutine ascaling (ia,is,az,a,error)
  use classic_api  
  !---------------------------------------------------------------------
  ! This is used to rescale autocorrelation
  ! (actually only AMPLITUDE RAW = unapply atmospheric calibration)
  !
  ! created 2000-10-20 RL
  !---------------------------------------------------------------------
  integer :: ia                     ! antenna
  integer :: is                     ! subband
  real :: az                        ! amplitude factor
  real :: a                         ! amplitude factor
  logical :: error                  !
  ! Global
  include 'clic_parameter.inc'
  include 'clic_dheader.inc'
  include 'clic_par.inc'
  include 'clic_clic.inc'
  ! Local
  complex :: zscale(mrlband,2,mnbat)
  real :: ascale(mrlband,mnant)
  common /clicscale/ zscale, ascale
  save /clicscale/
  !------------------------------------------------------------------------
  ! Code:
  error = .false.
  a = ascale(is,ia)
  if (a.eq.0 .or. az.eq.0) then
    a = 1
    return
  endif
  az = az * ascale(is,ia)
  return
end subroutine ascaling
