;+
; NAME:
;       GOOD_MAX
; PURPOSE:
;       Determine the real plot maximum, ignoring bad points
; CALLING SEQUENCE:
;       max = good_max(counts [,gvec,gmin])
; INPUTS:
;       counts          array of counts
; OUTPUTS:
;       max             maximum value
; OPTIONAL OUTPUTS:
;	gvec		vector of points used in the max. determination
;	gmin		minimum using same vector
; KEYWORD OUTPUTS:
;	thresh		threshold to test against
;	debug		prints other info.
; RESTRICTIONS:
;
; PROCEDURE:
;       Finds good maxiumum after first removing "spikes"
; MODIFICATION HISTORY:
;       RDB  04-Jul-92
;	RDB     Jun-94	Rewritten
;	RDB  29-Jul-94	Small correction for last point
;                       Improved handling of single point
;       RDB  27-Oct-95  Improved removal of bad points
;                       added /nan in min and max function calls...
;-

function good_max,cnts,gvec,gmin,thresh=thresh,debug=debug

if n_elements(cnts) eq 1 then begin	;only one value
  gmax = cnts
  gmin = cnts
  gvec = [0]
  return,gmax
endif

threshold = 2000.
if keyword_set(thresh) then threshold = thresh

;	look for sudden changes
bb=cnts(1:*)-cnts(0:*)
nn = [where(abs(bb) gt threshold),n_elements(cnts)-2]
mm = nn(1:*)-nn(0:*)
if keyword_set(debug) then begin
  print,nn,mm
  print,bb(nn)
endif

;	and construct vector of values not including them
pp = indgen(n_elements(cnts))
if nn(0) gt -1 then begin
;;  if n_elements(mm) eq 1 and mm(0) eq 0 then $		;last point bad?
;;  pp(nn+1) = -1  else  pp(nn(where(mm gt 1))) = -1
  pp(nn+1) = -1  
  pp = all_vals(pp)
  if pp(0) eq -1 then pp=pp(1:*)
endif
if keyword_set(debug) then help,cnts,pp

gvec = pp
if fix(strmid(!version.release,0,1)) ge 4 then begin
  print,'Version 4 min-max'
  gmin = min(cnts(pp),/nan)
  gmax = max(cnts(pp),/nan)
endif else begin
  gmin = min(cnts(pp))
  gmax = max(cnts(pp))
endelse

print,'Gmin,gmax =',gmin,gmax
zz = where(cnts gt gmax)
if keyword_set(debug) and zz(0) ge 0 then print,'Values exceeding gmax:',cnts(zz)

return,gmax
end
