;+
; NAME:
;     MAKE_TPOVIEW
; PURPOSE:
;     Creates an overview plot of the standard SAV files for each
;     baseline contained in the file.
; CATEGORY:
;     OVRO APC WEB
; CALLING SEQUENCE:
;     make_bloview,filename[,type=type]
; INPUTS:
;     filename   the name of the .SAV file containing data to be plotted.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     type       a string specifying what type of output is desired.  Can
;                  be one of 'screen' (or 'scr'), 'jpeg' (or 'jpg'), or 'gif'.
;                  If omitted, the default is 'screen'.  If 'jpeg' or 'gif'
;                  is specified, the output filename is the same as the
;                  input filename, except the extension is changed to '.jpg'
;                  or 'gif' as appropriate.
; ROUTINES CALLED:
;     read_ovsa_fits, write_gif, write_jpeg, break_file, utplot_io
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 16-Jun-2000 by Dale E. Gary

pro make_bloview,filename,type=type

   ; Default type of display is the screen (actually the current device)
   if (n_elements(type) eq 0) then type = 'SCREEN'
   uctype = strupcase(type)

   ; Verify that the TYPE keyword is okay
   case uctype of
      'GIF':
      'JPG':
      'JPEG': uctype = 'JPG'
      'SCREEN':
      'SCR': uctype = 'SCREEN'
      else: begin
         print,'Make_BLOview: Invalid device type specified.  Must be GIF, JPG, or SCREEN'
         return
        end
   endcase

   ; Read the FTS file
   restore,filename

   ntimes = n_elements(tavg)
   nf = n_elements(f)
   nant = sqrt(n_elements(avg[*,0,0]))
   nbl = nant*(nant-1)/2

   bl_str = ''
   ants = [1,2,4,5,6,7]
   for iant = 0, nant-2 do begin
      for jant = iant+1, nant-1 do begin
        bl_str = [bl_str,string(ants[iant],ants[jant],format='(I1,"-",I1)')]
      endfor
   endfor
   bl_str = bl_str[1:*]

   ; Determine size of window for the NBL feeds
   xsiz = ntimes<700>250    ; X size of plot area for 1 baseline
   xtot = xsiz + 50.    ; X size of window
   ysiz = 72.           ; Y size of plot area for 1 baseline
   ytot = ysiz*nbl      ; Y size of window
   xoff = 40.           ; X offset to image LLC
   yoff = 26.           ; Y offset to image LLC

   ; Save current device name
   dsav = !d.name
   if (uctype eq 'SCREEN') then begin
      ; Create a window of the correct size...
      window,xsiz=xtot,ysiz=ytot
   endif else begin
      ; ...or create a Z-buffer of the correct size
      set_plot,'z'
      device,set_res=[xtot,ytot]
   endelse
   tvlct,/get,rold,gold,bold
   loadct,3
   tvlct,/get,r,g,b
   erase,255

   ; Loop over baselines
   for i = 0, nbl-1 do begin

      ; Extract the dynamic spectrum for this baseline
      data = reform(sqrt(avg[nant+i*2,*,*]^2 + avg[nant+i*2+1,*,*]^2))
      data = data/(reform((*refcal.pfactors)[2,i+nant,*])#replicate(1,ntimes))
      ; Loop through the frequencies, subtracting the most common
      ; value as determined from a histogram at each frequency
;      for j = 0, nf-1 do begin
;         hist = histogram(data(j,*)>0,bin=0.5,min=0)  ; Binsize 0.5 SFU
;         hist[0] = 0  ; Force the result NOT to be zero (in case of lots of NaN)
;         junk = max(hist,imax)   ; Peak of the histogram occurs at IMAX
;         data[j,*] = (data[j,*] - imax*0.5)>0.1
;      endfor

      xo = xoff
      yo = ytot-(i+1)*ysiz + yoff
      xs = xsiz-xoff
      ys = (ysiz-yoff)*0.9

      tv,bytscl(congrid(rotate(alog10(data>1),-5),xs,ys)),xo+1,yo+1
      if (f[0] le 1.4) then begin
         yran = [f[nf-1],1.0]
      endif else begin
         yran = [f[nf-1],f[0]]
      endelse
      xran = tavg[[0,ntimes-1]]/1000.
      ; Draw the plot box around the image
      utplot_io,/noerase,/nodata,tavg/1000.,f,xran=xran,$
          yran=yran,xsty=1,ysty=1,charsize=0.8,$
          pos=[xo/xtot,yo/ytot,(xs+xo)/xtot,(ys+yo)/ytot],$
          color=0,tls.date,$
          xtit='Amplitude on baseline '+bl_str[i]+' on ****',ytit='!4m!3 [GHz]'

      smax = strtrim(string(max(data),format='(F8.1)'),1)
      smin = strtrim(string(min(data>1),format='(F8.1)'),1)
      bar = replicate(1.0,10)#indgen(ys)
      tvscl,bar,xtot-40,yo+1
      plots,[0,0,10,10,0]+xtot-40,[0,ys,ys,0,0]+yo,/dev,color=0
      xyouts,xtot-28,yo-5,smin,/dev,charsize=0.8,color=0
      xyouts,xtot-28,yo+ys-5,smax,/dev,charsize=0.8,color=0
      xyouts,xtot-28,yo+ys/2.-5,' sfu',/dev,charsize=0.8,color=0

      ; Factor of 10 tick marks
      ndecades = fix(alog10(smax))
      for k = 0, ndecades do begin
         plots,[-5,0]+xtot-40,(ys/(alog10(smax)+1))*(k+1)+[yo,yo],/dev,color=0
      endfor

   endfor

   if (uctype eq 'JPG' or uctype eq 'GIF') then begin
      ; Read the z-buffer, then go back to original device
      img = tvrd()

      break_file,filename,disk,dir,file,ext
      outname = disk+dir+file

      ; Convert 24-bit image to 8-bit image
;      img = color_quan(bkgnd,1,r,g,b,colors=256)

      ; Write GIF or JPG file according to TYPE keyword
      if (uctype eq 'GIF') then begin
         outname = outname+'.gif'
         ; Write it to disk
         write_gif,outname,img,r,g,b
      endif else if (uctype eq 'JPG') then begin
         ; The z-buffer is a byte device, so create a true-color image
         ; from the one read from the z-buffer, using the image byte
         ; values as indexes into the color tables
         tcolor = bytarr(3,xtot,ytot)
         tcolor(0,*,*) = r[img]
         tcolor(1,*,*) = g[img]
         tcolor(2,*,*) = b[img]

         outname = outname+'.jpg'
         write_jpeg,outname,tcolor,true=1
      endif
   endif

   ; Set plot settings back to original
   set_plot,dsav
   tvlct,rold,gold,bold

return
end