;+
; NAME:
;     DAILY_PLOT
; PURPOSE:
;     Plot the results of the DAILY calibration on a single page.
; CATEGORY:
;     OVSA APC CALIBRATION ANALYSIS SUPPORT
; CALLING SEQUENCE:
;     daily_plot, scan,iref,o_datfile,lines[,/printer]
; INPUTS:
;     scan       An array of SCAN structures of size NSCAN, created in
;                  DAILY.PRO, containing the information to appear in
;                  the plot.
;     refscan    A SCAN structure (may or may not be one of the elements
;                  of SCAN) containing the reference scan.
;     o_datfile  A string containing the filename of the original
;                  file from which the DAILY calibration data were taken.
;     lines      A string array containing the phase slopes in the form
;                  of a table, which is printed at the bottom of the
;                  output plot.  On output, an additional line is added
;                  to the end of this array, giving the phase information
;                  relative to the reference calibration.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     printer    A switch to indicate that the output should go to the printer
; ROUTINES CALLED:
; OUTPUTS:
;     lines      The input string array, plus an additional line at the
;                  end of the array giving the phase information relative
;                  to the reference calibration.
; COMMENTS:
; SIDE EFFECTS:
;     Creates a plot
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 28-May-2000 by Dale E. Gary
;     01-Jun-2000  DG
;       Slight change to use REFSCAN, which may not be an element of
;       the SCAN array.
;     05-Jun-2000  DG
;       Add plot and table for Reference Calibration comparison
;     16-Jul-2000  DG
;       Change plotting and output of reference comparison to include
;       phase offset.
;     17-Jul-2000  DG
;       Change plotting and output of all scans to include phase offset.
;     27-Jul-2000  DG
;       Explicitly set the window size for no printer, to 1/2 the
;       screen size.
;     07-Nov-2005  DG
;       Added another triad, for 7-element data
;     15-May-2014  DG
;       Adjust reading of 'save.txt' to reflect new line added
;-
pro daily_plot,scan,refscan,o_datfile,lines,amf,printer=printer

   oldp = !p
   olddev = !d.name

   ; If the output is to go to the printer, set the output device and save the
   ; current DEVICE and PLOT system variables
   if (keyword_set(printer)) then begin
      set_plot,'printer'
      device,get_current_font=oldfont
      oldprp = !p
   endif else begin
      xy = get_screen_size()
      window,0,xs=xy[0]/2,ys=xy[1]
      !p.multi=0
   endelse

   ; Determine dimensions of array
   f = reform(refscan.amf[0,*,0])
   nscans = n_elements(scan)
   ibl = where(scan[0].amf[0,0,*] ne 0,nbl)

   ; Determine how many triads (combinations of three antennas)
   ; there are.  Basically there are either 3 or 4
   case nbl of
      9: ntriad = 4
     11: ntriad = 5
     else: ntriad = 3
   endcase
   bl_str=['1-2-4','1-2-5','1-2-6','1-2-7','1-2-8']

   ; Set boundaries of plot area, in normalized device coordinates
   x0 = 0.33
   x1 = 0.95
   y0 = 0.4
   y1 = 0.95

   ; Determine width of entire plot area
   xwid = (x1-x0)
   ywid = (y1-y0)

   ; Determine width of subplots
   xwidi = xwid/ntriad
   ywidi = ywid/(nscans>5)

   ; Set LLC of each subplot
   x = (indgen(nscans*ntriad) mod ntriad)*xwidi+x0
   y = (reverse(indgen((nscans>5)*ntriad)/ntriad))*ywidi+y0

   ; Set plot parameters appropriate to PRINTER device
   if (keyword_set(printer)) then begin
      device,/port,/inch,xsiz=8.0,ysiz=10.0,xoff=0,yoff=0,set_font='Courier New'
      !p.thick=2
      !p.charthick=2
      !x.thick=2
      !y.thick=2
   endif
   oldcsize = !p.charsize
   !p.charsize=0.5

   ; Write out title for the plot
   xyouts,/norm,0.5,y1+0.025,'Daily Calibration for file '+o_datfile,charsize=1.0,align=0.5
   xyouts,/norm,0.5,y1+0.010,scan[0].date,charsize=1.0,align=0.5

   ; Loop over scans
   for i = 0,nscans-1 do begin

      ; Loop over "triads"
      for j = 0, ntriad-1 do begin

         ; Calculate the position of the subplot to be plotted
         pos = [x[i*ntriad+j],y[i*ntriad+j],x[i*ntriad+j]+xwidi,y[i*ntriad+j]+ywidi]

         ; Set labels for those subplots that need them.
         if (j gt 0) then begin
            !y.tickname=replicate(' ',10)
            !y.title=''
         endif else begin
            !y.tickname=''
            !y.title = 'Relative Phase [deg]'
         endelse
         if (i lt nscans-1) then begin
            !x.tickname=replicate(' ',10)
            !x.title=''
         endif else begin
            !x.tickname=''
            !x.title = 'Frequency [GHz]'
         endelse

         ; Calculate the measured phase for baseline 1-2 (relative to reference phase)
         phz  =  scan[i].amf[3,*,  0] - refscan.amf[3,*,  0]
         ; Calculate the phases corresponding to the straight line fit
         ; (the line that goes through 0 and through the 5 GHz point).
         phz0 = scan[i].pslp[0  ]*f + scan[i].poff[0  ]
