;+
; Name:  hsi_obs_summ_rate::plot
;
; Purpose:  Plot method for hsi_obs_summ_rate object.
;
; Calling sequence: obj -> plot
;	Any plot keywords passed in will be passed through to the plot routines through _extra.
;
; Keyword Inputs:
;	dim1_use - array of indices in y array to use (i.e. the energy bands to plot)
;	plotman_obj - plotman object reference.  If passed, some parameters are set in plotman.
;	flags_obj - an existing hsi_show_flags() object.  If you don't pass one in, but do select
;		some flags to be shown (by calling with /saa, /night, etc), a ndw flags_obj will be created.
;	ylog -  if set, y axis will be log
;	Can also pass in most regular plot keywords and plot keywords accepted by the xyplot__define object
;	Can also pass in arguments to hsi_show_flags, such as /saa, /night, /flare, /atten, /decim, and
;      flag_changes structure
;      corrected_countrate - if set, correct the count rate for the
;      plot
;      obs_summ_flag_obj - an hsi_obs_summ_flag object, for the flags
;      needed for the corrected count rate
;
; Outputs:
;	status = 0 means success, 1 means problem.
;	err_msg - Error message if any.  Default is ''.
;
; Examples:
;	obj = obj_new('hsi_obs_summ_rate')
;	d = obj -> getdata(obs_time_interval=['2000/8/31 0200', '2000/8/31 0500'])
;	obj -> plot
;	hsi_linecolors
;	obj -> plot, dim1_colors=indgen(10)+1, /ylog, /saa, /night, /flare
;	obj -> plot, dim1_use=[0,1,2], charsize=2.
;
;   To pass in a previously accumulated set of flag changes (so that the files won't be read again):
;	flag_obj = hsi_obs_summ_flag()
;	d = flag_obj -> getdata()
;	flag_changes = flag_obj -> changes()
;	obj -> plot, dim1_colors=indgen(10)+1, /ylog, /saa, /night, /flare, flag_changes=flag_changes, $
;		flag_colors=[8,4,6,9,2,3]
;
; History:  Written Kim, 27-Jul-2000
; Modifications:
;   5-Mar-2001, Kim.  Times in time array are at start of interval, so offset time array by
;     1/2 an interval to plot correctly.
;   16-Apr-2001, Kim.  Use utplot object instead of ltc object.  Also added plotman_obj keyword
;     so if there is a plotman object being used, this routine can set some parameters needed
;     in the plotman object (namely the dim1 parameters).
;	1-May-2001, Kim.  Set dim1_name, not dim1_unit, in plotman object. Pass dim1_vals to utplot
;		object for constructing label.
;	26-Feb-2002, Kim.  Added flags_obj keyword, and calls to show flag labels and bars
;	08-Aug-2002, Kim.  Updated header documentation
;       21-aug-2002, jmm, added obs_summ_flag_obj, and
;       corrected_countrate keywords
;	2-Dec-2002, Kim.  utplot object no longer expects times in TAI
;	12-mar-2003, jmm, Added Catch to avoid crashes
;	30-Jul-2004, Kim. utplot object now expects a utbase, and x array relative to utbase
;	04-Apr-2005, Kim.  Make label containing dets, flags, etc, wrap if longer than 18 chars
;	   Requested by A. Shih so size of plot portion will always be same for browser tool
; 06-Aug-2009, Kim.  Destroy objects before exiting (memory leak).  
;       9-mar-2011, jmm, Gets detector label from info.seg_index_mask,
;                        to deal with cases where d9 is not added
; 11-Oct-2017, jmm, added alt_title keyword
; 29-Jun-2018, jmm, Passes _extra into corrected_countrate call, for
;                   /att0 option
; 6-nov-2019, jmm, replaced HESSI in title with RHESSI
;-
;============================================================================

pro hsi_obs_summ_rate::plot, $
	status=status, $
	err_msg=err_msg, $
	dim1_use=dim1_use, $
	plotman_obj=plotman_obj, $
	flags_obj=flags_obj, $
        ylog=ylog, $
        corrected_countrate=corrected_countrate, $
        obs_summ_flag_obj=obs_summ_flag_obj, $
        smooth2=smooth2, $
        alt_title=alt_title, $
	_extra=_extra

status = 1
err_msg = ''
local_flags_obj = 0

;err = 0
;catch, err
;If(err Ne 0) Then Begin
;  catch, /cancel
;  message, /info, 'Error, No Plot'
;  err_msg = 'HSI_OBS_SUMM_RATE::PLOT, Error'+strcompress(string(err))
;  goto, cleanup
;Endif

checkvar, ylog, 1

info = self -> get (/info)
IF(keyword_set(corrected_countrate)) THEN BEGIN ;jmm, 21-aug-2002
   data = self -> corrected_countrate(obs_summ_flag_obj=obs_summ_flag_obj,_extra=_extra)
;smooth2 keyword smooths to look to see how flare list should work
   If(keyword_set(smooth2)) Then Begin
       For j = 0, n_elements(data[*,0])-1 Do Begin
           tmp = reform(data[j, *])
           tmp = smooth(tmp, 15)
           tmp = smooth(tmp, 31)
           data[j, *] = tmp
       Endfor
   Endif
ENDIF ELSE data = self -> get (/countrate) ;returns uncompressed cps

times = self -> get (/time_array)
nen = n_elements(info.energy_edges)
dim1_vals = transpose([ [info.energy_edges[0:nen-2]], [info.energy_edges[1:nen-1]] ])

; times returned are at start of interval
times = times + (times[1]-times[0])/2.

if exist(_extra) then begin
	if tag_exist(_extra,'timerange') then if total(anytim(_extra.timerange)) ne 0. then timerange=_extra.timerange
endif
if not exist(timerange) then timerange = self->get(/obs_time_interval)

det_nos = strcompress(/remove, string(where(info.seg_index_mask[0:8] Eq 1)+1))
label = 'Det '+strjoin(det_nos,  ',')
if not exist(flags_obj) then begin
  flags_obj = hsi_show_flags(_extra=_extra)
  local_flags_obj = 1
endif
flags_selected = flags_obj -> get(/selected)
if total (flags_selected) gt 0 then begin
	flag_text = flags_obj -> getlabel (timerange, n_bar=n_bar)
 	if flag_text ne '' then label = label + ', ' + flag_text
	if n_bar gt 0 then label = [replicate('',n_bar), label]
endif
; force this part of label to be short than longest line in label which
; will be last channel  - '7000 - 20000 kev --'
label = wrap_txt (label, length=18, delim=', ', /no_dollar)

IF(keyword_set(corrected_countrate)) THEN BEGIN ;jmm, 21-aug-2002
   title = 'RHESSI Observing Summary Count Rates, Corrected'
   ytitle = 'Corrected Count Rate (s!u-1!n detector!u-1!n)'
ENDIF ELSE BEGIN
   title = 'RHESSI Observing Summary Count Rates'
   ytitle = 'Count Rate (s!u-1!n detector!u-1!n)'
ENDELSE

IF(keyword_set(alt_title)) THEN title = alt_title

if not exist(dim1_use) then dim1_use = indgen(n_elements(data[*,0]))

dim1_ids = info.dim1_ids + ' keV'
times = anytim(times)
utbase = min(times)
utplot_obj = obj_new('utplot', times-utbase, transpose(data), utbase=anytim(utbase,/vms))

utplot_obj -> set, $
	id=title, $
	dim1_id=dim1_ids, $
	data_unit=ytitle, $
	dim1_unit='keV', $
	dim1_use = dim1_use, $
	dim1_vals = dim1_vals, $
	label=label, /enab_sum, _extra=_extra

utplot_obj -> plot, ylog=ylog, status=status, err_msg=err_msg, _extra=_extra

if err_msg ne '' then print,err_msg

if not status then return

if total (flags_selected) gt 0 then flags_obj -> display, timerange

; maybe resurrect the following to allow energy range input selection (instead of selecting
; by indices in dim1_use
;i1 = 0   &  i2 = 8
;if n_elements(energy_plot) eq 2 then begin
;	nedg = n_elements(info.energy_edges)
;	q1 = where (energy_plot[0] lt info.energy_edges[1:*], count1)
;	q2 = where ( energy_plot[1] gt info.energy_edges[0:nedg-2], count2)
;	if count1 gt 0 and count2 gt 0 then begin
;		i1 = (q1[0]) > 0
;		i2 = (q2(count2-1)) < 8
;		if i2 lt i1 then err_msg = 'No data in specified energy range: ' + arr2str(energy_plot)
;	endif else begin
;		err_msg = 'No data in specified energy range: ' + arr2str(energy_plot)
;	endelse
;endif

; maybe resurrect the following to put the full energy range in the legend when plotting the sum
;e_string = strtrim (string (info.energy_edges, format='(f7.1)'), 2)
;text =e_string[i1] + ' - ' +e_string[i2+1] + ' keV'

if is_class(plotman_obj, 'plotman', /quiet) then $
	plotman_obj -> set, $
		dim1_name=info.dim1_unit, $
		dim1_ids=info.dim1_ids, $
		dim1_use=dim1_use, $
		/dim1_enab_sum

cleanup:
; use destroy in case they don't exist yet - won't complain
destroy, utplot_obj
if local_flags_obj then destroy,flags_obj  ; don't destroy if it gets passed out

return
end
