;+
; NAME:
;   Read_DriftData
; PURPOSE:
;
;
;
; CATEGORY:
;
; CALLING SEQUENCE:
;
; INPUTS:
;
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;
; ROUTINES CALLED:
;  openarc,newscan,getcycle,gaincor
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;
;-

pro read_driftdata,filename=filename,hrec=hrec,time=time,A1TP=A1TP,A2TP=A2TP,HA=HA

   time=0L

   ; Open the file
   lun = openarc(filename,a,nrec)

   ; Read header info, etc.
   rec = newscan(a,nrec,hrec,header,obseq,cfg,traj,refcal,gparm,geometry,pRecent,pOld,cyc_str) - 1
   bigdata = temporary(*cyc_str.pbigdata)
   pol = temporary(*cyc_str.ppol)

   nf = n_elements(*obseq.phord)
   A1TP = fltarr(nf,10000)
   A2TP = fltarr(nf,10000)

   ; Read Cycles
   i = 0

   REPEAT BEGIN
skiprec:
      cycle = get_cycle(a,data,rec,header,obseq,cfg,tcycle)

      if (n_elements(cycle) eq 1) then begin
         ; Check if this is a header record, meaning we have reached
         ; the end of the scan, otherwise, continue on
         if (cycle eq !SEGM.EOS) then goto,endtime
         if (cycle eq !SEGM.HEADER) then goto,endtime
         goto, skiprec
      endif

      ; Transfer needed part of cyc_str structure to more convenient variable names, then
      ; free the memory associated with those parts of cyc_str.
      bigdata[0]=cycle

      smldata = gaincor(bigdata,pol,header,cfg,obseq,tcycle,gparm,geometry)
      time=[time,tcycle]
      A1TP[*,i]=reform(smldata[0,*,2])
      A2TP[*,i]=reform(smldata[1,*,2])
      i = i + 1

   ENDREP UNTIL (n_elements(cycle) LT 50)

endtime:
   time=time[1:*]
   A1TP=A1TP[*,0:n_elements(time)-1]
   A2TP=A2TP[*,0:n_elements(time)-1]
   print,'header.tls',header.tls

   free_lun,lun

   ; Get hour angle (in msec) for the center of scan
   tnow = double(time[n_elements(time)/2])  ; Time at center of scan
   t = [1d,tnow,tnow^2]

   ; Get MJD corresponding to center time
   reads,header.tls.date,yy,mm,dd,format='(I4,1x,I2,1x,I2)'
   reads,msec2str(tnow),hh,mn,sc,format='(1x,I2,1x,I2,1x,I2)'
   mjd = julday(mm,dd,yy,hh,mn,sc)-2400000.5d

   ; Get RA and LST for this time, and calculate HA
   ranow = total(geometry.a_ra*t)           ; RA at this time
   lst = ovsa_lst(mjd)
   ha = lst-ranow

   ; Force HA to be between -12 h and + 12 h
   ha = ((ha + 43200000d + 86400000d) mod 86400000d) - 43200000d
   print,'Hour Angle: ',msec2str(ha)

   ; Free memory associated with structures
   freescan,obseq,traj,refcal,gparm,geometry,pRecent,pOld,cyc_str

end