;         phz0 = (scan[i].pslp[0  ]*5 + scan[i].poff[0  ])*f/5

         ; Determine whether there are any lobe corrections.  They will be applied
         ; in the plot command.
         nlobe = nint((phz - phz0)/360.)

         ; Plot the points for the 1-2 baseline, and overplot the straight line fit
         plot,/noerase, f,phz-nlobe*360,psym=1,pos=pos,$
               yran=[-300,300],xran=[0,12],xsty=1,ysty=1,symsize=0.5
         oplot,[0,f],[scan[i].poff[0],phz0]
;         oplot,[0,f],[0,phz0]

         ; Repeat for baseline 1-j
         phz  =  scan[i].amf[3,*,j+1] - refscan.amf[3,*,j+1]
         phz0 = scan[i].pslp[j+1]*f + scan[i].poff[j+1]
;         phz0 = (scan[i].pslp[j+1]*5 + scan[i].poff[j+1])*f/5
         nlobe = nint((phz - phz0)/360.)
         oplot, f,phz-nlobe*360,psym=2,symsize=0.5
         oplot,[0,f],[scan[i].poff[j+1],phz0],linesty=1
;         oplot,[0,f],[0,phz0],linesty=1

         ; Repeat for baseline 2-j
         phz  =  scan[i].amf[3,*,j+1+ntriad] - refscan.amf[3,*,j+1+ntriad]
         phz0 = scan[i].pslp[j+1+ntriad]*f + scan[i].poff[j+1+ntriad]
;         phz0 = (scan[i].pslp[j+4]*5 + scan[i].poff[j+4])*f/5
         nlobe = nint((phz - phz0)/360.)
         oplot, f,phz-nlobe*360,psym=4,symsize=0.5
         oplot,[0,f],[scan[i].poff[j+1+ntriad],phz0],linesty=2
