;+
; PROJECT:
;	SDAC
;
; NAME:
;	GOESPLOT
;
; PURPOSE:
;       Display the time profile of any interval of GOES data.
;
; CATEGORY:
;       GOES
;
; CALLING SEQUENCE:
;	GOESPLOT, [FLARE=FLARE, STIME=STIME, ETIME=ETIME, $
;               TARRAY=TARRAY, YARRAY=YARRAY, YCLEAN=YCLEAN, CLEANED=CLEANED,$
;               YDERIV=YDERIV,CH_SELECT, PLOTFILE=PLOTFILE, LOGPLOT=LOGPLOT,$
;               POINTPLOT=POINTPLOT, ERROR=ERROR, XRANGE=XRANGE, YRANGE=YRANGE,$
;               MARKBAD=MARKBAD, BACK=BACK, CH0_BAD=CH0_BAD, CH1_BAD=CH1_BAD,$
;               NOERASE=NOERASE, DERIV=DERIV, E_BARS=E_BARS, ERR_MSG=ERR_MSG, $
;		NODATA=NODATA, AVE_TARRAY=AVE_TARRAY, AVE_YCLEAN=AVE_YCLEAN, $
;		SAT=SAT, N_PTS=N_PTS, PROC=PROC]
;
; CALLS:
;       HXRBS_FORMAT, CHECKVAR, READ_MINICAT, ATIME, ANYTIM, GFITS_R,
;	CLEAN_GOES, SET_UTLABEL, ERROR_BARS, GETUTBASE, SYS2UT, SET_GRAPHICS,
;	CHKLOG, LINECOLORS, UTPLOT, EPLOT
;
; INPUTS:
;       Through keywords
;
; OUTPUTS:
;       Through keywords
;
; KEYWORDS:
; 	FLARE:		HXRBS Flare number
; 	STIME:		Start time of data to plot in any of allowed formats:
;               	'YY/MM/DD,HHMM:SS.XXX', 'DD-MMM-YY HH:MM:SS.XXX',
;               	seconds since 79/1/1, structure, or 7xn array
; 	ETIME:		End time of data to plot in any of allowed formats
; 	TARRAY:		Variable in which to return the time array.
;			Times are in seconds relative to the start of the day.
;			x=getutbase() contains the number of seconds to the
;			start of the day from 79/1/1,0000.
;             		i.e.  print,atime(tarray(0)+getutbase(0)) will print
;			the ascii time for the first point.
; 	YARRAY:		Variable in which to return the two channels of GOES
;			data for each time in TARRAY.
; 	YCLEAN:		Variable in which to return the two channels of cleaned
;             		(spikes are eliminated) GOES data for each time in
;			TARRAY
; 	CLEANED:	If set, cleaned data is used for plot.
; 	YDERIV:		Variable in which to return time derivative of two
;			channels.
; 	CH_SELECT:	Channels to plot. [1,0] means Chan 1 only, [0,1] means
;			Chan 2 only, [1,1] means Chan 1 overlaid on Chan 2.
;			Default is [1,1].
; 	PLOTFILE:	If nonzero, a plot file will be created when you plot
;			on screen. Can be set either to a nonzero number in
;			which case the file name will be goesplot.xx or can be
;		 	set to the desired file name. Format of plotfile can
;			be selected by entering the SELECT_DEV procedure.
; 	LOGPLOT:	If non-zero, y axis is logarithmic.
; 	POINTPLOT:	If non-zero, a point plot is drawn. Otherwise,histogram.
; 	ERROR:		0/1 No errors found / Errors found.  Error msg text
;			in ERR_MSG.
; 	XRANGE:		2-element vector specifying limits for x axis
; 	YRANGE:		2-element vector specifying limits for y axis
; 	MARKBAD:	Plot 'X's at the times where there were spikes and
;			the data was interpolated from surrounding points
; 	BACK:		Values of background to subtract for two channels
; 	CH0_BAD:	Element numbers of data arrays where Channel 1 data
;			had spike which was eliminated and interpolated over.
; 	CH1_BAD:	Same as CH0_BAD for Channel 2.
; 	NOERASE:	If set, don't clear screen before plotting.
; 	DERIV:		If set, plot derivative of GOES channel requested in
;			COMB and OVERLAY keywords.
; 	E_BARS: 	If set, draws error bars.
; 	ERR_MSG:	ASCII string containing error message if ERROR = 1
; 	NODATA:		If set, only plot box is drawn, useful for further
;			overplotting
; 	AVE_TARRAY:	Averaged tarray. See n_pts.
; 	AVE_YCLEAN:	Averaged yclean. See n_pts.
; 	SAT:		6, 7, 8, 9  for GOES 6, GOES 7 or GOES 8  GOES 9  data
;			(default depends on time selected or defaults to last used).
; 	N_PTS:		Sample average to be used by the rebin function.
;			Default is 1.
; 	PROC:		A procedure to call with arguments encoded in a
;			structure.  Used for drawing lines on GOES plots
;
; COMMON BLOCKS:
;       goesplot, savegoes
;
; PROCEDURE:
;	GOESPLOT reads the file for requested flare and
;       plots the time profile with the following options:
;             plot any combination of the available channels
;             overlay any combination of the available channels
;             logarithmic or linear y axis
;             point or histogram plot
;             only plot data within x and/or y limits
;       If the device is capable of X windows graphics (logical name
;       DEVICE_TYPE equals X) then X windows is the default screen graphics
;       device.  Otherwise Tektronix is the default.  PostScript is the
;       default printer format.  The user can select the devices by typing
;       SELECT_DEV.
;       The time array and the raw and cleaned data are returned in
;       keyword arguments.
;	Sample calls:
; 		GOESPLOT,FLARE=5,TARRAY=T,YARRAY=Y,CH_SEL=[1,0]
; 		GOESPLOT,STIME='92/4/19,2300',ETIME='92/4/19,2350',/CLEAN,/MARK
;
; MODIFICATION HISTORY:
; 	Written by Kim Tolbert  10/92 (based on hxarchive.pro)
; 	Mod. by KT 7/16/93 to handle real time data (in FITS format, data later
;   		than 93/1/1).
; 	Mod. by KT 12/94 to accept a filename in PLOTFILE keyword, to accept
;   		any times in any format in STIME and ETIME keywords, and to set default
;   		ASCII time format to HXRBS, then restore it to whatever it was on exit.
; 	Mod. by Amy Skowronek 7/94 to only look for FITS files.  All DC files
;   		have been converted to FITS and placed in one directory.
; 	ras, 7-dec-94, did some error handling in clean_goes to check for degenerate
;		cases, too little good data in particular
; 	AES, 3/13/95, added yderiv, variable in which to return time derivative
; 	ras, 5-aug-95 added nodata to facilitate overplots of time-averaged data
; 	RCJ, 09/95 added SAT and N_PTS keywords, SAVESAT in common block, and
;      		REBIN function to be applied to tarray and yplotted
; 	aes, 3/96  added time/sat consistency checks for goes 8 & 9
; 	ras, 3-aug-96, changed satellite constraints to allow goes 7,8,and 9 when the
;		files exist
; 	RCJ, 09/12/96 Added ave_tarray and ave_yclean keywords.
;       RCJ, 09/13/96 Added documentation.
; 	ras, 16-oct-1996, include test to account for end of GOES7
;	RCJ, 11/01/96, rescale charsize if pmulti(2)=2 or >2 and sc_device='X',
;		Add sample avg. (if > 1 pt) subtitle to graph plot.
;		Changed distance input to pl_scale from .07 to .12
;	RCJ, 12/10/96, rescale charsize if pmulti(2)=2 or >2, sc_device='X',
;		*and* !d.y_size le 512. Rescaled charsize was too big
;		in fsplot, option  data,all4 , where window is resized to
;		!d.y_size=959. Also rescale y coordinate of xyouts under
;		same conditions.
;	RCJ, 01/07/96, modify command xyouts,...,codes to xyouts,...,codes(q)
;		so that extra codes won't show on short period ps plots.
;		Print msg when sample avg. > n_elements y-axis.
;	RAS, 01/28/1997, added readme to common savegoes
;	RAS, 02/04/1997, ensured stime and etime are scalars for tests
;	     default satellite is the last satellite used.
;	Version 18,
;	RAS, 02/07/1997, passed satellite number into cleaning algorithm.
;	Version 19,
;	richard.schwartz@gsfc.nasa.gov, fixed bug with yover
;	Version 20,
;	richard.schwartz@gsfc.nasa.gov, 18-may-1998, changed 'X' to xdevice('X')
;	richard.schwartz@gsfc.nasa.gov, 13-jul-1998, use axis to label right y axis.
;	amy@aloha.nascom.nasa.gov, 22-jul-1998, added a character to the plot
;   		label so it can display the numbers of satellites over 9.	
;	richard.schwartz@gsfc.nasa.gov, 19-aug-1998, fix GOES class labeling.
;	
;-
;
PRO GOESPLOT, FLARE=FLARE, STIME=SIN, ETIME=EIN, $
              TARRAY=TARRAY, YARRAY=YARRAY, YCLEAN=YCLEAN, CLEANED=CLEANED,$
              CH_SELECT=CH_SELECT, PLOTFILE=PLOTFILE, LOGPLOT=LOGPLOT,$
              POINTPLOT=POINTPLOT, ERROR=ERROR, XRANGE=XRANGE, YRANGE=YRANGE,$
              MARKBAD=MARKBAD, BACK=BACK, CH0_BAD=CH0_BAD, CH1_BAD=CH1_BAD,$
              NOERASE=NOERASE, DERIV=DERIV, E_BARS=E_BARS, ERR_MSG=ERR_MSG,$
	      YDERIV=YDERIV, NODATA=NODATA, SAT=SAT, N_PTS=N_PTS, PROC=PROC, $
	      AVE_TARRAY=AVE_TARRAY,AVE_YCLEAN=AVE_YCLEAN
