pro xhkplot_event, event
;
;
;
;HISTORY:
;	Written Jan-95 by M.Morrison
;	 6-Feb-95 (MDM) - Added /NOSTRING to GET_HK_INFO call
;	 7-Jun-95 (MDM) - Patch to not do the pause between pages
;			  when making hardcopy
;	 8-Jun-95 (MDM) - Copy read mnemonics list to plot list
;			  when setting the read mnem
;	12-Jun-95 (MDM) - Modified to add "LAST N HOURS" option
;	 1-Aug-95 (MDM) - Turned off the debug statement
;			- Then turned it back on
;	19-Sep-95 (MDM) - Protect against trying to plot when there hasn't
;			  be a successful database read.
;	 2-Dec-95 (MDM) - Modified to grab the mnemonics properly (it was
;			  off one character and truncated 8 character mnemonics)
;	27-Feb-96 (DBG) - Added a feature to print on the graph the number of
;			   data points being used
;
;TODO - need to read the time text field even if <CR> is not hit
;
common xhkplot_blk1, hk, all, last_all
common utcommon, utbase, utstart, utend, xst
;
qdebug = 1
qdebug = keyword_set(qdebug)
if (qdebug) then print, event_name(event)
;if (qdebug) then help, /st, event
widget_control,event.top,get_uvalue=all
widget_control, all.id_info, set_value='  '
;
qhk = data_type(hk) eq 8	;hk data has been read in
qmnem = all.mnem ne ''
qtime = (strtrim(arr2str(all.text_vals(0:1),delim=''),2) ne '') and $
	(strtrim(arr2str(all.text_vals(2:3),delim=''),2) ne '')
qplot = 0
save_dev = !d.name

