;+
;
; NAME:
;	HXISTPLOT
;
; PURPOSE:
;	Plots time series for sum of selected pixels
;
; CATEGORY:
;	HXIS display
;
; CALLING SEQUENCE:
;	HXISTPLOT
;
; CALLED BY:
;	HXISWIDGET
;
; CALLS TO:
;	HXISSUM_AREA, HXISGETWINDOW, HXISHARD, HXISSTRLABEL, UTPLOT,
;	HXISEDGE_IMG
;
; INPUTS:
;       none explicit, only through commons
;	
; OPTIONAL INPUTS:
;	none
;
; OUTPUTS:
;       none explicit, only through commons
;
; OPTIONAL OUTOPUTS:
;	none
;
; COMMON BLOCKS:
;	hxisasread.common
;	hxisarea.common
;	hxiscolor.common
;	hxisdata_info.common
;	hxistime.common
;	hxistspec.common
;	hxiswidget.common
;	
; SIDE EFFECTS:
;	If info.hard set, then the plot is printed.
;
; RESTRICTIONS:
;	none
;
; PROCEDURE:
;	Check to see if time series arrays ain memory are still valid.
;	If not then recalculate time series.  Plot the timeseries, and
;	the lifetime function if info.dead is set.
; 
; MODIFICATION HISTORY:
;	JAN-1991, Paul Hick (ARC)
;       JAN-1993, Elaine Einfalt (HSTX) - converted to widgets
;-

pro HXISTPLOT

@hxisarea.common
@hxisasread.common
@hxiscolor.common
@hxisdata_info.common
@hxislife_fnc.common
@hxispass.common                      
@hxistime.common
@hxistplot.common
@hxiswidget.common
@hxiswindow.common


error = 0				; sucess until failure

;
; If there is already a time series in memory. Further testing will be performed
; to see if this saved spectra fits all the current program conditions
;
 
  if (n_elements(TPLOT_TIME) ne 0) and (n_elements(TPLOT_DATA) ne 0) $
     then in_memory=1 $
     else in_memory=0

;
; If there are no selected pixels, then select some pixels
;

  if (pixels(0) eq -1) then HXISAREA, error=error 

;
; If still don't have any pixels, nothing more can be done here.
; Else, how many pixels are there.
;

  if (PIXELS(0) eq -1) or error then begin
	widget_control, comment, set_value='No pixel(s) selected', /append
	error=1
	return
  endif else CUR_NPIX = n_elements(PIXELS)  ; # of pixels selected most recent

;
; Test to see if the pixels have changed since last call to TPLOT
;

  last_npix = n_elements(T_PIXIES)		; # of pixels from last TPLOT

  if last_npix ne cur_npix then in_memory = 0 $ ; Selected different pixels.
  else begin  					; Same number of pixels, but
						;    are they the same pixels.
    not_eq = where(T_PIXIES ne PIXELS)          ; Compare the old and the new
    if not_eq(0) ne -1 then in_memory = 0       ; They were not the same in
						;    at least one element
  endelse

;
; All bets are off if the TPLOT calculation has been invalidated.
;
  if INFO.MODE(1) eq 0 then in_memory = 0   


;
; If there is a TPLOT time series in memory and the pixels are the same...
; We can only use the time series in memory if the current parameter match
; the parameters present when the time series was calculated.
;


 if in_memory then begin

  if (timg(info.frst_img) ge T_START) and $     ; if start time within bounds
     (timg(info.last_img) le T_STOP)  and $    	;    end time within bounds
     (info.tover    	  eq T_TOVER) and $	;    same average
     (info.back    	  eq T_BACK)  and $	;    same background
     (info.dead    	  eq T_DEAD)  and $	;    same dead time
     (info.sig            eq T_SIG)   and $      ;    same sigma
     (info.deriv    	  eq T_DERIV) $		;    same derivative request
  then GOTO, PLOT_TIMESERIES                    ; then don't recalculate

 endif



;===========================================================================
;
; Well, we didn't get to jump. So, we need to go calculated time series.
;
;===========================================================================