;
common goesplot, save_bangp, save_bangx, save_bangy
;
common savegoes ,savesat, savestime, saveetime, savetarray, saveyarray, $
	saveyclean, savech0_bad, savech1_bad, loedges, hiedges, readme

hxrbs_format, old_format = old_time_format
error = 0

if not(keyword_set(sin) and keyword_set(ein)) then begin
   if not(keyword_set(flare)) then begin
      print,'Please specify a flare number or time interval via keywords ',$
            'FLARE or STIME and ETIME'
      print,'e.g. goesplot,FLARE=xxx or ',$
            'goesplot,stime=''91/1/1,1200'',etime=''91/1/1,1400'')'
      err_msg = 'Error. You didn''t select start/end time, flare # ' + $
                'or channels.'
      goto,error_exit
   endif
endif

checkvar, ch_select, [1,1]
checkvar, plotfile, 0
checkvar, logplot, 0
checkvar, pointplot, 0
checkvar, markbad, 0
checkvar, back, [0,0]
checkvar, deriv, 0
checkvar, noerase, 0
checkvar, xrange, [0.,0.]
checkvar, yrange, [0.,0.]
checkvar, e_bars, 0
checkvar, sat, 0
checkvar, n_pts, 1
save_bangp=replicate(!p,2)
save_bangx=replicate(!x,2)
save_bangy=replicate(!y,2)

