; Copyright (c) 1998-2007 Andreas Scholl (LBNL); A.P. Hitchcock  All rights reserved
;+
;NAME:
;		CIMAGE.PRO
;
;LAST CHANGED: ----------------------------------- 	12-Sep-07 (aph)
;
; PURPOSE:
;	This procedure cleans up images by removing very low and very high values.
;
; CATEGORY:
;	Image processing
;
; CALLING SEQUENCE:
; for procedures:
;	CIMAGE;;ResetImageRange
;
; INPUTS: none
;
; KEYWORDS: none
;
; OUTPUTS:
;	Image is modified (??)
;
; COMMON BLOCKS: none
;
; SIDE EFFECTS: none
;
; RESTRICTIONS: does not work if low contrast, Error trapped if flat image
;
; PROCEDURE:
;	This procedure calculates a histogram and determine two levels (Top and Bottom)
; such that 2 rows worth of pixels are above and two rows worth of
; pixels are below these levels. The image is then scaled between Top and Bottom
; instead of using Minimum and Maximum.
;
; EXAMPLE:
;
;
; MODIFICATION HISTORY:
; (22-Jan-07 as) Andreas Scholl provided routine as a solution to problem of arbitary removal
;         of first 5 columns (causes dimensional problems)
; (12-Sep-07 aph) incorporated; AXIS standard header added
;-


pro CIMAGE::ResetImageRange

        CATCH, ErrorStatus
        if ErrorStatus ne 0 then begin
                PRINT, !ERROR_STATE.MSG
                self.Top = self.Maximum
                self.Bottom = self.Minimum
                return
        endif
        self.Maximum = MAX(self->GetImageData(), MIN = mini, /NAN)
        self.Minimum = mini
        nbins = UINT(self.Maximum-self.Minimum<1024)
        binsize = FIX((self.Maximum-self.Minimum)/nbins, TYPE = self.PixType)
        hist = HISTOGRAM(self->GetImageData(), LOCATIONS = locs, MAX = self.Maximum, MIN = self.Minimum, BINSIZE = binsize)
        lim = ULONG(SQRT(FLOAT(self.ImDim[0])*FLOAT(self.ImDim[1])))*2
        if lim eq 0L then lim = 1L
        s = 0L
        ind = 0
        while (s lt lim) and (ind lt N_ELEMENTS(locs)) do begin
                s = s + hist[ind]
                ind = ind+1
        endwhile
        if ind ge N_ELEMENTS(locs) then ind = ind-1
        self.Bottom = locs[ind]
        s = 0L
        ind = (nbins>1)-1
        while (s lt lim) and (ind ge 0) do begin
                s = s + hist[ind]
                ind = ind-1
        endwhile
        self.Top = locs[ind+1]
        if self.Bottom ge self.Top then self.Top += 1


end