;+
; NAME:
;     SRSP_PLOT_RCAL
; PURPOSE:
;     Plots the RCAL data from an SRSP RCVRCAL sequence
; CATEGORY:
;     SRSP APC DATA-ANALYSIS
; CALLING SEQUENCE:
;     srsp_plot_rcal,filename,hrec
; INPUTS:
;     filename  the name of a valid SRSP data (.ARC) file
;     hrec      the record number of the start of the FREQCAL sequence
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
;     A plot is shown on the current graphics device
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 06-Jun-2001 by Dale E. Gary
;-
pro srsp_plot_rcal,filename,hrec

   ; Open the file and create an associated array
   lun = srsp_openarc(filename,a,nrec)

   if (lun eq 0) then begin
      print,'SRSP_PLOT_FCAL: Could not open file '+filename
      return
   endif

   rec = hrec-1
   data = getdata(rec,a)
   ; Verify that HREC points to a valid FREQCAL header
   tls = srsp_tl_decode(data)
   if (tls.segmentcode ne 1) then begin
      print,'SRSP_PLOT_RCAL: Record '+string(hrec,format='(I5)')+' is not a header record.'
      free_lun,lun
      return
   endif
   if (tls.scancode ne 30) then begin
      print,'SRSP_PLOT_FCAL: Scan is not a RCVRCAL scan.'
      free_lun,lun
      return
   endif

   koff = 1
   rdoff = 16
   l = (r = intarr(124*28))     ; RCP and LCP channels w/ ND on
   lo = (ro = intarr(124*28))   ; RCP and LCP channels w/ ND off
   ir = indgen(124)*4 + rdoff
   il = ir + 1

   ; Get next record
   rec = rec + 1
   data = getdata(rec,a)
   if (n_elements(data) lt 512) then goto,done
   tls = srsp_tl_decode(data)
   j = 0
   ; Loop through records while still in the
   while (tls.scancode eq 30) do begin
      if (tls.segmentcode eq 1) then begin
         ; This is a header record, so time to stop
         goto,done
      endif
      if (tls.segmentcode eq 3) then begin
         r[j:j+123] = data[ir] and 'fff'x
         ro[j:j+123] = data[ir+2] and 'fff'x
         l[j:j+123] = data[il] and 'fff'x
         lo[j:j+123] = data[il+2] and 'fff'x
         j = j + 124
      endif
      rec = rec + 1
      data = getdata(rec,a)
      if (n_elements(data) lt 512) then goto,done
      tls = srsp_tl_decode(data)
   endwhile

done:
   free_lun,lun
   r = r[koff:*]
   l = l[koff:*]
   ro = ro[koff:*]
   lo = lo[koff:*]
   !p.multi=[0,2,3]
   plot,(r-ro)<4000,yran=[0,4000],xran=[0,4095],xsty=1
   plot,(l-lo)<4000,yran=[0,4000],xran=[0,4095],xsty=1
   plot,(r-ro)<4000,yran=[0,4000],xran=[4096,4096*2-1],xsty=1
   plot,(l-lo)<4000,yran=[0,4000],xran=[4096,4096*2-1],xsty=1
   plot,(r-ro)<4000,yran=[0,4000],xran=[4096*2,4096*3-1],xsty=1
   plot,(l-lo)<4000,yran=[0,4000],xran=[4096*2,4096*3-1],xsty=1
   !p.multi=0
return
end