case (strtrim(event_name(event),2)) of
   "BUTTON":begin                               ; option selection
      case strupcase(get_wvalue(event.id)) of
	 ;------ Main buttons
         "QUIT": begin
		widget_control, event.top,/destroy
	    endcase
	 "CLEARPLOT": begin
		clearplot
		clear_utplot
	    endcase
	 "SET PRINTER": set_printer
         "XLOADCT": xloadct, group=event.top
	 "DELETE LAST": if !d.window ne -1 then wdelete
	 "HARDCOPY": begin
		set_plot, 'ps'
		qplot = 1
            endcase
	 "READ DBASE": begin
		if (qtime and qmnem) then begin
			sttim = arr2str(all.text_vals(0:1), delim=' ')
			entim = arr2str(all.text_vals(2:3), delim=' ')
			mnem = str2arr(all.mnem)
			every = fix(all.text_vals(8)) > 1

			widget_control, all.id_info, set_value='*** Reading Database *** '
			mapx, event.top,/map,/show,sensitive=0
			hk = get_hk_info([sttim, entim], mnem, qdebug=qdebug, every=every, /nostring)
			mapx, event.top,/map,/show,sensitive=1
			widget_control, all.id_info, set_value=' '

			all.text_vals(4:7) = all.text_vals(0:3)		;copy RD time/date range into PLOT range
			for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)

			all.yrange_mnem = arr2str(fltarr(2,n_elements(mnem)))
		end else begin
			tbeep, 3
			out = ' '
			if (not qtime) then out = [out, 'You must enter the start/end time first']
			if (not qmnem) then out = [out, 'You must enter the mnemonics first']
			widget_control, all.id_info, set_value=out
		end
	     endcase
	  "PLOT ALL": begin
		qplot = 1
		all.plot_option = 0
	     endcase
	  "PLOT SEPARATELY": begin
		qplot = 1
		all.plot_option = 1
	     endcase
	  "PRINT VALUES": begin
		if (!d.window ne -1) then begin
			instruct = ['Mark on the plot the time(s) desired', $
					'Click with the middle or right button to specify a single time', $
					'Click with the left button if you wish to specify a time range', $
					'Click around starting point']
			widget_control, all.id_info, set_value=instruct
			wshow & cursor, x0, y0, /data, /down
			button = !err
			times = fmt_tim(  anytim2ints(xst, off=x0) )
			if (button eq 1) then begin
			    instruct = 'Click around the ending point'
			    widget_control, all.id_info, set_value=instruct
			    wshow & cursor, x0, y0, /data, /down
			    times = [times, fmt_tim(  anytim2ints(xst, off=x0) )]
			    qlist = 0
			end else begin
			    qlist = 1
			end

			;;mapx, event.top,/map,/show,sensitive=0
			widget_control, all.id_info, set_value='Extracting info - Stand BY'
			;;out = hkplot_info(hk, times = times)
			out = hkplot_info(hk, times = times, list=qlist)
			;;mapx, event.top,/map,/show,sensitive=1
			widget_control, all.id_info, set_value='Done...'
			print, out
			;
			outfil = concat_dir(getenv('HOME'), 'xhkplot_print.' + ex2fid(anytim2ex(!stime)))
			if (all.print_file ne '') then outfil = all.print_file
			all.print_file = outfil
			file_append, outfil, [out, ' ', ' ', ' ']
			widget_control, all.id_info, set_value='Output written to ' + outfil
		end
	      endcase
	  "SAVE INPUTS": begin
			out = ['# XHKPLOT inputs saved ' + !stime, $
				'STTIM_RD:   ' + arr2str(all.text_vals(0:1), delim=' '), $
				'ENTIM_RD:   ' + arr2str(all.text_vals(2:3), delim=' '), $
				'STTIM_PL:   ' + arr2str(all.text_vals(4:5), delim=' '), $
				'ENTIM_PL:   ' + arr2str(all.text_vals(6:7), delim=' '), $
				'EVERY:      ' + all.text_vals(8), $
				'MNEM:       ' + all.mnem, $
				'YRANGE_ALL: ' + arr2str(all.yrange_all), $
				'YRANGE_MNEM: ' + all.yrange_mnem]
			outfil = concat_dir(getenv('HOME'), 'xhkplot_inputs.' + ex2fid(anytim2ex(!stime)))
			prstr, out, file=outfil
			widget_control, all.id_info, set_value='Current inputs written to ' + outfil
	     endcase

	  ;------------------ Selecting mnemonic list
	  "SELECT MNEMONIC FROM GROUP LIST": if (event.select) then begin
		lst_file = concat_dir('$MDI_CAL_INFO', 'xhkplot_mnem.lst')
		list = rd_tfile(lst_file)
		ss = where(strmid(list, 0, 3) eq '***')
		tits = strmid(list(ss), 4, 999)
		ntits = n_elements(tits)
		tits = tits(0:ntits-2)
		;
		mapx, event.top,/map,/show,sensitive=0
		itit = xmenu_sel(tits, /one, group=event.top)
		itit = itit(0)
		mapx, event.top,/map,/show,sensitive=1
		if (qdebug) then print, itit
		;
		if (itit ne -1) then begin
		    i1 = ss(itit) + 1
		    i2 = ss(itit+1) - 1
		    mnem = list(i1:i2)
		    if (qdebug) then print, mnem
		    all.mnem = arr2str(mnem)
		    widget_control, all.id_mnem_rd, set_value=mnem

		    all.mnem_plot = all.mnem		;MDM added next three lines 8-Jun-95
		    mnem = str2arr(all.mnem_plot)
		    widget_control, all.id_mnem_pl, set_value=mnem
		end
	     end
	  "SELECT FROM FULL MNEMONIC LIST": if (event.select) then begin
		lst_file = concat_dir('$MDI_CAL_INFO', 'xhkplot_mnem.full_lst')
		list = rd_tfile(lst_file)

		mapx, event.top,/map,/show,sensitive=0
		ss = xmenu_sel(list, group=event.top)
		mapx, event.top,/map,/show,sensitive=1

		if (qdebug) then print, ss
		if (ss(0) ne -1) then begin
		    mnem = strlowcase( strmid(list(ss), 1, 8) )
		    if (qdebug) then print, mnem
		    all.mnem = arr2str(mnem)
		    widget_control, all.id_mnem_rd, set_value=mnem

		    all.mnem_plot = all.mnem		;MDM added next three lines 8-Jun-95
		    mnem = str2arr(all.mnem_plot)
		    widget_control, all.id_mnem_pl, set_value=mnem
		end

	     end
	  ;------------------ Timerange Plotting control
	  "PLOT FULL ORIGINAL INPUT TIME RANGE": begin
		all.text_vals(4:7) = all.text_vals(0:3)
		for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)
	     endcase
	  "PLOT TO FULL RANGE OF AVAILABLE DATA": begin
		if (qhk) then begin
		    n = n_elements(hk.(0).daytime)
		    all.text_vals(4) = gt_day(  hk.(0).daytime(0), /str)
		    all.text_vals(5) = gt_time( hk.(0).daytime(0), /str)
		    all.text_vals(6) = gt_day(  hk.(0).daytime(n-1), /str)
		    all.text_vals(7) = gt_time( hk.(0).daytime(n-1), /str)

		    for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)
		end else begin
		    tbeep, 3
		    widget_control, all.id_info, set_value='You must read the database first'
		end
	     endcase
	  "TO SET PLOT RANGE BY CLICKING ON PLOT": begin
		if (!d.window ne -1) then begin
			widget_control, all.id_info, set_value='Click around starting point'
			wshow & cursor, x0, y0, /data, /down
			all.text_vals(4) = gt_day(  anytim2ints(xst, off=x0), /str)
			all.text_vals(5) = gt_time( anytim2ints(xst, off=x0), /str)
			for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)
			;
			widget_control, all.id_info, set_value='Click around ending point'
			wshow & cursor, x0, y0, /data, /down
			all.text_vals(6) = gt_day(  anytim2ints(xst, off=x0), /str)
			all.text_vals(7) = gt_time( anytim2ints(xst, off=x0), /str)
			for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)
			widget_control, all.id_info, set_value='Click on PLOT button to re-plot'
			;qplot = 1
		end else begin
			tbeep, 3
			widget_control, all.id_info, set_value='You must plot the data first'
		end
	     endcase

	  ;------------------ Y Range Plotting control
	  "SET Y-RANGE FOR ALL MNEMONICS": begin
		;input, 'Enter Y minimum', ymin, !y.crange(0)
		;input, 'Enter Y Maximum', ymax, !y.crange(1)
		ymin = string(all.yrange_all(0))
		ymax = string(all.yrange_all(1))
		xmenu_gen_input, 'All Mnemonic Range ', ymin, ymax, labels=['YMIN: ','YMAX: '], group=event.top
		all.yrange_all = [float(ymin), float(ymax)]
	     endcase

	  "SET Y-RANGE FOR INDIVIDUAL MNEMONICS": begin
		mnem = str2arr(all.mnem) 
		n = n_elements(mnem)
		if (all.yrange_mnem eq '') then all.yrange_mnem = arr2str(fltarr(2,n))
		y = str2arr(all.yrange_mnem)
		y = reform(y, 2, n, /overwrite)
		ymin = string(y(0,*))
		ymax = string(y(1,*))
		xmenu_gen_input, mnem, ymin, ymax, labels=['YMIN: ','YMAX: '], group=event.top
		y(0,*) = float(ymin)
		y(1,*) = float(ymax)
		all.yrange_mnem = arr2str(y)
	     endcase
	  "SET Y-RANGE TO AVERAGE +/- 1 SIGMA": begin
		all.yrange_qsig = abs(1-all.yrange_qsig)
	     endcase

	  "SET Y-RANGE FOR ALL MNEMONICS BY CLICKING ON PLOT": begin
		if (!d.window ne -1) then begin
			widget_control, all.id_info, set_value='Click around Y-min'
			wshow & cursor, x0, y0, /data, /down
			all.yrange_all(0) = y0
			widget_control, all.id_info, set_value=['Y-Min set to ' + string(y0), 'Click around Y-Max']
			wshow & cursor, x0, y0, /data, /down
			widget_control, all.id_info, set_value=['Y-Max set to ' + string(y0), 'Click on PLOT button']
			all.yrange_all(1) = y0
			;;qplot = 1
		end else begin
			tbeep, 3
			widget_control, all.id_info, set_value='You must plot the data first'
		end
	     endcase
	  "RESET TO SELECT ALL MNEMONICS READ": begin
		all.mnem_plot = all.mnem

		mnem = str2arr(all.mnem_plot)
		widget_control, all.id_mnem_pl, set_value=mnem
	     endcase

	  ;------------------ Y Range Plotting control

	  "SET PSYM": begin
		if (event.select) then begin
		    psym = xmenu_psym(group=event.top)
		    if (psym ne -99) then !p.psym = psym
		end else begin
		    !p.psym = 0
		end
	     endcase
	  "ENABLE SEPARATE LINESTYLE FOR OVERPLOTTED LINES": begin
		all.qenab_linestyle = event.select	
	     endcase
	  "SET TO PLOT 4 PLOTS PER PAGE (2X2)": begin
		all.qenab_4plot = event.select
	     endcase

          else: message,/info,"UNKNOWN BUTTON:   " + strupcase(get_wvalue(event.id))
       endcase
   endcase 
   "TEXT_CH": begin
		newv = get_wvalue(event.id)
		ss = where(all.text_id eq event.id)
		ss = ss(0)
		case ss of
		    8: begin		;"every" text window
			    barr = byte(strcompress(newv, /remove))
			    if (min(barr) lt 48) or (max(barr) gt 57) then begin	;not a number
				tbeep, 3
				widget_control, all.id_info, set_value='The "EVERY" value must be an integer'
			    end else begin
				all.text_vals(ss) = newv
			    end
			    widget_control, all.text_id(8), set_value=all.text_vals(8)
			end
		    9: begin		;"last N hours" text window
			    barr = byte(strcompress(newv, /remove))
			    if (min(barr) lt 48) or (max(barr) gt 57) then begin	;not a number
				tbeep, 3
				widget_control, all.id_info, set_value='The "LAST N HOURS" value must be an integer'
			    end else begin
				all.text_vals(ss) = newv
				
                        	entim = ut_time()
                        	dur = float(all.text_vals(ss)) * 60.*60  ;in seconds
                        	sttim = anytim2ints(entim, off=-dur)

                        	all.text_vals(0)        = gt_day(sttim, /str)
                        	all.text_vals(1)        = gt_time(sttim, /str)
                        	all.text_vals(2)        = gt_day(entim, /str)
                        	all.text_vals(3)        = gt_time(entim, /str)

                        	for i=0,3 do widget_control, all.text_id(i), set_value=all.text_vals(i)
			    end
			    widget_control, all.text_id(9), set_value=all.text_vals(9)
			end
		    else: begin
			    if ((ss mod 2) eq 0) then newv2 = gt_day(newv,/str) $
					else newv2 = gt_time(newv,/str)
			    all.text_vals(ss) = newv2
			    if (ss eq 0) and (all.text_vals(2) eq '') then all.text_vals(2) = all.text_vals(0)

			    for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)
			end 
		end
	end

   "LIST": begin
	case event.id of
	    all.id_mnem_rd: begin
		mnem = str2arr(all.mnem)
		n = n_elements(mnem)
		ss = rem_elem(indgen(n), event.index)		;remove that item
		if (ss(0) eq -1) then mnem = '' else mnem = mnem(ss)
		all.mnem = arr2str(mnem)
		;
		widget_control, all.id_mnem_rd, set_value=mnem
	       end
	    all.id_mnem_pl: begin
		mnem = str2arr(all.mnem_plot)
		n = n_elements(mnem)
		ss = rem_elem(indgen(n), event.index)	;remove that item
		if (ss(0) eq -1) then mnem = '' else mnem = mnem(ss)
		all.mnem_plot = arr2str(mnem)
		;
		widget_control, all.id_mnem_pl, set_value=mnem
	       end
	endcase
   endcase
