;+
; NAME:
;   RELPHZ
; PURPOSE:
;   Given a time index during a scan, uses the phases at that time
;   as the phase calibration and applies those phases to all other
;   times.  This has the effect of making the image at the given time
;   a point source at the map center, while images at other times show
;   the source structure and position relative to that at the
;   fiducial time.
; CATEGORY:
;   OVSA APC Calibration
; CALLING SEQUENCE:
;       out2 = relphz(out,calindex)
; INPUTS:
;   out		  An array containing calibrated data (the result of acting
;               on AVG array with APPLY_CAL_ALL() routine).
;   calindex  An integer value representing the time index into the OUT
;               array to use as the fiducial time (phases at that time
;               will become the phase calibration.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;       None
; ROUTINES CALLED:
; OUTPUTS:
;   out2	  A array of the same data as in OUT, except that the
;               phases are modified by using the time indicated by
;               CALINDEX as the phase calibration.
; COMMENTS:
;   This routine can be handy when the data for an event are not well
;   calibrated by standard techniques and data exist at another time
;   for which there is some reason to think that the source structure
;   is simple.  The result can be used only as an indication of change
;   in source position and/or structure.  If the fiducial time chosen
;   is not simple, the results will be garbage.
; SIDE EFFECTS: -
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 31-Jan-2004 by Dale E. Gary
;-

function relphz,out,calind

   ; Save a copy to avoid making changes to an input array
   out2 = out
   ; Determine number of antennas and use it to get number of baselines
   nant = sqrt(n_elements(out[*,0,0,0]))
   nbl = nant*(nant-1)/2.

   ; Determine cosine channel indexes (c) and sine channel indexes (s)
   c = nant+1+indgen(nbl)*2
   s = nant+indgen(nbl)*2

   ; extract the phases corresponding to input index CALIND
   calphz = atan(out[s,*,calind,*],out[c,*,calind,*])

   ; Determine the number of times in the data
   ntimes = n_elements(out[0,0,*,0])

   ; Step through the times, extracting amplitude (a) and phase (p),
   ; then apply the calibration phase given by CALPHZ, and finally
   ; insert the result back into the OUT array
   for i = 0, ntimes-1 do begin
      p = atan(out[s,*,i,*],out[c,*,i,*])
      a = sqrt(out[s,*,i,*]^2+out[c,*,i,*]^2)
      p = p - calphz
      out2[c,*,i,*] = a*cos(p)
      out2[s,*,i,*] = a*sin(p)
   endfor

return,out2
end