;+
; NAME:
;     CAL_PCLOSE
; PURPOSE:
;     Force phase closure in calibration data.
; CATEGORY:
;     OVRO APC CALIBRATION
; CALLING SEQUENCE:
;     calout = cal_pclose(calin)
; INPUTS:
;     calin    A float array of size (nc,nf,nb) where NC=5 is the number of
;                columns of calibration data (F_ghz, Amp, dAmp, Pha, dPha),
;                NF is the number of frequencies at which the calibration
;                data were taken, and NB=7 is the number of baselines for
;                which the calibration data were taken.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
;     pclose
; OUTPUTS:
;     calout  An exactly parallel array to CALIN, but with phases corrected
;                for phase closure.
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
;     This routine will have to be fixed to work with more than 5
;     antennas (7 baselines)
; MODIFICATION HISTORY:
;     Written 17-Jun-1999 by Dale E. Gary
;     01-Jul-1999  DG
;       Modified to use a more generic routine, PCLOSE(), to do most of
;       the work.
;     04-Apr-2000  DG
;       Reset phases to input phase if more than one of a triad is NaN
;     16-Jun-2000  DG
;       Made the routine more general, should work with any combination of
;       antennas provided the 12 baseline is included and is the first one.
;     04-Jan-2003  DG
;       New calibration scheme means phases close to zero, so removed 225.
;       in PCLOSE call.
;-

function cal_pclose,calin

   calout = calin
   nf = n_elements(calin[0,*,0])
   nbl = n_elements(calin[0,0,*])

   ; List of indexes for each triad of antennas, for 5 antennas
   ntriad = (nbl-1)/2
   ns1 = 1
   ne1 = ntriad
   ns2 = ne1+1
   ne2 = nbl-1
   triad_list = [0,ns1,ns2]
   if (ntriad gt 1) then begin
      for i = 1, ntriad-1 do begin
         triad_list = [[triad_list],[[0,ns1+i,ns2+i]]]
      endfor
   endif

   for i = 0, nf-1 do begin

      ; Input phases for this frequency, one for each baseline
      pin = reform(calin[3,i,*])

      ; Weights (7-element array)
      w = reform(calin[2,i,*]/calin[1,i,*])

      ; Correct the phases for all of the baselines
      calout[3,i,*] = pclose(pin,w,cor=Cor,0.0)
      calout[5,i,*] = Cor
      ; If two or more baselines of a triad are NaN, we the closed phases are
      ; not valid, so reset to input phase.
      for j = 0, ntriad-1 do begin
         good = where(finite(calin[3,i,triad_list[*,j]]),ngood)
         if (ngood lt 2) then calout[[3,5],i,triad_list[*,j]] = calin[[3,5],i,triad_list[*,j]]
      endfor
   endfor

return,calout
end