;+
; NAME:
;	CUT_MAX	  
;
; PURPOSE:
;	To cut an image at a certain value of its histogram.
;	This can be useful when a few 'hot' pixels (as they
;	might occur during flatfielding) might damage the 
;	dynamical range of an image.
;	First the histogram of the image is calculated. 
;	Then, the value is determinated for which a certain
;	fraction (default: 99%) lies below this level. All
;	values higher than this level are set to the pixel
;	value determined by this level.
;
; CATEGORY:
;	PICO
;
; CALLING SEQUENCE:
;	CUT_MAX,image
;
; INPUTS:
;	image:	a two dimensional (image-)array.
;
; OPTIONAL INPUTS:
;	None
;
; KEYWORD PARAMETERS:
;	LEVEL:	gives a user specified level at which the
;		histogram should be cut. If not specified,
;	        the default value is 0.99
;       UPPER, LOWER: If either is set, the upper cutting
;               or lower cutting is performed at levels
;               LEVEL and (1-LEVEL)
;       VERBOSE: If set, additional information is given
;
; OUTPUTS:
;	The image, limited in the dynamical range to the 
;	(LEVEL) lower part.
;
; OPTIONAL OUTPUTS:
;	None
;
; EXAMPLE:
;	newimage=CUT_MAX(image,LEVEL=.99,/LOW,/UP)
;	The upper 1% of the image will be set to the value
;	of the former 99% level, the lower 1% to the value
;	of 1%;
;
; COMMON BLOCKS:
;	None
;
; SIDE EFFECTS:
;	None
;
; RESTRICTIONS:
;	None
;
; MODIFICATION HISTORY: V1.0 Alexander Epple 30-Jun-1994 : MPAe
;       LOWER and UPPER Keywords: AE 25-MAR-1997 MPAe
;-
;+

function cut_max,img, LEVEL=level, UPPER=up, LOWER=low, $
                 VERBOSE=verbose, ORGSIZE=orgsize
time=SYSTIME(1)

dt=DATA_TYPE(img)
image=FLOAT(img)
sz=SIZE(image)

IF (KEYWORD_SET(up)+KEYWORD_SET(low) EQ 0) THEN up=1
IF (NOT KEYWORD_SET(orgsize)) THEN image=CONGRID(image,sz(1)/4,sz(2)/4)

IF (NOT KEYWORD_SET(level)) THEN level=.99
IF ((level GT 1.0) OR (level LE 0)) THEN level=.99

IF (level EQ 1) THEN RETURN,img

minimum=1.*min(image)
maximum=1.*max(image)
span=maximum-minimum
IF (span EQ 0) THEN RETURN,img
binning=span/1000.

hist=HISTOGRAM(FLOAT(image), BINSIZE=binning, OMIN=omin, OMAX=omax)

histsum=LONARR(N_ELEMENTS(hist))
FOR i=1,N_ELEMENTS(hist)-1 DO histsum(i)=histsum(i-1)+hist(i)
histsum=FLOAT(histsum)/MAX(histsum)

indexlow=(WHERE(histsum GT (1-level)))(0)
indexup=(WHERE(histsum GT level))(0)

limitlow=minimum+indexlow*binning
limitup=minimum+indexup*binning

IF KEYWORD_SET(up) THEN BEGIN
  IF KEYWORD_SET(low) THEN BEGIN
    image=img<limitup>limitlow
  ENDIF ELSE BEGIN 
    image=img<limitup
  ENDELSE
ENDIF ELSE image=img>limitlow

IF KEYWORD_SET(verbose) THEN BEGIN
  PRINT,'Original min and max: ',minimum, maximum
  PRINT,'New min and max:      ',min(image),max(image)
  PRINT,'Time needed: '+SC(SYSTIME(1)-time,DEC=2)+' sec.'
ENDIF

RETURN,RECONVERT(image,dt)

END

