; RLDIF
;---------------------------------------------------------------
;! determines Right minus Left phase difference, corrects cal files
;# Task UV Calibration polarization
;-----------------------------------------------------------------------
;;  Copyright (C) 2004, 2006-2007, 2009-2011, 2013, 2018-2019
;;  Associated Universities, Inc. Washington DC, USA.
;;
;;  This program is free software; you can redistribute it and/or
;;  modify it under the terms of the GNU General Public License as
;;  published by the Free Software Foundation; either version 2 of
;;  the License, or (at your option) any later version.
;;
;;  This program is distributed in the hope that it will be useful,
;;  but WITHOUT ANY WARRANTY; without even the implied warranty of
;;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;  GNU General Public License for more details.
;;
;;  You should have received a copy of the GNU General Public
;;  License along with this program; if not, write to the Free
;;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,
;;  MA 02139, USA.
;;
;;  Correspondence concerning AIPS should be addressed as follows:
;;         Internet email: aipsmail@nrao.edu.
;;         Postal address: AIPS Project Office
;;                         National Radio Astronomy Observatory
;;                         520 Edgemont Road
;;                         Charlottesville, VA 22903-2475 USA
;-----------------------------------------------------------------------
RLDIF     LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
RLDIF:  Task to return/apply Right - Left phase difference
INNAME                             UV data (name).
INCLASS                            UV data (class).
INSEQ             0.0    9999.0    UV data (seq. #).  0 => high
INDISK                             Disk unit #.       0 => any
CALSOUR                            Calibration source list
CALCODE                            Calibrator code '    '=>all
TIMERANG                           Time range to list
SELBAND                            Bandwidth to select (kHz)
SELFREQ                            Frequency to select (MHz)
FREQID                             Freq. ID to select.
                                   None selected => 1.
BIF               0.0      100.0   Lowest IF number 0=1
EIF               0.0      100.0   Highest IF number
BCHAN             0.0     2048.0   Low channel number 0=>1
ECHAN             0.0     2048.0   High channel number
ANTENNAS                           Antennas to list
UVRANGE           0.0              UV range in kilolambda
SUBARRAY          0.0     1000.0   Subarray, 0=>1
                                   Cal. info for input:
DOCALIB          -1.0      101.0   > 0 calibrate data & weights
                                   > 99 do NOT calibrate weights
GAINUSE                            CAL (CL or SN) table to apply
DOPOL            -1.0       10.0   If >0 correct polarization.
PDVER                              PD table to apply (DOPOL>0)
BLVER                              BL table to apply.
FLAGVER                            Flag table version
DOBAND           -1.0       10.0   If >0 apply bandpass cal.
                                   Method used depends on value
                                   of DOBAND (see HELP file).
BPVER                              Bandpass table version
SMOOTH                             Smoothing function. See
                                   HELP SMOOTH for details.
DOAPPLY          -1.0       1.0    > 0 => apply to CL or BP
                                   table now
POLANGLE                           Polarization angle for
                                   CALSOUR in source # order
CALIN                              Text file listing cal source
                                   Q and U by frequency.
SPECTRAL         -1.0       1.0    > 0 do spectral solution
                                   using PD table
INTPARM                            Smoothing parameters for
                                   spectral mode
DOPRINT          -3.0     132.0    > 0 -> use the terminal,
                                   else use the line printer
                                   > 72 => terminal width
                                   = 0 -> no printing
OUTPRINT
                                   Printer disk file to save
BADDISK                            Disk to avoid for scratch.
CLCORPRM @                         R-L phase difference returned
                                   if SPECTRAL <= 0
----------------------------------------------------------------
RLDIF
Type:  Task
Use:   Determines the right minus left polarization phase difference
       by comparing the phases of the RL and LR visibilities to the
       expected phase.  The expected phase of RL and LR* is ATAN2(U,Q)
       which is twice the polarization position angle, as a function
       of IF and/or spectral channel.  Note that this phase difference
       arises because the right and left phases are separately
       referenced with nothing in CALIB and BPASS to force the two to
       a common reference.

       RLDIF can be run in an IF-dependent fashion (SPECTRAL <= 0).
       In this mode, it can print matrix listings of RL and LR* which
       can be examined for bad data and/or other issues.  RLDIF
       returns the mean phases in the CLCORPRM adverb.  They must be
       corrected before they are used in CLCOR or RLCOR:
          FOR I=1:20; CLCORP(I) = EXPECT-CLCORP(I); END
       where EXPECT is the expected R-L phase (twice the source
       polarization angle).  The printing in RLDIF may be suppressed.
       Note that RLCOR itself may be used to apply the R-L correction
       to the CL table, the AN table (PCAL D terms), and the SU table
       (calibrator Q and U).  Set DOAPPLY=1 for this.  A new CL table
       is created, but the changes to the SU and AN table may not be
       reversed simply.  (A TASAV before RLDIF might be a good idea.)

       RLDIF may also be used in a fully channel-dependent mode
       (SPECTRAL > 0).  In this mode, the matrix printing is
       suppressed, but the answers and rmses may be (should be)
       printed.  If DOAPPLY > 0, the BP, PD, and CP tables are
       corrected, with new versions being written for each.

       The RMSes printed are meant to be the uncertainties in the mean
       values.
Adverbs:
  INNAME.....UV file name (name).       Standard defaults.
  INCLASS....UV file name (class).      Standard defaults.
  INSEQ......UV file name (seq. #).     0 => highest.
  INDISK.....Disk unit #.               0 => any.
  CALSOUR....List of calibration sources to be used. '  '=> all; if
             any starts with a '-' then all except ANY source named.
  CALCODE....Calibrators may be selected on the basis of the
             calibrator code given in the SU table.
                  '    ' => any calibrator code selected
                  '*   ' => any non blank code (cal. only)
                  '-CAL' => blank codes only (no calibrators)
                  anything else = calibrator code to select.
             NB: The CALCODE test is applied in addition to the
             other selection tests
  TIMERANG...Time range of the data to be used and listed. In order:
                Start day, hour, min. sec,
                end day, hour, min. sec.
             Days relative to reference date.
  SELBAND....Bandwidth of data to be selected. If more than one IF is
             present SELBAND is the width of the first IF required.
             Units = kHz, 0=> all
  SELFREQ....Frequency of data to be selected. If more than one IF is
             present SELFREQ is the frequency of the first IF
             required. Units = MHz, 0=> all
  FREQID.....Frequency identifier to select.  If either SELBAND or
             SELFREQ are set, their values overide that of FREQID.
             However, setting SELBAND and SELFREQ may result in an
             ambiguity.  In that case the task will request that you
             use FREQID.  If neither SELBAND, SELFREQ nor FREQID are
             specified then the first FQ id in the FQ table (usually
             1) will be used.
  BIF........IF to list - first returned.  0 -> 1
  EIF........Last IF listed and returned.  0 -> BIF+19 or max
             whichever is smaller.
  BCHAN......First channel to average. 0=> 1
             When SPECTRAL > 0, channels < BCHAN are corrected but
             using smoothed corrections from channels BCHAN and
             greater.  All channels are used to find solutions
             however.
  ECHAN......Last channel to average.  0=> Highest
             When SPECTRAL > 0, all channels are used to find
             solutions.  However, the corrections for channels > ECHAN
             are determined by the solutions for channels <= ECHAN.
  ANTENNAS...A list of the antennas to list.  If any number is
             negative then the antennas specified are not listed
             and all others are.  All 0 => list all.
  UVRANGE....Range of projected spacings to be listed in 1000's of
             wavelengths.  0  =>  1, 1.E10
  SUBARRAY...Subarray number to list. 0=>1.
  DOCALIB....If true (>0), calibrate the data using information in the
             specified Cal (CL) table for multi-source or SN table for
             single-source data.  Also calibrate the weights unless
             DOCALIB > 99 (use this for old non-physical weights).
  GAINUSE....Version number of the Cal. table to apply to the
             data if DOCALIB=1.  Refers to a CL table for
             multisource data of an SN table for single source.
             0 => highest.  Used for OPTYPE='MATX','LIST'.
  DOPOL......If > 0 then correct data for instrumental polarization as
             represented in the AN or PD table.  This correction is
             only useful if PCAL has been run or feed polarization
             parameters have been otherwise obtained.  See HELP DOPOL
             for available correction modes: 1 is normal, 2 and 3 are
             for VLBI.  1-3 use a PD table if available; 6, 7, 8 are
             the same but use the AN (continuum solution) even if a PD
             table is present.
  PDVER......PD table to apply if PCAL was run with SPECTRAL true and
             0 < DOPOL < 6.  <= 0 => highest.
  BLVER......Version number of the baseline based calibration
             (BL) table to appply. <0 => apply no BL table,
             0 => highest.
  FLAGVER....Specifies the version of the flagging table to be
             applied.  0 => highest numbered table.  <0 => no flagging
             to be applied.
  DOBAND.....If true (>0) then correct the data for the shape of the
             antenna bandpasses using the BP table specified by BPVER.
             The correction has five modes:
             (a) if DOBAND=1 all entries for an antenna in the table
             are averaged together before correcting the data.
             (b) if DOBAND=2 the entry nearest in time (including
             solution weights) is used to correct the data.
             (c) if DOBAND=3 the table entries are interpolated in
             time (using solution weights) and the data are then
             corrected.
             (d) if DOBAND=4 the entry nearest in time (ignoring
             solution weights) is used to correct the data.
             (e) if DOBAND=5 the table entries are interpolated in
             time (ignoring solution weights) and the data are then
             corrected.
  BPVER......Specifies the version of the BP table to be applied.
             <0 => no bandpass correction done.
  SMOOTH.....Specifies the type of spectral smoothing to be applied to
             a uv database . The default is not to apply any smoothing.
             The elements of SMOOTH are as follows:
             SMOOTH(1) = type of smoothing to apply: 0 => no smoothing
               To smooth before applying bandpass calibration
                 1 => Hanning, 2 => Gaussian, 3 => Boxcar, 4 => Sinc
               To smooth after applying bandpass calibration
                 5 => Hanning, 6 => Gaussian, 7 => Boxcar, 8 => Sinc
             SMOOTH(2) = the "diameter" of the function, i.e. width
               between first nulls of Hanning triangle and sinc
               function, FWHM of Gaussian, width of Boxcar. Defaults
               (if < 0.1) are 4, 2, 2 and 3 channels for SMOOTH(1) =
               1 - 4 and 5 - 8, resp.
             SMOOTH(3) = the diameter over which the convolving
               function has value - in channels.  Defaults: 1,3,1,4
               times SMOOTH(2) used when input SMOOTH(3) < net
               SMOOTH(2).
  DOAPPLY....False (<= 0) => pass the results back to AIPS in CLCORPRM
                   if SPECTRAL is false and display results in the
                   message window.
             True  (> 0)  => copy the GAINUSE CL table to the
                   highest+1 and correct the L phases (when SPECTRAL
                   is false).  Otherwise, copy the BPVER bandpass
                   table and apply the L phases when SPECTRAL is
                   true.
  POLANGLE...Polarization angle of the included sources in order of
             their source number in the data set (may or may not be
             the order of names in the CALSOUR adverb).  If 0.0 and the
             source is a recognized one (e.g. 3C286, 3C147, 3C138,
             3C48), then the task knows correct (likely?) values as a
             function of frequency.  Otherwise, this parameter must be
             provided when DOAPPLY > 0.  Values are replaced with
             those from CALIN if any.  The value for 3C286 depends
             slightly on frequency beginning July 24, 2018.  3C48,
             3C138, and 3C147 are found from table lookup to be
             significant functions of frequency.
  CALIN......Name of text file containing the calibration source Q and
             U values as a function of frequency.  The lines in the
             text file give the frequency in GHz, Q and U or
             polarization angle, and source number in that order in
             free format.  If there is only one calibration source
             then the source number may be omitted or 0.  Limit is 4
             sources for any number of frequencies (within current
             AIPS limits).  Note that the SU table and the CP table
             cannot be used for this purpose since the values in them
             are corrupted by the unknown R-L phase for which we are
             trying to solve.  The text file format is described below
             in detail.
  SPECTRAL...False (<= 0) => average spectral channels BCHAN tthrough
                   ECHAN and apply the solution through the CL table
                   or CLCORPRM on an IF basis.
             True  (> 0)  => find the R-L phase difference on a
                   channel by channel basis and, if DOAPPLY > 0, apply
                   the result through the BP table.  DOPRINT and
                   OUTPRINT allow a text file suitable for plotting to
                   be produced.
  INTPARM....After the phase corrections are determined, they may be
             smoothed in frequency further using the INTPARM selected
             function.  This is to provide better S/N than one would
             have with unsmoothed single channels.
             INTPARM(1) = type of smoothing to apply:
               0 => no smoothing
               1 => Hanning
               2 => Gaussian
               3 => Boxcar
               4 => Sinc (i.e. sin(x)/x)
             INTPARM(2) = the "diameter" of the function, i.e. width
               between first nulls of Hanning triangle and sinc
               function, FWHM of Gaussian, width of Boxcar. Defaults
               (if < 0.1) are 4, 2, 2 and 3 channels for INTPARM(1) =
               1 - 4.
             INTPARM(3) = the diameter over which the convolving
               function has value - in channels.  Defaults: 1, 3, 1, 4
               times INTPARM(2) used when input INTPARM(3) <
               INTPARM(2) (after application of defaults).
  DOPRINT....For DOLINE <= 0, the printing option is for MATX
             LISTR-like displays of RL and LR* phases with rmses under
             control:
                False (< 0) use the line printer if OUTPRINT = ' '
                   else write named OUTPRINT file only.
                   When OUTPRINT is not blank, DOPRINT=-2 suppresses
                   the page-feed character on page headers and
                   DOPRINT=-3 suppresses page headers and most other
                   header information.
                = 0   no printing just return answer.
                True  (> 0) use the terminal interactively.  The task
                   will use the actual terminal width as a display
                   limit unless 72 < DOPRINT < width.  In that case, the
                   display limit will be DOPRINT characters.
             For DOLINE > 0, any DOPRINT not equal 0 will cause a text
             file to be written to OUTPRINT if that adverb is not
             blank.  This text file will be suitable input to PLOTR.
             If DOPRINT > 0, this file contains separate lists for each
             source and excludes channels outside BCHAN and ECHAN.
             If DOPRINT < 0, the smoothed and extrapolated and averaged
             over sources correction data are shown instead.
  OUTPRINT...For DOLINE <= 0, disk file name in which to save the line
                printer output.  ' ' => use scratch and print
                immediately for interactive jobs - batch jobs use
                OUTPRINT = 'PRTFIL:BATCHjjj.nnn' (jjj= job #, nnn =
                user #).  When OUTPRINT is not blank, multiple outputs
                are concatenated, and the file is not actually
                printed.
             For DOLINE > 0, if not ' ', the disk file name of a file
                to contain a text file which, when fed to PLOTR, can
                make a plot of the spectrum of the corrections.
  BADDISK....Disk numbers to avoid for scratch files.  Scratch
             files may be created by the sorting routines if
             calibration or flagging is applied.
  CLCORPRM...OUTPUT adverb: right-left phase difference in degrees for
             IFs BIF through BIF+19.    The self-consistent mean
             phases so determined are returned in the adverb CLCORPRM
             - but must be corrected before they are used in CLCOR or
             RLCOR:
                 FOR I=1:20; CLCORP(I) = EXPECT-CLCORP(I); END
             where EXPECT is the expected R-L phase (twice the source
             polarization angle).

CALIN file format:
   1. Begins with a line which defines the contents of the file
         ;FQUS   for columns of frequency, Q, U, and source number.
         ;FAS    for columns of frequency, polarization angle, and
                 source number
   2. Comment lines at any point begin in column 1 with either a
      ; or a # character.
   3. Data lines contain the specified type of data columns:
         ;FQUS   frequency in GHz, Q, U in the same units, and
                 optionally source number
         ;FAS    frequency in GHz, polarization angle in degrees
                 (= ATAN2 (U, Q) / 2.0), and optionally source number
      The source number may be omitted or set to 0 if there is only
      one source included.  Source number is an integer and all
      numbers are free format separated by one or more blank
      characters.

Example 1:
;FQUS
# QUOUT run 12-JAN-2011 11:24:35 using CP version    2
  4.988000000    0.348104    0.780174      0
  4.990000000    0.348104    0.780174      0
  4.992000000    0.346920    0.780659      0
  4.994000000    0.344028    0.781819      0
  4.996000000    0.338668    0.783813      0
  4.998000000    0.336427    0.784259      0

Example 2:
;FAS
# QUOUT run 12-JAN-2011 11:27:03 using CP version    2
  4.988000000    32.97708      0
  4.990000000    32.97708      0
  4.992000000    33.01998      0
  4.994000000    33.12441      0
  4.996000000    33.31594      0
  4.998000000    33.39096      0
----------------------------------------------------------------