;
; If we have passed PROC, then we are trying to overplot on the figue
;
   if keyword_set( proc) then begin
	proc_tags = tag_names(proc)
	ex_proc = proc.(0)
	for  ip= 1,n_elements( proc_tags)-1 do begin
	ex_proc = ex_proc+','+proc_tags(ip)+'= proc.('+strtrim(ip,2)+')'

   	endfor
	;help,ex_proc
   endif

savelogplot = logplot
if keyword_set(deriv) and logplot then begin
   print,'Changing to linear y axis for derivative plot.'
   logplot = 0
endif

; if plotfile keyword passed, it is either nonzero (use goesplot.xx as
; filename) or the name of the plot file.
if keyword_set(plotfile) then begin
   if (size(plotfile))(1) eq 7 then plotname = plotfile else $
      plotname = 'goesplot'
   noplotfile = 0
endif else noplotfile = 1

; If flare number specified, read mini catalog to get corresponding times.
if keyword_set(flare) then begin
   read_minicat, fldata, num_flares, flare=flare, error=error
   if error ne 0 then begin
      err_msg = 'Error reading flare catalog to get times for ' + $
                'selected flare.'
      goto, error_exit
   endif
   stime = (atime(fldata.start_sec, /hxrbs) )(0)
   etime = (atime(fldata.start_sec + fldata.dur, /hxrbs))(0)
endif else begin
   stime = (atime(sin, /hxrbs))(0)
   etime = (atime(ein, /hxrbs))(0)
endelse

