;+
; NAME:
;     APPLY_BEPHZ
; PURPOSE:
;     Correct for the non-zero phase induced by phase switching and
;     synchronous sampling in the Mk II backend.
; CATEGORY:
;     OVRO APC DATA ANALYSIS
; CALLING SEQUENCE:
;     apply_bephz,muxarr,s,c,upper,choff,data
; INPUTS:
;     muxarr   An NANT x NANT array giving the code determining whether
;                a given baseline is AB (=0), BC (=-1), or CA (=1).
;     s        An array of indexes into the NANT x NANT array giving
;                sine channels
;     c        An array of indexes into the NANT x NANT array giving
;                cosine channels
;     upper    An array of indexes into the NANT x NANT array giving
;                the channels in the same order as in DATA.
;     choff    An array of offsets into the DATA array corresponding
;                to the channels in S and C.
;     data     An array of size (NANT*NANT,NF) giving the data for one
;                cycle of the observing sequence (input and output)
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
; OUTPUTS:
;     data     On output, the corrected data, in the same format as on
;                input.
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 03-Jan-2003 by Dale E. Gary
;-
pro apply_bephz,muxarr,s,c,upper,choff,data

   i = 0
   nf = n_elements(data[0,*])
   xf = replicate(1,nf)
   nant = n_elements(muxarr[0,*])

   ; Make an NANT x NANT array of 135 degrees, expressed in radians
   chanphz = replicate(135*!dtor,nant,nant)
   ; Zero the diagonal (total power) elements
   chanphz[indgen(nant),indgen(nant)] = 0
   ; Change the sign of all non-AB baselines
   swap = where(muxarr ne 0,nswap)
   if (nswap ne 0) then chanphz[swap] = -chanphz[swap]

   ; Create an array of the appropriate size for the phases to be applied
   p = data[*,0]

   ; Phases to be applied are the inverse of the backend-induced phases
   p[choff] = -chanphz

   ; Apply the backend channel phase offsets by
   ; multiplying all channels by both sin(-chanphz) and cos(-chanphz)
   dsin = data*(sin(p)#xf)
   dcos = data*(cos(p)#xf)

   ; Set sine channels to appropriate combination of data
   data[s,*] = dcos[s,*] + dsin[c,*]

   ; Set cosine channels to appropriate combination of data
   data[c,*] = dcos[c,*] - dsin[s,*]

return
end