;
; Create arrays for time series
;

  n_plots  = n_elements(where(info.btyp ge 0))		; # plots
  n_images = info.last_img - info.frst_img + 1		; # of images

  TFF = replicate(-1., n_images, n_plots)  
  if n_plots eq 1 then TFF = reform(TFF, n_images, 1)

  ;
  ; Time array for time series, one time for each image used in display
  ;

  TXX = timg(info.frst_img:info.last_img)

							
;
; Save current settings, they will be restored after the SUM_AREA loop
;
  save_frst = info.frst_img  &  save_last = info.last_img 	
  save_mode = info.mode(0)   &  info.mode(0) = 0		

;
; Half the averaging value in units of hours
;
  average = float(info.tover) / 7200.	

;
;
; Calculate the TPLOT time series for the current program parameters
;

  tellme = 'Summing selected pixels for images ' + strtrim(info.frst_img+1,2) $
	 + ' to ' + strtrim(info.last_img+1,2) + ',   processing image ' 

  widget_control, comment, set_value='Calculating time series...', /append

  for I = save_frst, save_last do begin 
    ;
    ; Loop over all images between first and last image displayed
    ;
      if ((I+1) mod 25) eq 0 then $
         widget_control, comment, set_value=tellme + strtrim(i+1,2),/append

    ;
    ; Collect all the images within the given average of this image.
    ; Reassign first and last image to this range for SUM_AREA.
    ;

      range = where(abs(timg-timg(I)) le average)  
      INFO.FRST_IMG = range(0)                     
      INFO.LAST_IMG = range(n_elements(range)-1)

    ;
    ; Sum all the pixels selected for this image ("I") in the range.
    ; Results in N_PLOTS values, one for each plot.
    ;
      HXISSUM_AREA, datarea, I, save_last, error=error

      if error then begin
	widget_control, comment, set_value='Unable to sum pixels.', /append
	return
      endif

    ;
    ; The TPLOT time series data values
    ;
      TFF(I-save_frst, *) = datarea 

  endfor

  widget_control, comment, set_value='Completed pixel summing.', /append

;
; Restore values now that SUM_AREA is done.
;
  info.frst_img = save_frst  &  info.last_img = save_last
  info.mode(0)  = save_mode

; 
; Each of the plots requires at least two points of valid data.
;
  success = 0						; assumes no data
  for A =0, n_plots-1 do begin   		
        ok = where( (TFF(*,A) ne -1.), valid_data)    	; is there valid data  
	if valid_data gt 1 then success=1  		; there is at least 2
  endfor

  if not(success) then begin 	
     ;
     ; There was not one plot that had at least two valid data points.
     ;
     widget_control, comment, set_value='Sorry. No valid data available ' + $
			      'for time series of summed pixels.',/append
     error = 1
     return
  endif


;
; Do the derivative, if requested.
; 
  if info.DERIV then begin			
     for A = 0, n_plots-1 do begin
	 I = where(TFF(*,A) ne -1.,I0)
	 if I0 gt 1 then begin
	    I0 = I0-1
	    T0 = TIMG(I)  &  F0 = TFF(I,A)
	    TP = shift(T0,-1)  &  TP(I0) = 2*T0(I0)-T0(I0-1)
	    FP = shift(F0,-1)  &  FP(I0) = 2*F0(I0)-F0(I0-1)
	    TM = shift(T0,1)   &  TM(0)  = 2*T0(0)-T0(1)
	    FM = shift(F0,1)   &  FM(0)  = 2*F0(0)-F0(1)
	    TD = (TP-T0)/(T0-TM)
	    D1 = (F0-FM)*TD  &  D2 = (FP-F0)/TD  &  D1 = D2/(TP-TM)
	    TFF(I,A) = D1/3600.
	 endif
     endfor
   T0 = 0  &  F0 = 0  &  TP = 0  &  TM = 0  & TP = 0  & FP = 0
 endif