if n_elements(sat) eq 0 and n_elements(savesat) ne 0 then sat = savesat
if n_elements(sat) eq 0 then $
case 1 of
 	(anytim(stime,/sec) gt anytim('80/1/4',/sec)) and $
		(anytim(etime,/sec) lt anytim('94/01/01',/sec)) : sat = 6
	(anytim(stime,/sec) gt anytim('94/8/18',/sec)) and $
		(anytim(etime,/sec) lt anytim('96/3/21',/sec)) :  sat=7
	(anytim(stime,/sec) gt anytim('96/3/21',/sec)) and $
		(sat eq 6 ) : sat = 8
	(anytim(stime,/sec) gt anytim('96/8/10',/sec)) and $
		(sat eq 7 ) : sat = 8
else:
endcase

;stop

; If times are the same as last time we read data, we already have the data.
; Or if times are contained within saved times, extract the subset we want.
;
; Now that we have more satellite choices, the program checks for that condition, too.
; RCJ 09/95.
;
if n_elements(savestime) ne 0 then begin
	; Changed by V. Grechnev
	if n_elements(savestime) eq 1 then savestime = savestime[0]
	if n_elements(saveetime) eq 1 then saveetime = saveetime[0]

   if (sat eq savesat) and (stime eq savestime) and (etime eq saveetime) then begin
      tarray = savetarray & yarray = saveyarray & yclean = saveyclean
      ch0_bad = savech0_bad & ch1_bad = savech1_bad
      goto, gotfile
   endif
   if (stime ge savestime) and (etime le saveetime) $
      and (sat eq savesat) then begin
      utb = getutbase(0)
      q = where ( (savetarray+utb gt utime(stime)) and $
                  (savetarray+utb lt utime(etime)), kq)
      if kq gt 0 then begin
         tarray = savetarray(q) & yarray = saveyarray(q,*)
         yclean=saveyclean(q,*)
         ch0_bad = savech0_bad - q(0)  &  ch1_bad = savech1_bad - q(0)
         qc = where (ch0_bad ge 0 and ch0_bad lt kq, kqc)
         if kqc gt 0 then ch0_bad = ch0_bad(qc) else ch0_bad = -1
         qc = where (ch1_bad ge 0 and ch1_bad lt kq, kqc)
         if kqc gt 0 then ch1_bad = ch1_bad(qc) else ch1_bad = -1
         goto, gotfile
      endif
   endif
endif

; hardcode the channel edges
loedges = [1., .5]  &  hiedges = [8., 4.]


gfits_r, tarray=tarray, yarray=yarray, stime=stime, etime=etime, $
   error=error, sat=sat, numstat=numstat, tstat=tstat, stat=stat, $
   err_msg=err_msg
if error ne 0 then begin
   if strpos( err_msg, 'File for requested time not found.') ne -1 then begin
      ;Requested satellite tried, loop through all others exiting after 20!
      print,'Try another satellite'
      goto, error_exit
   endif else goto, error_exit
endif
;endelse

help,tarray,yarray
if n_elements(tarray) gt 5 then clean_goes, tarray = tarray, yarray = yarray, $
   yclean = yclean, bad0 = ch0_bad, bad1 = ch1_bad, numstat=numstat, satellite=sat, $
   tstat=tstat, stat=stat, error=clean_error  $
else begin
   ch0_bad = -1
   ch1_bad = -1
   yclean = yarray
endelse

if clean_error then begin
   err_msg = 'Problem in Clean_GOES, error.'
   error=1
   goto, error_exit
endif

savesat=sat
savestime = stime & saveetime = etime
savetarray=tarray & saveyarray=yarray & saveyclean=yclean
savech0_bad = ch0_bad & savech1_bad = ch1_bad

;This commented out section was used to create the XDR save file for the
; SDAC widget demo.
;saveutb = long(getutbase())
;savetarray = long(savetarray*10)
;save,/xdr,file='goes_data.sav', saveutb, savetarray, saveyarray, $
;   saveyclean, savech0_bad, savech1_bad, savestime, saveetime, loedges, $
;   hiedges
;savetarray = savetarray / 10.d0

gotfile:

if keyword_set(cleaned) then yuse = yclean else yuse = yarray

sizey = size(yuse)
q=where (ch_select eq 1, kq)
if kq eq 0 then begin
   print,'No channels selected.'
   err_msg = 'Error. You didn''t select any channels.'
   goto, error_exit
