;+
; NAME:
;     PLOT_GCPARM
; PURPOSE:
;     Plots the gain parameters (nonlinearity and atten factors) as
;     a function of time for the current and preceding month.  The
;     plot is saved into GCAL_DIAG_R.SAV or GCAL_DIAG_L.SAV (according
;     to value of POL keyword) in !DEFAULTS.DBDIR
; CATEGORY:
;     OVRO APC DIAGNOSTICS GCALCHEK
; CALLING SEQUENCE:
;     plot_gcparm,tls,nant,gcstat,pol=pol
; INPUTS:
;     tls      a standard time/label structure from the scan header
;                segment record of the GCAL scan.
;     nant     the number of antennas used in GCAL scan.
;     gcstat   the gain status string array, defined in GCALCHEK.  It
;                is a string array of size STRARR(NLINES,NTYPE,NANT)
;                where NLINES = 3 is the number of lines for each
;                button in the DIAGNOSE screen, NTYPE = 5 is the number
;                of buttons in the DIAGNOSE screen for each antenna,
;                and NANT is the number of antennas.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     pol	   single char string, 'r' or 'l', specifies whether the
;                data in GCSTAT are R or L data.  Resulting SAVE file
;                name has POL string appended to its name.
; ROUTINES CALLED:
; OUTPUTS:
; COMMENTS:
;     The results are written in the form of a plot to file GCAL_DIAG_R.SAV
;     or GCAL_DIAG_L.SAV in directory !DEFAULTS.DBDIR.  This plot is displayed
;     in pieces in DIAGNOSE.
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 18-Apr-1999 by Dale E. Gary
;     11-Jan-2000  DG
;       Eliminated hardwired directory locations.
;     12-Mar-2000  DG
;       Fixed to allow use with any number of antennas up to 8
;     11-Nov-2000  DG
;       Fixed a bug involving data arrays not being declaring in some
;       cases.
;     09-Jan-2004  DG
;       Added POL keyword to allow both R and L output
;-
pro plot_gcparm,tls,nant,gcstat,pol=pol

   common GC_prgmtr, id

   if (not keyword_set(pol)) then pol = 'R'  ; Default polarization

   ; Maximum number of antennas for which APC code must work.
   maxant = 8

   ; Strip out year and doy from yrday string, to use as arguments to
   ; CVDOY routine.  CVDOY returns a three element array with year, month,
   ; and day, all numeric.
   year = strmid(tls.yrday,0,4)
   doy = strmid(tls.yrday,5,3)
   out = cvdoy(year,doy)

   ; Read the time/label string time data into numerical variables
   reads,tls.yrday+tls.timstr,yr,day,hr,mn,format='(I4,1X,I3,1X,I2,1X,I2)'

   ; Convert to a double-precision number with the time encoded as
   ; decimal day, then divided by 1000 to add to year.day formatted
   ; number [e.g. 1998.023 + ((hr+mn/60)/24)/1000].  This will be
   ; compared to the values read from the current month file to find
   ; which entry is the current entry.
   yrday = double(yr)+double(day + (hr+mn/60.d0)/24.d0)/1.d3

   ; Create filename from elements
   filename2 = !defaults.dbdir + $
              string(out(0),out(1),format='(I4,I2.2)') + '.GNP'

   ; Get the filename of the next previous month
   if (out(1) eq 1) then begin

      ; It was January, so go to december of previous year
      out(0) = out(0)-1
      out(1) = 12
   endif else begin

      ; Otherwise just go to previous month
      out(1) = out(1)-1
   endelse

   ; Create filename from elements
   filename1 = !defaults.dbdir + $
              string(out(0),out(1),format='(I4,I2.2)') + '.GNP'

   ; See if the filenames already exists and act accordingly
   f = findfile(filename1,count=n)

   yrsec = dblarr(100)
   data = fltarr(6*maxant)
   gcparm = fltarr(6*maxant,100)
   i = -1

   if (n ne 0) then begin

      ; File exists.  Open it for reading.
      openr,lun,/get_lun,filename1
      line = ' '
      ; Read and throw away header lines of file
      readf,lun,line
      readf,lun,line
      readf,lun,line

      ; Go through the entries in the file one at a time until EOF is
      ; reached.
      while (NOT eof(lun)) do begin

         i = i + 1
         ; Read a line and convert its time label to seconds of the year
         readf,lun,line
         reads,line,lyr,lday,lhr,lmn,format='(I4,1X,I3,1X,I2,1X,I2)'
         yrsec(i) = double(lday*86400. + (lhr*3600.+lmn*60.d0))

         ; Read data from line
         reads,line,data,format='(17X,8(1X,6f6.3))'
         gcparm(*,i) = data

      endwhile
      free_lun,lun
   endif else begin
      lyr = fix(year)
   endelse

   thisyear = lyr
   f = findfile(filename2,count=n)

   if (n ne 0) then begin
      ; File exists.  Open it for reading.
      openr,lun,/get_lun,filename2
      line = ' '
      ; Read and throw away header lines of file
      readf,lun,line
      readf,lun,line
      readf,lun,line

      ; Go through the entries in the file one at a time until EOF is
      ; reached.
      while (NOT eof(lun)) do begin

         i = i + 1
         ; Read a line and convert its time label to year.day as above
         readf,lun,line
         reads,line,lyr,lday,lhr,lmn,format='(I4,1X,I3,1X,I2,1X,I2)'
         lyrday = double(lyr)+double(lday + (lhr+lmn/60.d0)/24.d0)/1.d3

         ; Compare this entry with the new entry to be inserted
         if (lyrday eq yrday) then icur = i

         yrsec(i) = double(((lyr-thisyear)*365. + lday)*86400. + (lhr*3600.+lmn*60.d0))

         ; Read data from line
         reads,line,data,format='(17X,8(1X,6f6.3))'
         gcparm(*,i) = data

      endwhile
      free_lun,lun
   endif

   res = progmeter(id,0.85)

   typstr = ['NonLin','5DB Attn','10DB Attn','20DB Attn','20*DB Attn','Residual']
   if (i gt 0) then begin
      olddev = !d.name
      set_plot,'z'
      device,set_res=[350*nant,300*2]*0.8
      !p.charsize=1.5
      !p.symsize=0.75
      !p.multi=[0,nant,2,0,0]
      yrsec = yrsec(0:i)
      gcparm = gcparm(*,0:i)
      for j = 0, nant-1 do begin
        utplot,yrsec,gcparm(1+6*j,*),psym=1,string(thisyear,format='(I4,"/01/00,00:00")'),$
          yran=[0.9,1.5],yticks=12,ysty=1, title='Attenuator Factors', $
          xtit='Start Date in '+string(fix(thisyear),format = '(I4)'), $
          ytit = '5 DB        10 DB        20 DB',$
          ytickname=['0.90','0.95','1.00','1.05','0.9/1.1','0.95','1.00',$
                          '1.05','0.9/1.1','0.95','1.00','1.05','1.10']
        if (n_elements(icur) ne 0) then plots,yrsec[icur],gcparm[1+6*j,icur],psym=6
        outplot,[0,365.D*86400.D*2.],[1.,1.],linesty=2

        outplot,yrsec,gcparm(2+6*j,*)+0.2,psym=4
        if (n_elements(icur) ne 0) then plots,yrsec[icur],gcparm[2+6*j,icur]+0.2,psym=6
        outplot,[0,365.D*86400.D*2.],[1.,1.]+0.2,linesty=2

        outplot,yrsec,gcparm(3+6*j,*)+0.4,psym=5
        if (n_elements(icur) ne 0) then plots,yrsec[icur],gcparm[3+6*j,icur]+0.4,psym=6
        outplot,[0,365.D*86400.D*2.],[1.,1.]+0.4,linesty=2

        ; Write out status line values
        if (n_elements(icur) ne 0) then begin
           ; Second line is just the values of GCPARM
           gcstat(1,3,j) = string(gcparm([0,1,2,3]+6*j,icur),format='(5(f5.2,":"))')
           ; For the 5 different types of data in GCPARM (NL, 5DB, 10DB, 20DB, Resid)
           ; compare current value with average over last two months
           for ind = 0, 4 do begin
              k = ([0,1,2,3,5])(ind)
              ; Get average and standard deviation using MOMENT() function
              mom = moment(gcparm(k+6*j,*))
              if (abs(mom(0) - gcparm(k+6*j,icur)) gt 2*sqrt(mom(1))) then begin
                 ; Greater than 2 sigma, so flag as warning
                 gcstat(2,3,j) = 'WARN: '+typstr[k]+' deviation'
              endif
           endfor
        endif
      endfor

      set_plot,olddev
      res = progmeter(id,0.9)
      set_plot,'z'

      for j = 0, nant-1 do begin
        utplot,yrsec,gcparm(5+6*j,*),psym=1,string(thisyear,format='(I4,"/01/00,00:00")'),$
          yran=[0.0,2.0],yticks=8,ysty=1, title='Nonlinearity/Residuals', $
          xtit='Start Date in '+string(fix(thisyear),format = '(I4)'), $
          ytit = 'Residual      Nonlinearity',$
          ytickname=['0.00','0.25','0.50','0.75','-.5/1','-0.25','0.00',$
                          '0.25','0.50']
        plots,yrsec[i],gcparm[5+6*j,i],psym=6

        outplot,yrsec,gcparm(0+6*j,*)+1.5,psym=4
        if (n_elements(icur) ne 0) then plots,yrsec[icur],gcparm[0+6*j,icur]+1.5,psym=6
        outplot,[0,365.D*86400.D*2.],[0.,0.]+1.5,linesty=2
      endfor
      img2 = tvrd()

      !p.multi=0
      !p.charsize=1
      !p.symsize=0
      set_plot,olddev

      res = progmeter(id,0.95)

      restore,file=!defaults.dbdir+'gcal_diag_'+pol+'.sav'

      save,file=!defaults.dbdir+'gcal_diag_'+pol+'.sav',grcvr,gnd,resf,img,img2

   endif


end