;
; Have now successfully calculated the time series for TPLOT
;
  info.mode(1) = 1				

;
; The parameters used to calculate the TPLOT time series to be put in memory
;
  T_START  = timg(info.frst_img)
  T_STOP   = timg(info.last_img)
  T_TOVER  = info.tover            
  T_DERIV  = info.deriv 
  T_BACK   = info.back
  T_DEAD   = info.dead            
  T_SIG    = info.sig
  T_PIXIES = pixels   	     

;
; This is the resulting TPLOT time series for the current program parameters
;
   TPLOT_DATA = TFF  
   TPLOT_TIME = TXX



PLOT_TIMESERIES:

;===========================================================================
;
; Have the TPLOT time series, so give the people what they want.
;
;===========================================================================



;
; Need to get compressed list of images, with valid data, within current times.
; Valid data still means, at least two points of non-negative values.
;

  plot_arr = -1  
  n_plots  = n_elements(where(info.btyp ge 0))		; # plots 

  ;
  ; Save the indexes of all the data that can pass the test below.
  ; Only valid data will be plotted. 
  ;

  valid_indexes = fltarr(n_elements(tplot_time),6) - 1
  for A = 0, n_plots-1 do begin 	    ; for each of the displayed images

;       ;
;       ; Within the current program time range, where are the valid data 
;       ; for each plot.
;       ;
;
;         I = where( (TPLOT_DATA(*,A) ge (info.scal*.001)) and $
;		    (timg(info.frst_img) le tplot_time) and $
;		    (timg(info.last_img) ge tplot_time), still_valid)

    ;
    ; Do this "WHERE" to get time range to be used. Do the greater-equal
    ; test in the PLOT command, so lines are not connected between data gaps.
    ;
    N = where( (timg(info.frst_img) le TPLOT_TIME)   and $
	       (timg(info.last_img) ge TPLOT_TIME) )
    ;
    ; Do this "WHERE" to get the number of valid data points.
    ;
    I = where(TPLOT_DATA(N,a) ge (info.scal*.001), still_valid) 

    valid_indexes(0,a) = N

    ;
    ; Which image positions have this valid data. These will be the
    ; only ones plotted.
    ;

      if still_valid gt 1 then $
           if plot_arr(0) ne -1 then plot_arr = [plot_arr,A] $
			        else plot_arr = A
  endfor

  if plot_arr(0) eq -1 then begin
     ;
     ; There was not one plot, in this time range, that had at least two 
     ; valid data points.
     ;
       widget_control, comment, set_value='Sorry. No valid data available ' + $
			        'for time series in this time range.',/append
       return
  endif


  n_valid = n_elements(plot_arr)       		; # w/ valid data
  n_plots = n_valid + (1 * info.dead)		; leave room for lifetime fnc

;
;
; Set up the output plot
;
;

;
; For screen output get a new window or reuse old one.
; For a hard copy set up the device.
;
    
  info.cplot_up = 0 				; about to erase current window
  if not(info.hard) then hxisgetwindow  $
		    else hxishard, /fileopen, colo=info.colo

  !P.MULTI = [n_plots, 1, n_plots]

  if not(info.hard) then TEXT = 1.7 $   ; to screen
		    else TEXT = 1.      ; hard copy

  if n_plots gt 2 then CSIZE = 1.6*TEXT $  ; p.multi apply automatic "*0.5"
                  else CSIZE = 1.6*TEXT * 0.5

;
; Each BTYP gets it's own colored line
;
  colors = my_colors

; 
; When doing hard copy to grayscale printer lines should be in black
; 
  if info.hard and not(info.colo) then colors = colors * 0