endif
chana = q(0)
if kq eq 2 then chanb = q(1) else chanb = -1

set_utlabel,0 ; don't write start time label inside plot box

update=0 ; means start a new plot
if noerase then update=1 ; means add to current plot
if !p.multi(0) gt 0 then update=1 ; means add to current plot
pmulti = !p.multi


; Store the first channel requested (or derivative) in yplotted array
if keyword_set(deriv) then begin
   yplotted =(yuse(1:*,chana) - yuse(*,chana)) / $
       (fix(((tarray(1:*)-tarray(*))/3)+.5)*3.064)
   yplotted = [yplotted, yplotted(sizey(1)-2)]
endif else yplotted = yuse(*,chana) - back(chana)
if chana eq 0 then bada = ch0_bad
if chana eq 1 then bada = ch1_bad
q=where (bada ne -1, kbada)

;  If both channels were requested, store second channel in yover array.
if chanb ne -1 then begin
   if keyword_set(deriv) then begin
      yover = (yuse(1:*,chanb) - yuse(*,chanb)) / $
              (fix(((tarray(1:*)-tarray(*))/3)+.5)*3.064)
      yover = [yover, yover(sizey(1)-2)]
   endif else yover = yuse(*,chanb) - back(chanb)
   badb = ch1_bad
   q = where (badb ne -1, kbadb)
endif

if keyword_set(e_bars) then error_bars, tarray, yuse, ch0_bad, ch1_bad, ebars

psym = 10
if pointplot eq 1 then psym = 0

; Set x axis limits
if xrange(0) eq 0. then xmin = min(tarray) else xmin = xrange(0)
if xrange(1) eq 0. then xmax = max(tarray) else xmax = xrange(1)

; Set y axis limits
if yrange(0) eq 0. or yrange(1) eq 0. then begin
   ymax=max(yplotted)
   if chanb ne -1 then ymax = max([ymax,yover])
   if logplot then begin
      ymin = 1.e30
      q = where (yplotted gt 0., count)
      if count gt 0 then ymin = min(yplotted(q))
      if chanb ne -1 then begin
         q = where (yover gt 0., count)
         if count gt 0 then ymin = min([ymin,yover(q)])
      endif
      if ymin eq 1.e30 then begin
         err_msg = 'Error.  Log plot selected but no positive data to plot.'
         print, err_msg
         goto, error_exit
      endif
   endif else begin
      ymin = min(yplotted)
      if chanb ne -1 then ymin = min([ymin,yover])
   endelse
endif
if yrange(0) ne 0. then ymin = yrange(0)
if yrange(1) ne 0. then ymax = yrange(1)

;
;         use rebin here, on tarray and yplotted.
;            If n_pts=1, ave_tarray=tarray and yarray1=yplotted  RCJ 09/95
;
new_n=n_pts*(long(n_elements(yplotted)/n_pts))
if new_n lt 1 then begin
   err_msg='Sample avg. > n_elements y-axis. Try again.'
   goto,error_exit
endif
yarray1=yplotted(0:new_n-1)
ave_tarray=tarray(0:new_n-1)
yarray1=rebin(yarray1,new_n/n_pts)
ave_tarray=rebin(ave_tarray,new_n/n_pts)

title = 'GOES '+ string(sat,format='(i2)')
if keyword_set(deriv) then title = title + '    Derivative'
ytitle = 'Watts m!u-2!n'
if keyword_set(deriv) then ytitle = ytitle + ' s!u-1!n'


;  Construct labels for bottom of plot

sub1 = 'Data Start: ' + strmid(atime(xmin+getutbase(0),/hxr),0,17) + $
       '!cChannel '
sub2 = 'Plot created: ' + strmid(atime(sys2ut(0),/hxr),0,14)
edgelo = loedges(chana) & edgehi = hiedges(chana)
sub3 = '!c' + strtrim(chana+1,2) + ' (' + $
       strtrim(string(edgelo,format='(f6.1)'),2)+$
       ' - ' + strtrim(string(edgehi,format='(f6.1)'),2) + ' Angstroms)'
if not(keyword_set(deriv)) then begin
   if back(chana) gt 0. then sub3 = sub3 + '  Background subtracted = ' + $
       strtrim(string(back(chana),format='(e8.1)'),2) else $
       sub3 = sub3 + '  Background not subtracted'