;         oplot,[0,f],[0,phz0],linesty=2

         ; Write out which triad we are working with
         xyouts,/norm,pos[0]+0.005,pos[1]+0.005,bl_str[j]
      endfor

      ; Write out labels for this scan
      xyouts,/norm,x0/2,pos[1]+0.06,'Source: '+strtrim(scan[i].srcname),align=0.5,charsize=0.8
      xyouts,/norm,x0/2,pos[1]+0.06-0.015,'Date: '+scan[i].date,align=0.5,charsize=0.8
      xyouts,/norm,x0/2,pos[1]+0.06-0.030,'Time: '+scan[i].time,align=0.5,charsize=0.8
   endfor

   ; Plot the reference phase comparison
   ;-----------------------------------------------------------------
   ; Read the SAVE.TXT file written by WPHZFIT
   openr,slun,/get_lun,!defaults.workdir+'save.txt'
   line = ''
   readf,slun,line  ; Read first line, which should always be 'USE'
   if line ne 'USE' then print,'User must have skipped reference comparison, which is not allowed.'
   ref_fit = fltarr(5,nbl)
   readf,slun,ref_fit
   free_lun,slun

   ; Set boundaries of plot area, in normalized device coordinates
   x0 = 0.33
   x1 = 0.95
   y0 = 0.11
   y1 = 0.21

   ; Determine width of entire plot area
   xwid = (x1-x0)
   ywid = (y1-y0)

   ; Determine width of subplots
   xwidi = xwid/ntriad
   ywidi = ywid

   ; Set LLC of each subplot
   x = (indgen(ntriad) mod ntriad)*xwidi+x0
   y = (reverse(indgen(ntriad)/ntriad))*ywidi+y0

   ; Loop over "triads"
   for j = 0, ntriad-1 do begin

      ; Calculate the position of the subplot to be plotted
      pos = [x[j],y[j],x[j]+xwidi,y[j]+ywidi]

      ; Set labels for those subplots that need them.
      if (j gt 0) then begin
         !y.tickname=replicate(' ',10)
         !y.title=''
      endif else begin
         !y.tickname=''
         !y.title = 'Relative Phase [deg]'
      endelse

      ; Calculate the measured phase for baseline 1-2 (relative to reference phase)
      phz  =  amf[3,*,  0]

      ; Calculate the phases corresponding to the straight line fit.
      ; Allow for phase offsets in this fit.
      phz0 = ref_fit[1,0] + ref_fit[2,0]*f

      ; Determine whether there are any lobe corrections.  They will be applied
      ; in the plot command.
      nlobe = nint((phz - phz0)/360.)

      ; Plot the points for the 1-2 baseline, and overplot the straight line fit
      plot,/noerase, f,phz-nlobe*360,psym=1,pos=pos,$
            yran=[-300,300],xran=[0,12],xsty=1,ysty=1,symsize=0.5
      oplot,[0,f],[ref_fit[1,0],phz0]

      ; Repeat for baseline 1-j
      phz  =  amf[3,*,j+1]
      phz0 = ref_fit[1,j+1] + ref_fit[2,j+1]*f
      nlobe = nint((phz - phz0)/360.)
      oplot, f,phz-nlobe*360,psym=2,symsize=0.5
      oplot,[0,f],[ref_fit[1,j+1],phz0],linesty=1

      ; Repeat for baseline 2-j
      phz  =  amf[3,*,j+1+ntriad]
      phz0 = ref_fit[1,j+1+ntriad] + ref_fit[2,j+1+ntriad]*f
      nlobe = nint((phz - phz0)/360.)
      oplot, f,phz-nlobe*360,psym=4,symsize=0.5
      oplot,[0,f],[ref_fit[1,j+1+ntriad],phz0],linesty=2

      ; Write out which triad we are working with
      xyouts,/norm,pos[0]+0.005,pos[1]+0.005,bl_str[j]
   endfor
   ; Write out labels for this scan
   xyouts,/norm,x0/2,pos[1]+0.06,'Comparison of Daily',align=0.5,charsize=0.8
   xyouts,/norm,x0/2,pos[1]+0.06-0.015,'with Reference Cal',align=0.5,charsize=0.8
   xyouts,/norm,x0/2,pos[1]+0.06-0.030,'Add to table above',align=0.5,charsize=0.8

   ; Set up for hardware font if device is PRINTER
   if (keyword_set(printer)) then !p.font=0

   pstr = ''
;   phz0 = reform((ref_fit[1,*]/5 + ref_fit[2,*]))
   for i = 0, nbl-1 do pstr = pstr+string(ref_fit[2,i],nint(ref_fit[1,i]),format='(F7.1,I5)')
   print,pstr
   ; Add PSTR to the end of the LINES string array
   lines = [lines,pstr]

   ; Write the table at the bottom of the page
   nlines = n_elements(lines)
   if (nlines ne 0) then begin
      if (keyword_set(printer)) then device,set_font='Lucida Console*40'
      xyouts,/norm,0.5,0.34,'Table of Phase Slopes [degrees/GHz] for '+scan[0].date,align=0.5
      if (keyword_set(printer)) then device,set_font='Lucida Console*30'
      for i = 0, nlines-2 do begin
         xyouts,/norm,0,0.325-0.015*i,lines[i]
      endfor
      if (keyword_set(printer)) then device,set_font='Lucida Console*40'
      xyouts,/norm,0.5,0.05,'Table of Phase Slopes [degrees/GHz] Relative to Reference Scan',align=0.5
      if (keyword_set(printer)) then device,set_font='Lucida Console*30'
      hed0 = strmid(lines[0],14)
      hed1 = strmid(lines[1],14)
      i = strpos(hed0,'sig')
      while (i ne -1) do begin
         hed0 = strmid(hed0,0,i)+'poff'+strmid(hed0,i+3)
         hed1 = strmid(hed1,0,i)+'----'+strmid(hed1,i+3)
         i = strpos(hed0,'sig')
      endwhile

      xyouts,/norm,0,0.035,hed0
      xyouts,/norm,0,0.020,hed1
      xyouts,/norm,0,0.005,lines[nlines-1]
   endif

   ; Revert back to standard printer parameters, and set device to what it was
   ; upon entering the routine
   if (keyword_set(printer)) then begin
      device,/close
      !p = oldprp
      device,set_font=oldfont
      !x.thick=1
      !y.thick=1
      set_plot,olddev
   endif
   !y.tickname=''

   ; Revert back to plot parameters as they were upon entering the routine
   !p = oldp

return
end