;
; Loop through each plot, plotting time series for each band selected.
;

  widget_control, comment, set_value='Formatting plot...',/append
  xrange=[timg(info.frst_img),timg(info.last_img)]*3600.
  a_time = atime((364+info.doy)*86400.)

  for A = 0, n_valid-1 do begin					

       this_img = plot_arr(a)
       hxisstrlabel, info.btyp(this_img), info.blow(this_img), $
		     info.bup(this_img),  clab, quant, I  
       quant = quant+' ['+I+']'

       if (a ne n_valid-1) or INFO.DEAD $
	 then xtitle = '' $
         else xtitle = 'Universal Time (DOY ' + strtrim(info.doy,2) + ')'

       ;
       ; Tell me again...where were those valid indexes for this plot?
       ;

       valid = where(valid_indexes(*,this_img) ne -1)
       index = valid_indexes(valid, this_img)


       utplot, 	tplot_time(index)*3600., /yohkoh, $
		tplot_data(index,this_img)>(info.scal*.001) , a_time, $
		xrange=xrange,			$
		xmargin=[12,21+(3*info.hard)],	$
		ymargin=[3.0,1.5],		$
		charsize=CSIZE,			$
		xcharsize=1.,			$
		ycharsize=1., 			$
		title=CLAB,			$
		ytitle=quant,			$
		xtitle=xtitle,			$
		ytype=info.scal,		$
		/nolabel,			$
		/nodata

       oplot, 	tplot_time(index)*3600., tplot_data(index,this_img), $ 
	        color=colors(info.btyp(this_img))

  endfor

;
; Output program parameter on right side of output
;

  left = 0.80  &  a = 0.5  &  b = 0.03
  yesno = ['NO','YES']

  xyouts, LEFT,A,/normal,'Backg sub : ' + YESNO(INFO.BACK),size=TEXT
  A = A-B		
  xyouts, LEFT,A,/normal,'Dead time : ' + YESNO(INFO.DEAD), size=TEXT
  A = A-B		
  xyouts, LEFT,A,/normal,'Sigma     :' + string(format='(F4.1)', $
				sqrt(INFO.SIG)),size=TEXT
  A = A-1.5*B	
  xyouts, LEFT,A,/normal,'Start time : ', size=TEXT
  A = A-B		
  xyouts, LEFT,A,/normal, usestart, size=TEXT

  A = A-1.5*B	
  xyouts, LEFT,A,/normal,'Stop time : ', size=TEXT
  A = A-B		
  xyouts, LEFT,A,/normal, useend, size=TEXT

  A = A-1.5*B	
  xyouts, LEFT,A,/normal,'Average : ', size=TEXT
  A = A-B		
  xyouts, LEFT,A,/normal, strtrim(string(format='(F10.1)',info.TOVER),1)+ $
				' sec', size=TEXT



;
;
; Lifetime function plotting
;
;

  if INFO.DEAD then begin
    ;
    ; Plot the lifetime function, below the already plotted bands
    ;
      utplot, timg(fmode)*3600., dfm(fmode), $
		xrange=xrange,		$
		xmargin=[10,21],		$
		ymargin=[3.0,1.5],	$
		charsize=CSIZE, $
		xcharsize=1.,		$
		ycharsize=1., 		$
		ytitle="LIFETIME FNC" , $
		xtitle='Universal Time (DOY ' + strtrim(info.doy,2) + ')', $
		ytype=info.scal, 	$
		/nolabel

    ;
    ; Plot the smoothed lifetime function, below the already plotted bands
    ;
      oplot, TIMG(FMODE)*3600., LIFEFNC(FMODE), thick=2, color=colors(7)

    ;
    ; Plot the line through the two anchor points.
    ; This is the dead time correction used in other routines
    ;

      plots, [timg(info.frst_img),timg(info.last_img)]*3600., $
		LF1+RC*([timg(info.frst_img),timg(info.last_img)]-T1), $
		color=colors(5)

 endif

;
; Rap it up
;

!P.MULTI = 0  
!y.type = 0				; in case a used /YTYPE above

;
; If the pixels selected is any except the sum of fine and coarse FOV,
; draw the small contour in upper right corner
;

  if n_elements(pixels) ne 512 then hxisedge_img   	

;
; Plot complete, close and print.
;  
  
  if info.hard then hxishard, /fileclose, colo=info.colo


  wshow, current_window			; just incase pushed behind

return  
end