endif

if chanb ne -1 then begin
   edgelo = loedges(chanb) & edgehi = hiedges(chanb)
   sub4 = '!c!c' + strtrim(chanb+1,2) + ' (' + $
          strtrim(string(edgelo,format='(f6.1)'),2)+$
          ' - ' + strtrim(string(edgehi,format='(f6.1)'),2) + $
          ' Angstroms)'
   if not(keyword_set(deriv)) then begin
      if back(chanb) gt 0. then sub4 = sub4 + '  Background subtracted = ' + $
          strtrim(string(back(1),format='(e8.1)'),2) else $
          sub4 = sub4 + '  Background not subtracted'
   endif
endif else sub4 = ' '


; Plot stuff is set up, now do plot on screen and to plot file if requested.
; If don't want plot file, we'll just do loop once with iloop=2.
; If both screen and printer device are Tek, we'll just do loop once w/ iloop=1
; For other cases, loop twice, first creating plot file then plotting to screen
ifirst = 1 & ilast = 2
set_graphics, screen = sc_device, printer = hard_device
set_plot,sc_device

if noplotfile then begin
   ifirst = 2
endif else begin
   if(sc_device eq 'TEK') and (hard_device eq 'TEK') then ilast = 1
endelse
colors = [9,3]
;
;---------- Loop over output devices --------
for iloop = ifirst, ilast do begin
   if iloop eq 1 then tek_init, file=plotname, update=update
   if !d.name eq 'TEK' then device,gin_chars=6
;   if !d.name eq 'PS' then device,/landscape
;
;  if we haven't created the window yet, create it with backing store
;  Use execute command so we can test whether it was successful w/o crashing.
   test = execute ("if (iloop eq 2) and (sc_device eq xdevice('X')) and " + $
                   "(!d.window eq -1) then window,retain=2")
   if not test then begin
      print, ' '
      if !version.os eq 'vms' then begin
         print, 'Error creating window.  Possible reasons:'
         trans = chklog("sys$login")
         ustart = strpos (trans(0), '[')
         user = strmid (trans(0), ustart+1, strlen(trans(0))-ustart-2)
         node = chklog("sys$node")
         print, 'Your display node cannot do X windows graphics.'
         print, 'You have not authorized '+node+user+' to create a ' + $
                'window on the display node.'
         print, 'You did not issue the $ SET DISPLAY/CREATE/NODE=x ' + $
                'before entering IDL.'
         print, 'Your display node name is not known to '+node+'.  Specify '+$
                'your display node''s'
         print, '   address instead of the name in the set display command. '
      endif else print,'Error creating window.'
      print, ' '
      err_msg = 'Error opening plot window.'
      goto, error_exit
   endif

   if !d.name ne 'NULL' then linecolors

   !p.multi = pmulti ; reset to start value

   if noerase eq 0 then begin
      yran = [ymin,ymax]
      ystyle = 0
   endif else begin
      !p.multi(0) = !p.multi(0)+1
      yran = crange('Y')
      if not(logplot) then ystyle = 1
      ytitle = ' '
   endelse

; This is an attempt to correct the charsize when !p.multi=[0,1,2] or
; !p.multi=[0,1,>2] without affecting a 'tek' sc_device:
   chscale=ch_scale(0.8)
   if sc_device eq 'X' and  !d.y_size le 512 then begin
        if pmulti(2) eq 2 then chscale=ch_scale(0.8)*1.8
	if pmulti(2) gt 2 then chscale=ch_scale(0.8)*2.25
   endif

   utplot, ave_tarray, yarray1, $
      ymargin=[10,2],xmargin=[13,5], title=title, ytitle=ytitle, $
      xtitle=' ', xrange=[xmin,xmax], xstyle=1, yrange=yran, ystyle=ystyle, $
      ytype=logplot, psym=psym, chars = chscale, noerase=noerase, $
      color=colors(chana), nodata=nodata
   if noerase then !p.multi(0) = !p.multi(0) - 1
   if markbad and kbada gt 0 and not keyword_set(nodata) then $
      oplot, tarray(bada), yplotted(bada),psym=7, color=colors(chana)

   if chanb ne -1 and not keyword_set(nodata) then begin

      yover1=yover(0:new_n-1)
      yover1=rebin(yover1,new_n/n_pts)
      oplot, ave_tarray, yover1, psym=psym, color = colors(chanb)
      if markbad and kbadb gt 0 then $
         oplot, tarray(badb), yover(badb), $
         psym=7, color=colors(chanb)
   endif
