;+
; NAME:
;     RELVIS
; PURPOSE:
;     Determines relative visibility, V(S)/V(0), where V(s) is the visibility
;     as a function of fringe spacing s, and V(0) is the visibility at zero
;     fringe spacing, i.e. total power.  The relative visibility is independent
;     of calibration, and will be unity for a point (unresolved) source but
;     will decrease with increasing s for a resolved one.
; CATEGORY:
;     OVRO APC ANALYSIS
; CALLING SEQUENCE:
;     rv = relvis(filename[,tp][,tpmin=tpmin])
; INPUTS:
;     filename  the name of the file containing output data from ANALYZE
;                 *after* preflare subtraction.  If preflare subtraction
;                 has not been done, the results will be invalid.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     tpmin     if set, gives the minimum total power value for which to
;                 determine the relative visibility.  If omitted, 5 sfu is
;                 the minimum value.
; ROUTINES CALLED:
; OUTPUTS:
;     rv        the relative visibility of size (NBL,NF,NTIMES) for each
;                 baseline.  It will contain NaN where the total power is
;                 less than TPMIN.
;     tp        optional output containing the calibrated total power
;                 used in determining RV, of size (NANT,NF,NTIMES).
; COMMENTS:
;     Because of the strange way that OVSA measures polarization, the
;     strict relative visibility for circular polarization involves a
;     fudge factor ranging from 0 to 1, depending on the polarization
;     of the source.  Write polarization measurements on baselines as Rij
;     and Lij, and linear polarization measurements as Iij, where ij are
;     antenna numbers.  Write measurements in total power as Ai, where Ai
;     are in general (Ri + Li), but for some antennas R and/or L are not
;     measured at all.  Thus, what is actually measured in total power is:
;      Antenna      RCP position        LCP position
;       A1          I1 = (R1 + L1)      L1
;       A2          R2                  I2 = (R2 + L2)
;       An>2        In = (Rn + Ln)      In = (Rn + Ln)
;     The corresponding baseline correlated amplitudes are
;      Baseline     RCP position        LCP position
;       A12         sqrt(R1*R2)         sqrt(L1*L2)
;       A1n         sqrt(I1*In)         sqrt(L1*Ln)
;       A2n         sqrt(R2*Rn)         sqrt(I2*In)
;       others      sqrt(Im*In)         sqrt(Im*In)
;     The fudge factors for the relative visibilities will then be
;     (from, e.g. RV = Aij/sqrt(Ai*Aj))
;      Baseline     RCP position        LCP position
;       A12         1/sqrt(1+L1/R1)     1/sqrt(R2/L2+1)
;       A1n         1                   1/sqrt(Rn/Ln+1)
;       A2n         1/sqrt(1+Ln/Rn)     1
;       others      1                   1
;     These fudge factors range from 0 to 1, depending on the polarization
;     of the source, as follows:
;             __Unpol'd__     _100% RCP_     _100% LCP_
;      BL      RCP   LCP       RCP   LCP      RCP   LCP
;      A12    0.707 0.707       1     0        0     1
;      A1n      1   0.707       1     0        1     1
;      A2n    0.707   1         1     1        0     1
;      oth      1     1         1     1        1     1
;
;     The relative visibility of a point source would then have these values,
;     and in order to convert this to unity, as required for a point source,
;     the RV will be divided by these values.  Note that RV is only useful for
;     simple sources, so we will make the approximation that the total power
;     polarization is the true source polarization.
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 04-Aug-2001 by Dale E. Gary
;     21-Nov-2001  DG
;       Fixed a couple of errors.
;     27-Dec-2001  DG
;       Removed subtraction of preflare, since it can be done much better
;       in OVSA_PRESUB.
;-
function relvis,file,tp,tpmin=tpmin

   if (n_elements(file) eq 0) then file = dialog_pickfile(path=!defaults.workdir,filter='*.sav')
   if (file eq '') then return,-1
   restore,file

   ntimes = n_elements(tavg)
   nf = n_elements(f)
   nant = refcal.nant  ; Number of antennas
   nbl = refcal.nbl    ; Number of baselines
   if (size(avg,/n_dim) eq 3) then npol = 1 else npol = refcal.npol  ; Number of polarizations in data
   reffac = (*refcal.pfactors)  ; Extract REFCAL amplitude/TP factors

   antstr = ['1','2','4','5','6','7']
   ; Apply calibration, and keep only TP part
   cal = apply_cal_all(tavg,avg,f,refcal)
   if (npol gt 1) then begin
      tpc = cal[0:nant-1,*,*,2]    ; Save calibrated I TP
      tp = avg[0:nant-1,*,*,2]     ; Uncalibrated
      tprc = reform(cal[1,*,*,0])  ; For R poln, save R for ant 2 in TP
      tplc = reform(cal[0,*,*,1])  ; For L poln, save L for ant 1 in TP
   endif else begin
      tpc = cal[0:nant-1,*,*]  ; If only 1 poln, assume I
      tp = avg[0:nant-1,*,*]   ; Uncalibrated
   endelse

   ; Now determine TP polarization if NPOL > 1
   if (npol gt 1) then begin

   endif

   y = indgen(nbl)*2 + nant    ; Channel numbers of sin channels
   x = y + 1                   ; Channel numbers of cos channels
   amp = sqrt(avg[x,*,*,0]^2 + avg[y,*,*,0]^2)   ; Amplitudes of baselines

   ; Generate a parallel array to the Amplitude array, with the quantity
   ; sqrt(T_i*T_j) for baseline i-j.
   tpbl = fltarr(nbl,nf,ntimes)
   tpblsfu = tpbl   ; Parallel array to TPBL, but calibrated in SFU
   k = 0
   bl_str = strarr(nbl)
   ants = [1,2,4,5,6,7]
   for iant = 0, nant-2 do for jant = iant+1, nant-1 do begin
      tpbl[k,*,*] = sqrt(tp[iant,*,*]*tp[jant,*,*])
      tpblsfu[k,*,*] = sqrt(tpc[iant,*,*]*tpc[jant,*,*])
      bl_str[k] = string(ants[iant],ants[jant],format='(I1,"-",I1)')
      k = k + 1
   endfor

   ; Simple calculation to get Relative Visibility!
   rv = amp/tpbl

   ; When TPBL is too small, RV will not be significant, so blank values
   ; where the total power is less than about 5 SFU
   bad = where(tpblsfu lt 5.0,nbad)
   if (nbad ne 0) then rv[bad] = !values.f_nan

;   window,/free,xsiz=100*5,ysiz=100*3
;   tvscl,congrid(alog10(rotate(reform(tp[1,*,200:239]>1),-5)),100,100),0

;   s = [1,74,93,33.,92,28,37,26,48,70,32,50,51,144,48]
;   ss = reverse(sort(s))
;   for i = 1, nbl-1 do begin
;      tvscl,congrid(rotate(reform(rv(ss[i-1],*,200:239))>0<1,-5),100,100),i
;      xyouts,2+(i mod 5)*100,(2-i/5)*100+20,bl_str[ss[i-1]],color=255,/dev
;   endfor

return,rv
end
