;+
; NAME:
;     PLOT_MED
; PURPOSE:
;     Plot dynamic spectrum contained in a "MED" file output by
;     OVSA_EXPLORER
; CATEGORY:
;     OVRO APC DATA ANALYSIS
; CALLING SEQUENCE:
;     plot_med,filename[,maxdat=maxdat][,mindat=mindat][,fluxlim=fluxlim][,/rcp][,/lcp][,/p][,/log]
; INPUTS:
;     filename   the name of the MED file containing the data.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     LOG        a keyword to specify that the flux density should be log-scaled
;     maxdat     the maximum value to use to scale the plot
;     mindat     the minimum value to use to scale the plot
;     RCP          plot only the RCP flux density
;     LCP          plot only the LCP flux density
;     P          plot percent polarization (if set, maxdat and mindat are taken
;                  to be range of polarization, or range -100 to 100 is assumed)
;     FLUXLIM    flux limit above which to determine percent polarization.
; ROUTINES CALLED:
;     utplot, get_ovsa_image
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 29-Dec-2003 by Dale Gary
;     31-Dec-2003  DG
;       Added a labeled color bar to show the flux density in sfu.
;     06-Jan-2004  GN
;       Made use of get_ovsa_image to emulate the freq-log scale.
;     27-Aug-2005  GN
;       Added R,L, and P keywords to allow plotting RCP , LCP and polarization
;       data if ldata and rdata are present in the med files as saved by the
;       updated version of ovsa_explorer using "Save median data" menu item,
;       which replaced the old "Save TP and Movie" item.
;     28-Aug-2005  DG
;       Added FLUXLIM keyword, and set default flux limit of 20 sfu for
;       calculation of polarization.  Added gray color at center of color
;       scale for polarization plot.  Changed FIX to LONG for color bar
;       labeling, since large fluxes were overflowing 2-byte signed integer.
;     15-Apr-2006  DG
;       Added LOG keyword to allow plotting of log flux density (ignored for poln)
;     09-Dec-2006  DG
;       Had to change R and L keywords to RCP and LCP in order to distinguish
;       old keyword L from LOG.
;
;-
pro plot_med,filename,maxdat=maxdat,mindat=mindat,lcp=lcp,rcp=rcp,p=p,fluxlim=fluxlim,log=log

   ; If the filename was not given, prompt the user for one
   if (n_elements(filename) eq 0) then begin
      filename = dialog_pickfile(path=!defaults.workdir,filter='*.med',title='Enter MED file to read:')
      if (filename eq '') then return
   endif

   ; Open the file
   restore,filename

   if (n_elements(tavg) eq 0) then return ; Error return in case RESTORE did not work, or
                                          ; data are not correct

   ;Replace the default data with the one indicated by R,L,or P keywords
   what='Total Power'
   scale='Flux Density Scale (Linear)'
   units='sfu'
   if keyword_set(rcp) then begin
    if (n_elements(rdata) eq 0) then return;Error return in case that RCP data is not present
    data=rdata
    what='RCP'
   end
   if keyword_set(lcp) then begin
    if (n_elements(ldata) eq 0) then return;Error return in case that LCP data is not present
    data=ldata
    what='LCP'
   end
   if keyword_set(p) then begin
    if (n_elements(ldata) eq 0) then return;Error return in case that LCP data is not present
    if (n_elements(rdata) eq 0) then return;Error return in case that RCP data is not present
    if (not keyword_set(fluxlim)) then fluxlim = 20
    data=100*(rdata-ldata)/(rdata+ldata)
    badpol=where(data lt -100 or data gt 100,nbad)
    if (nbad ne 0) then data[badpol]=!values.f_nan
    nopol = where((rdata+ldata) lt fluxlim,nbad)
    if (nbad ne 0) then data[nopol] = 0.0
    what='Polarization'
    scale='Polarization Scale'
    units='%'
   end


   dsav = !d.name
        if (!version.os_family eq 'Windows') then set_plot,'win' $
   else if (!version.os_family eq 'UNIX')    then set_plot,'x'
   ; Save the color scheme, since we are going to change it.
   tvlct,/get,ro,go,bo
   ; Change to rainbow+white color table
   loadct,39
   if (keyword_set(p)) then begin
      ; For polarization color scheme, make central color gray
      tvlct,/get,r,g,b
      r[126:128] = (g[126:128] = (b[126:128] = 128))
      tvlct,r,g,b
   endif
   ; Open the window
   window,/free,xsiz=600,ysiz=300
   x1 = 70
   y1 = 100
   x2 = x1+500
   y2 = y1+150
   ; If the DATMAX keyword was not set, use the max in the data
   if (not keyword_set(maxdat)) then maxdat = max(data,/nan) else maxdat = float(maxdat)
   if (not keyword_set(mindat)) then mindat = min(data,/nan) else mindat = float(mindat)
   ; Make the axis border and tickmarks
   utplot,tavg/1000.,f,/ylog,yran=[18,1],/ysty,datstr,/xsty,position=[x1-1,y1-1,x2,y2],/dev,xticklen=-0.05,yticklen=-0.02,$
          color=0,background=255,title='OVSA '+what+' Data for '+datstr,ytit='Frequency [GHz]'
   ; Overplot the data
   ;tvscl,bytscl(congrid(rotate(data,-5),x2-x1,y2-y1),max=maxdat,min=mindat),x1,y1
   if (keyword_set(log) and not keyword_set(p)) then begin
      tvscl,bytscl(alog10(congrid(get_ovsa_image(data,f,tavg),x2-x1,y2-y1)>1),max=alog10(maxdat),min=alog10(mindat>1)),x1,y1
      scale='Flux Density Scale (Logarithmic)'
   endif else begin
      if (keyword_set(log)) then begin
         print,'Cannot apply log scaling to percent polarization'
         log = 0
      endif
      if (keyword_set(p)) then data[0:1,0]=[mindat,maxdat]   ; Force data to have max and min values
      tvscl,bytscl(congrid(get_ovsa_image(data,f,tavg),x2-x1,y2-y1),max=maxdat,min=mindat),x1,y1
   endelse
   ; Create color bar
   xyouts,x1+260,y1-65,scale,color=0,/dev
   bar = indgen(256)#replicate(1,20)
   tv,bar,x1,y1-70
   plots,[x1,x1+256,x1+256,x1,x1]-1,[y1,y1,y1+21,y1+21,y1]-71,color=0,/dev
   plots,[x1,x1]-1,    [-6,0]+y1-71,color=0,/dev
   plots,[x1,x1]-1+ 64,[-6,0]+y1-71,color=0,/dev
   plots,[x1,x1]-1+128,[-6,0]+y1-71,color=0,/dev
   plots,[x1,x1]-1+192,[-6,0]+y1-71,color=0,/dev
   plots,[x1,x1]-1+256,[-6,0]+y1-71,color=0,/dev
   if (keyword_set(log)) then begin
      xyouts,x1-1,    y1-90,strtrim(string(long(mindat+10^(  0*alog10(maxdat-mindat)/256.)+0.5)>1,format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+ 64,y1-90,strtrim(string(long(mindat+10^( 64*alog10(maxdat-mindat)/256.)+0.5)>1,format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+128,y1-90,strtrim(string(long(mindat+10^(128*alog10(maxdat-mindat)/256.)+0.5)>1,format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+192,y1-90,strtrim(string(long(mindat+10^(192*alog10(maxdat-mindat)/256.)+0.5)>1,format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+256,y1-90,strtrim(string(long(mindat+10^(256*alog10(maxdat-mindat)/256.)+0.5)>1,format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+280,y1-90,units,color=0,/dev
   endif else begin
      xyouts,x1-1,    y1-90,strtrim(string(long(mindat+  0*(maxdat-mindat)/256.+0.5),format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+ 64,y1-90,strtrim(string(long(mindat+ 64*(maxdat-mindat)/256.+0.5),format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+128,y1-90,strtrim(string(long(mindat+128*(maxdat-mindat)/256.+0.5),format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+192,y1-90,strtrim(string(long(mindat+192*(maxdat-mindat)/256.+0.5),format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+256,y1-90,strtrim(string(long(mindat+256*(maxdat-mindat)/256.+0.5),format='(I6)'),2),align=0.5,color=0,/dev
      xyouts,x1-1+280,y1-90,units,color=0,/dev
   endelse
   ; Reset the color table and plot device
   tvlct,ro,go,bo
   set_plot,dsav

return
end