;
   if keyword_set(e_bars) and not keyword_set(nodata) then begin
      if keyword_set(deriv) then factor = .44 else factor = 1.
      eplot,tarray,yplotted,ey=(ebars(*,chana)*factor),color=colos(chana)
      if chanb ne -1 then eplot,tarray,yover,ey=(ebars(*,chanb)*factor),$
         color=colors(chanb)

   endif
;
;	The following is for average saving purposes:
sizey=size(yarray1)
ave_yclean=fltarr(sizey(1),2)
ave_yclean(*,0)=yarray1 & if chanb ne -1 then ave_yclean(*,1)=yover1
;
;--Use normalized x and y window limits to place labels
;
   l = !x.window(0) & r = !x.window(1)
   b = !y.window(0) & t = !y.window(1)
   xi = !x.s
;
   if exist( ex_proc) then  result_execute= execute( ex_proc)

; This is an attempt to correct the charsize when !p.multi=[0,1,2] or
; !p.multi=[0,1,>2] without affecting a 'tek' sc_device:
   chscale=ch_scale(0.9,/xy)
   dist_y=b-pl_scale(.07,/yc)
   if sc_device eq xdevice('X') and !d.y_size le 512 then begin
	if pmulti(2) eq 2 then chscale=ch_scale(0.9,/xy)*1.9
	if pmulti(2) gt 2 then chscale=ch_scale(0.9)*1.3
        dist_y=b-pl_scale(.12,/yc)
   endif

   xyouts, l, dist_y, sub1, /normal, chars = chscale
   xyouts, l+(r-l)*.53, dist_y, sub2, /normal, $
           chars=chscale
   xyouts, l+(r-l)*.18, dist_y, sub3, /normal, $
          chars = chscale, color=colors(chana)
   xyouts, l+(r-l)*.18, dist_y, sub4, /normal, $
                 chars=chscale, color=colors(chanb>0)

   if markbad then xyouts, l, dist_y, $
        '!c!c!cX marks bad data points' , /normal, chars = chscale
   if (n_pts ne 1) then xyouts, l+(r-l)*.53, dist_y, $
	'!c!c!cSample average = '+strtrim(n_pts,2) , /normal, chars=chscale

;  Print GOES importance levels on right side of log plots
   if (logplot and not keyword_set(deriv) ) then begin
	
	ylims = crange('y')
	ytickv = 10.^[-11+indgen(9)]
	ytickname = [strarr(3)+' ','A','B','C','M','X',' ']
	q = where(( ytickv ge ylims(0)) and ( ytickv le ylims(1)), kq)
	if kq gt 0 then axis, yaxis=1, ytickv = ytickv(q),/ylog, ytickname=ytickname(q)

      ;Following code is the bizarre difficult way.!!
      ;levels = [1.e-8, 1.e-7, 1.e-6, 1.e-5, 1.e-4]
      ;codes = [' A', ' B', ' C', ' M', ' X']
      ;ylims = crange('y')
      ;q = where ((levels ge ylims(0)) and (levels le ylims(1)), kq)
      ;if kq gt 0 then $
      ;   xyouts,!x.crange(1), levels, codes(q), charsize=chscale
   endif
;
   yderiv=yclean

;--Save yplotted into yderiv, so it gets returned to the main program
   if keyword_set(deriv) then begin
   yderiv(*,0)=yplotted
   if n_elements(yover) eq n_elements(yderiv(*,1)) then yderiv(*,1)=yover
   endif
;
;help,yarray,tarray,yclean,yderiv
;--Save system plotting variables for device in case we're going back
;  to plot for another device.
;
   save_bangp(iloop-1) = !p
   save_bangx(iloop-1) = !x
   save_bangy(iloop-1) = !y
;
;--Close the TEK file.
;
   if iloop eq 1 then TEK_END
endfor ; end of loop over output devices
goto, getout

error_exit:
error = 1

getout:
logplot = savelogplot  ; restore logplot value in case changed it to linear
if old_time_format eq 'YOHKOH' then yohkoh_format
end