endcase

;--------------

if (qplot) then begin

    if (strtrim(all.mnem_plot,2) eq "") then begin
	qhk = 0
    end else begin
	mnem = str2arr(all.mnem_plot)
	if (qhk) then begin		;MDM added 19-Sep-95
	    sublist = hkplot_info(hk, mnemlist=mnem)
	    tits = hkplot_info(hk, /tit)
	end
    end

    if (qhk) then begin
	if (all.text_vals(4) eq '') then all.text_vals(4:7) = all.text_vals(0:3)	;copy RD time/date range into PLOT range
	for i=0,7 do widget_control, all.text_id(i), set_value=all.text_vals(i)

	sttim = arr2str(all.text_vals(4:5), delim=' ')
	entim = arr2str(all.text_vals(6:7), delim=' ')
	timerange = [sttim, entim]
	every=all.text_vals(8)

	widget_control, all.id_info, set_value='*** Plotting Data *** '
	mapx, event.top,/map,/show,sensitive=0
	if (!d.name eq 'X') then begin
	    if (!d.window eq -1) then window
	    wshow
	end

	if (all.qenab_4plot and (all.plot_option ne 0)) then begin
	    !p.multi = [0,2,2]
	    ;!p.charsize = 1.3
	end else begin
	    !p.multi = 0
	    ;!p.charsize = 0
	end
	case all.plot_option of
	    0: begin
		yrange = all.yrange_all
		if (yrange(0) eq yrange(1)) then yrange = 0b
		;	
		new_hkplot, hk, timerange=timerange, yrange=yrange, codelist=sublist, qdebug=qdebug, $
					qlinestyle=all.qenab_linestyle, $
				sigma=all.yrange_qsig*all.yrange_sig,every=every ;(DBG)
	       end
	    1: begin
		n = n_elements(str2arr(all.mnem))
		if (all.yrange_mnem eq '') then all.yrange_mnem = arr2str(fltarr(2,n))
		y = str2arr(all.yrange_mnem)
		y = reform(y, 2, n, /overwrite)

		n = n_elements(sublist)
		i = 0
		while (i le n-1) do begin
		    yrange = y(*, sublist(i))		;first try individual mnemonic ranges
		    if (yrange(0) eq yrange(1)) then yrange = all.yrange_all	;second try overall range
		    if (yrange(0) eq yrange(1)) then yrange = 0b		;third - reset

		    npp = (!p.multi(1) * !p.multi(2) )>1
		    qnover = ((i mod npp) ne npp-1) and (i ne n-1)
		    new_hkplot, hk, timerange=timerange, yrange=yrange, codelist=sublist(i), $
				nover=qnover, tit=tits(sublist(i)), qdebug=qdebug, $
				sigma=all.yrange_qsig*all.yrange_sig,every=every
		    if (not qnover) and (i ne n-1) and (!d.name ne 'PS') then begin
			;pause
			result = xmenu_gen_but(['Continue', 'Abort'], group=event.top, $
						instruct=['Pausing to inspect the plot'], $
						location=[0,200] )
			if (result eq 'ABORT') then i = n
		    end
		    i = i+1
		end
	       end
	endcase

	mapx, event.top,/map,/show,sensitive=1
	widget_control, all.id_info, set_value='*** Finished Plotting ***'

	set_plot, save_dev
    end else begin
	tbeep, 3
	widget_control, all.id_info, set_value='You must read the database first and/or select mnemonics'
    end
end

widget_control,event.top, set_uvalue=all, bad_id=destroyed	;update structure holding all of the info

return
end
