subroutine solve_flux(line,error)
  use gildas_def
  use gkernel_interfaces
  use classic_api
  use clic_rdata
  !---------------------------------------------------------------------
  ! 	Calculate the flux of sources in the current index,
  !	or the efficiency (JY_TO_KEL) if the flux is known
  !       /RESET : reset all unknown fluxes to zero.
  !---------------------------------------------------------------------
  character(len=*) :: line          !
  logical :: error                  !
  ! Global
  include 'clic_parameter.inc'
  include 'clic_clic.inc'
  include 'clic_display.inc'
  include 'gbl_pi.inc'
  include 'clic_par.inc'
  include 'gbl_memory.inc'
  ! Local
  character(len=6) :: ch
  character(len=80) :: snam,filnam
  logical :: new, output, iznogoud, usereal
  integer :: iband, iant, ix, iy, jw1, jw2, old_base, p_lun, ipol, kb, kif
  integer :: i, ia, ns,  if, is, if1, ier, nch, ir, ignored
  real :: frtol
  integer :: dtol
  parameter (frtol=1e3, dtol=7)    ! 1 GHz ... 1 week ...
  real :: visi(mnant,m_flux), wisi(mnant,m_flux),solflux(mnant,m_flux)
  real :: eff_in(mnant,m_flux)
  real :: aflux, sflux(m_flux), weff(mnant), seff(mnant), wflux
  real :: fff(mnant), wfff(mnant), factor
  real :: vsflux, wsflux, vt(4,3), wt(4,3), fflux(m_flux), ff, fi, fl, efl
  logical :: end, do_phcorr, reset
  logical :: do_reference
  character(len=132) :: chain
  character(len=12) :: argum, sname(m_flux), tsource
  integer(kind=address_length) :: k, ipk, ipkc, ipkl, data_in, kin
  integer(kind=data_length)    :: ldata_in, h_offset, c_offset, l_offset
  integer :: sdate(m_flux), iv, im, n_best, ind(mnant), nnn
  integer(kind=index_length) :: dim(4)
  integer(kind=entry_length) :: ifind(10)
  !
  integer :: mvoc1, mvoc2, nkey
  parameter (mvoc1=6, mvoc2=3)
  character(len=12) :: kw, voc1(mvoc1), voc2(mvoc2)
  data voc1/'CORRECTED','UNCORRECTED','REFERENCED',   &
    'NOREFERENCED','BEST','REAL'/
  data voc2/'OLD','NEW','FLUX'/
  !
  common /theflux/  seff, sflux, ns
  save /theflux/
  save sname
  !------------------------------------------------------------------------
  ! Code:
  ipol = 1 ! Dummy
  kb = 1   
  kif =1 
  save_scale = do_scale
  ! Verify if any input file
  call check_input_file(error)
  if (error) return
  !
  call check_index(error)
  if (error) return
  !
  output = .false.
  do_phcorr = .false.
  do_reference = .true.
  n_best = 3
  usereal = .false.
  if (sic_narg(0).ge.2) then
    i = 2
    do while (i.le.sic_narg(0))
      argum = 'UNCORRECTED'
      call sic_ke(line,0,i,argum,nch,.false.,error)
      i = i+1
      if (error) goto 999
      call sic_ambigs('SOLVE FLUX',argum,kw,nkey,voc1,mvoc1,error)
      if (error) goto 999
      if (kw.eq.'CORRECTED') then
        do_phcorr = .true.
      elseif (kw.eq.'UNCORRECTED') then
        do_phcorr = .false.
      elseif (kw.eq.'REFERENCED') then
        do_reference = .true.
      elseif (kw.eq.'NOREFERENCED') then
        do_reference = .false.
      elseif (kw.eq.'BEST') then
        call sic_i4(line,0,i,n_best,.true.,error)
        i = i+1
      elseif (kw.eq.'REAL') then
        usereal = .true.
        write (chain,'(a,i1,a)') 'Using visibility real part'   &
          //' instead of amplitude'
        call message(8,2,'SOLVE_FLUX',chain(1:lenc(chain)))
      endif
    enddo
  endif
  write (chain,'(a,i0,a)') 'Average fluxes will use the best ',   &
    n_best,' antennas'
  call message(8,1,'SOLVE_FLUX',chain(1:lenc(chain)))
  !
  reset = sic_present(4,0)
  !
  output = sic_present(3,0)
  if (output) then
    call sic_ch(line,3,1,snam,nch,.true.,error)
    if (error) goto 999
    new = .false.
    i = 2
    do while (i.le.sic_narg(3))
      call sic_ke(line,3,i,ch,nch,.true.,error)
      if (error) goto 999
      call sic_ambigs('SOLVE_FLUX',ch,kw,nkey,voc2,mvoc2,error)
      if (error) goto 999
      new = new.or.(kw.eq.'NEW')
      i = i+1
    enddo
    call sic_parsef(snam,filnam,' ','.int')
    ier = sic_getlun(p_lun)
    if (new) then
      ier = sic_open (p_lun,filnam,'NEW',.false.)
      if (ier.eq.0) then
        call user_info(snam)
        write(p_lun,2001) '! '
        write(p_lun,2001) '! CLIC\SOLVE FLUX /OUT '   &
          //filnam(1:lenc(filnam))//   ' FLUX NEW '
        write(p_lun,2001) '! '//snam(1:70)
        write(p_lun,2010)
      endif
    else
      ier = sic_open (p_lun,filnam,'APPEND',.false.)
    endif
    if (ier.ne.0) then
      call message(6,3,'SOLVE_FLUX','Cannot open file '//filnam)
      call messios(6,3,'SOLVE_FLUX',ier)
      error = .true.
      call sic_frelun(p_lun)
      return
    endif
  endif
  !
  if (reset) then
    k = 1
    do i=1, n_flux
      if (f_flux(i)) then
        f_flux(k) = .true.
        flux(k) = flux(i)
        c_flux(k) = c_flux(i)
        freq_flux(k) = freq_flux(i)
        date_flux(k) = date_flux(i)
        k = k+1
      endif
    enddo
    n_flux = k-1
  endif
  ! check if flux list contains a reference flux
  if (do_reference) then
    k = 0
    do i=1, n_flux
      if (f_flux(i)) then
        k = k+1
      endif
    enddo
    if (k.eq.0) then
      call message(6,3,'SOLVE_FLUX',   &
        'No source of known flux in flux list')
      error = .true.
      return
    endif
  else
    call message(4,1,'SOLVE_FLUX',   &
      'Using stored efficiencies to compute fluxes')
  endif
  jw1 = iw1(k_subb(1))
  jw2 = iw2(k_subb(1))
  !
  ! Select either real part (IY=3) or amplitude (IY=1, default)
  ix = 10
  iy = 1
  if (usereal) then
    iy = 3
  endif
  iband = i_band(k_band(1))
  ignored = 0
  !
  do_scale = .true.
  do_amplitude = .false.
  do_flux = .false.
  call show_general('AMPLITUDE',.false.,line,error)
  if (error) goto 999
  !
  old_base = i_base(1)
  if (i_base(1).gt.0) call switch_antenna
  call set_display(error)
  !
  ! Count sources in current index, store known fluxes and visibilities
  call get_first(.true.,error)
  if (error) goto 999
  call check_subb(1,.true.,error)
  if (error) goto 999
  ns = 0
  tsource = ' '
  end = .false.
  do while (.not. end)
    is = 0
    if (ns.ge.1) then
      do i=1, ns
        if (r_sourc.eq.sname(i)   &
          .and. abs(r_restf-fflux(i)).lt.frtol) then
          is = i
        endif
      enddo
    endif
    if (is.eq.0) then
      ns = ns + 1
      sname(ns) = r_sourc
      fflux(ns) = r_restf
      sdate(ns) = r_dobs
      if (r_flux.eq.0) then
        sflux(ns) = -1.0
      else
        sflux(ns) = -abs(r_flux)
      endif
      !
      ! Check if by chance flux is already known
      do if = 1, n_flux
        if (f_flux(if) .and. c_flux(if).eq.sname(ns) .and.   &
          ((freq_flux(if).le.0)  .or.   &
          (abs(fflux(ns)-freq_flux(if)).lt.frtol)) .and.   &
          ((date_flux(if).lt.-100000)   &
          .or. (abs(date_flux(if)-sdate(ns)).le.dtol))) then
          sflux(ns) = flux(if)
        endif
      enddo
      do ia = 1, r_nant
        visi(ia,ns) = 0
        wisi(ia,ns) = 0
        !cc NGRX: Use the efficience for Polarization 1 !!!
        eff_in(ia,ns) = r_jykel(1,ia)
      enddo
      is = ns
    endif
    ! Check subband group is OK
    call check_subb(1,.true.,error)
    if (error) goto 200
    if (do_pass.and..not.do_pass_memory) then
      if (do_pass_spectrum) then
        nnn = 1
        call fix_bp(nnn,ifind,error)
        if (nnn.le.0) then
          call message(8,3,'SOLVE_FLUX','No BANDPASS scan found')
          ignored = ignored + 1
          goto 200
        endif
      else
        if (do_pass_antenna .and. r_abpc.eq.0) then
          call message(6,2,'SOLVE_FLUX',   &
            'No Antenna RF Passband Calibration, data ignored')
          ignored = ignored + 1
          goto 200
        elseif (.not.do_pass_antenna .and. r_bpc.eq.0) then
          call message(6,2,'SOLVE_FLUX',   &
            'No Baseline RF Passband Calibration, data ignored')
          ignored = ignored + 1
          goto 200
        endif
      endif
    endif
    if (r_lmode.gt.1) then
      call message(6,2,'SOLVE_FLUX',   &
        'Autocorrelation scan ignored.')
      ignored = ignored + 1
      goto 200
    endif
    call get_data (ldata_in,data_in,error)
    if (error) goto 200
    if (do_pass) then
      call set_pass(r_nsb,r_nband,r_nbas+r_ntri,   &
        r_lntch, passc, passl, error)
      if (error) goto 200
    endif
    call set_corr(error)
    !
    ! Do not loop on records : use average for scan
    !
    call spectral_dump(ir,0,0)
    kin = gag_pointer(data_in,memory)
    ipk = kin  + h_offset(ir)
    call decode_header(memory(ipk))
    call set_scaling (error)
    if (error) return
    !
    ff = r_restf*1e-3
    fi = (r_restf-2*r_isb*r_fif1)*1e-3
    do ia = 1, n_base
      iant = -i_base(ia)
      call spectral_dump(ir,iant,0)
      ipkc = kin + c_offset(ir)
      ipkl = kin + l_offset(ir)
      do iv=1,4
        do im=1,3
          vt(iv,im) = 0
          wt(iv,im) = 0
        enddo
      enddo
      call arecord (r_nsb, r_nband, r_nbas, r_lntch,   &
        memory(ipkc),memory(ipkl),   &
        passc, passl, iant, iband, ipol, kb, kif, l_subb(1), i_subb(1,1),   &
        jw1,jw2,ix,iy, vt, wt, do_phcorr,error)
      if (error) goto 999
      visi(ia,is) = visi(ia,is) + vt(2,2)
      wisi(ia,is) = wisi(ia,is) + wt(2,2)
      !
      ! For flux output : printout 2 lines for each scan, and each antenna
      ! (compatibility with CLASS printouts)
      if (output.and.wt(2,2).gt.0) then
        call datec (r_dobs,chain,error)
        fl = vt(2,2)/wt(2,2)*abs(sflux(is))
        efl = abs(sflux(is))*1e-3/sqrt(wt(2,2))
        !cc NGRX: Give the efficiency for Polar 1 !!!!!!!!!!!!!!!
        do k=1,0,-1
          write(p_lun,2011) r_num, r_scan, k, 0d0, 0d0, 0d0,   &
            0.0, 0.0, iant, 1.0, 0.0, fl, efl,   &
            r_gim(1,iant), ff, fi, sname(is),chain(1:11)
        enddo
      endif
    enddo
200 error = .false.
    call get_next(end,error)
    if (error) goto 999
    if (sic_ctrlc()) then
      error = .true.
      goto 900
    endif
  enddo
  if (ignored.gt.0) then
    write(chain,'(i6,a)') ignored, ' ignored scans.'
    call message(6,2,'SOLVE_FLUX',chain(1:lenc(chain)))
  endif
  !
2011 format(1x,i8,i6,i3,3(1x,f8.3),1x,   &
    f9.2,1x,f8.2,1x,i2,1x,f9.2,1x,f8.2,1x,   &
    1pg10.3,1x,1pg10.3,1x,0pf6.2,2(1x,f8.3),1x,'''',a,'''',   &
    1x,'''',a,'''')
  do i = 1, ns
    do ia = 1, n_base
      if (wisi(ia,i).ne.0) then
        visi(ia,i) = visi(ia,i)/wisi(ia,i)
      elseif (sflux(i).gt.0) then
        write(chain,'(a,i2,a)') sname(i)//' antenna ',ia,   &
          ' cannot be used'
        call message(4,2,'SOLVE_FLUX',chain(1:lenc(chain)))
      endif
    enddo
  enddo
  !
  ! Get efficiencies (for sources with known flux)
  if (do_reference) then
    call sic_delvariable ('JY_PER_K',.false.,error)
    call sic_def_real ('JY_PER_K',seff,1,n_base,.false.,error)
    do ia = 1, n_base
      weff(ia) = 0
      seff(ia) = 0
    enddo
    if (do_phcorr) call message(6,1,'SOLVE_FLUX',   &
      'Amplitudes are corrected for r.m.s. phase errors')
    call message(6,1,'SOLVE_FLUX','Reference sources:')
    !
    ! Compute efficiencies
    do i=1, ns
      if (sflux(i).gt.0) then
        write(chain,1000) sname(i),sflux(i)
        call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
        ! Original formula  [ (visi/flux)*(wisi*flux**2) ]
        ! and in Scaled mode [ Scale*wisi ]
        do ia=1, n_base
          seff(ia) = seff(ia) + visi(ia,i)*wisi(ia,i)
          weff(ia) = weff(ia) + wisi(ia,i)
        enddo
      endif
    enddo
    !
    ! Check if any good efficiency:
    iznogoud = .true.
    do ia=1, n_base
      iznogoud = iznogoud .and. weff(ia).le.0
    enddo
    if (iznogoud) then
      call message(8,3,'SOLVE_FLUX',   &
        'No usable data with known flux')
      error = .true.
      if (output) then
        close (unit=p_lun)
        call sic_frelun(p_lun)
      endif
      do_scale = save_scale
      return
    endif
    call message(6,1,'SOLVE_FLUX','Average efficiencies:')
    !c NGRX: Use the efficiency for polar 1 !!!!!!
    do ia=1, n_base
      if (weff(ia).gt.0) then
        iant = -i_base(ia)
        seff(ia) = weff(ia)/seff(ia)
        write(chain,1001,iostat=ier)   &
          iant, seff(ia),1e-3/sqrt(weff(ia))*seff(ia)**2,   &
          r_jykel(1,ia)/seff(ia)
        call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
      else
        seff(ia) = 0
        write(chain,'(a,i2,a)') 'Efficiency for antenna ',ia,   &
          ' cannot be computed'
        call message(6,2,'SOLVE_FLUX',chain(1:lenc(chain)))
      endif
    enddo
  endif
  !
  ! Get fluxes (for other sources)
  call message(6,1,'SOLVE_FLUX','Sources, Fluxes and errors : ')
  do is=1, ns
    aflux = 0
    wflux = 0
    do ia=1, n_base
      iant = -i_base(ia)
      if (do_reference) then
        if (seff(ia).gt.0) then
          eff_in(ia,is) = seff(ia)
        else
          eff_in(ia,is) = 1000
        endif
      endif
      factor = eff_in(ia,is)*abs(sflux(is))
      vsflux = visi(ia,is)*factor
      wsflux = wisi(ia,is)/factor**2
      if (wsflux.ne.0) then
        write(chain,1004,iostat=ier) sname(is), iant,   &
          vsflux, 1e-3/sqrt(wsflux)
        call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
      endif
      fff(ia) = vsflux
      solflux(ia,is)= vsflux
      wfff(ia) = wsflux
    enddo
    !         CALL GR4_TRIE(FFF,IND,N_BASE,ERROR)
    call gr4_trie(eff_in(:,is),ind,n_base,error)
    !         DO IA= N_BASE, MAX(1,N_BASE-N_BEST+1), -1
    if (is.eq.1) then
      write(chain,'(i0,a,5(i0," "))') n_best," best antennas are ", ind(1:n_best)                    
      call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
    endif
    do ia= 1, n_best           !N_BASE, MAX(1,N_BASE-N_BEST+1), -1
      i = ind(ia)
      !            AFLUX = AFLUX + FFF(IA)*WFFF(I)
      aflux = aflux + fff(i)*wfff(i)
      wflux = wflux + wfff(i)
      if (wfff(i).eq.0) then
        write(chain,'(a,i0,a)') "Antenna ",i," was ignored"                    
        call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
      endif
    enddo
    if (wflux.ne.0) then
      aflux = aflux / wflux
      write(chain,1003,iostat=ier)   &
        sname(is), aflux, 1e-3/sqrt(wflux)
      call message(6,1,'SOLVE_FLUX',chain(1:lenc(chain)))
    endif
    !
    ! Compute the new fluxes for "free" sources
    if (sflux(is).le.0) then
      sflux(is) = aflux
      if1 = 0
      do if = 1, n_flux
        if (.not.f_flux(if) .and. c_flux(if).eq.sname(is)   &
          .and. (freq_flux(if).le.0 .or.   &
          (abs(freq_flux(if)-fflux(is)).lt.frtol))) then
          flux(if) = sflux(is)
          if (freq_flux(if).le.0) freq_flux(if) = fflux(is)
          date_flux(if) = sdate(is)
          f_flux(if) = .false.
          if1 = if
        endif
      enddo
      if (if1.le.0 .and. n_flux.lt.m_flux) then
        n_flux = n_flux+1
        f_flux(n_flux) = .false.
        flux(n_flux) = sflux(is)
        freq_flux(n_flux) = fflux(is)
        c_flux(n_flux) = sname(is)
        date_flux(if) = sdate(is)
      endif
    endif
  enddo
  !
  ! Keep the results in variables for calibration procedures.
  call sic_delvariable ('SOLVED',.false.,error)
  call sic_delvariable ('N_SOLVED',.false.,error)
  call sic_delvariable ('F_SOLVED',.false.,error)
  call sic_delvariable ('AF_SOLVED',.false.,error)
  call sic_def_inte    ('N_SOLVED',ns,0,0,.false.,error)
  call sic_def_charn   ('SOLVED',sname,1,ns,.false.,error)
  call sic_def_real    ('F_SOLVED',sflux,1,ns,.false.,error)
  dim(2) = ns
  dim(1) = mnant
  call sic_def_real    ('AF_SOLVED',solflux,2,dim,.false.,error)
  call sort_fluxes(error)
  do i=1, n_base
    iant = -i_base(i)
    jy_to_kel(iant) = eff_in(iant,is)
  enddo
  !
900 if (old_base.gt.0) call switch_baseline
  call set_display(error)
  if (output) then
    close (unit=p_lun)
    call sic_frelun(p_lun)
  endif
  do_scale = save_scale
  return
  !
999 error = .true.
  goto 900
  !
1000 format(1x,a,1x,'Flux = ',f8.4,' Jy')
1001 format(1x,'Ant. ',i0,2x,f7.3,' +- ',f5.3,' Jy/K  (',f5.2,')')
1003 format(1x,a,' Aver.',1x,f8.4,' +- ',f5.4)
1004 format(1x,a,' Ant ',i0,1x,f8.4,' +- ',f5.4)
2010 format(   &
    '!   Obs.#  Scan Code Azimuth   Elevation  Time  ',   &
    '     Position  ..  A#     Width      ..     Intensity',   &
    '     ..  Gain   Fsignal  Fimage Source  Date')
2001 format(a)
end subroutine solve_flux
