function histscale,image, window=window, lowcut=lowcut, hicut=hicut, $
	histfact=histfact, show=show
;
;+
;   Name: histscale
;
;   Purpose: use histogram to auto-scale (different from histogram equaliz...)
;
;   Input Parameters:
;      image - image to scale
;
;   Output 
;      function returns scaled image (byte)
;
;   Keyword Parameters:
;      lowcut - if set, ignore pixels < lowcut in histogram determination
;      hicut  - if set, ignore pixels > hicut  in histogram determination
;
;   Calling Sequence:
;      scaled_image=histscale(image [,lowcut=lowcut, hicut=hicut]
;
;
;   History:
;      25-sep-1995 (S.L.Freeland) - 
;-
minimg=min(image)
maximg=max(image)

if n_elements(lowcut) eq 0 then lowcut  = minimg+((maximg-minimg))*.1
if n_elements(hicut) eq 0 then hicut   = maximg-((maximg-minimg))*.1 

ss=where(image ge lowcut and image le hicut,sscnt) ; - apply cutoffs

hist=histogram(image(ss),/bin)		; histogram
tothist=totvec(hist)			; running total
dtotdx=deriv_arr(tothist)		; deriv.

if not keyword_set(histfact) then histfact=.0005
ss=where(dtotdx ge (histfact*max(dtotdx)),sscnt)
sscnt=0
if sscnt  gt 1 then retval=bytscl(image,min=ss(0), max=ss(sscnt-1)) else $
   retval=bytscl(image,min=lowcut, max=hicut)

if keyword_set(show) then begin
   wdef,0, (size(image))(1)*2,(size(image))(2)*2,/ur
   tv,image,0
   tv,retval,1
   !p.multi=[1,1,2]
   plot,hist,psym=10,color=100,yrange=[1,max(hist)],/ytype
   oplot,dtotdx, psym=1, color=150
   oplot,ss,dtotdx(ss),psym=2, color=200
endif

return,retval
end
