FUNCTION MinVect, array 

;+
; PURPOSE:
;	Looks for a minimum in EACH x-profile and returns
;	a vector of dimension N_Elements(ny)
;-

  n = N_Elements( array(0,*) )
  minimumArr = FltArr(n)
  FOR i = 0, n-1 DO minimumArr(i) = Min(array(*,i))

  RETURN, minimumArr

END ; MinVect


FUNCTION MinEnvBack, imageP, wLenP, dir, $
	BACKGROUND = back

;+
; NAME: 
;	Minimum Envelope Background Subtraction
; PURPOSE:
;	given a window of length n, a minimum envelope 
;	(in x- or y-direction) is calculated by centering the 
;	window around each scan (channel) to find the minimum
;	value inside the window. This minimum function  is
;	smoothed by an 1/dist-window of the same length n, 
;	where dist is the distance from the center of the window.
;	This smoothed minimum envelope is interpreted as
;	a background and is subtracted from the input data.
; CALLING SEQUENCE:
;	result = MinEnvBack( image, windowLen, direction )
; INPUTS:
;	image: a 2D real array
; 	windowLen: the length of the minimum envelope window
;	direction: 'X' or 'Y'
; RESULT:
;	the image with the minimum envelope background 
;	subtracted, of real type.
; KEYWORDS:
;	BACKGROUND: the minimum envelope backgound,
;		an array of same size as "image". This
;		is an output parameter.
; PROCEDURE:
;	For each profile, the minimum inside a given window
;	is stored and forms the first background. A weighted 
;	averaging of it is done before it is subtracted from the
;	original image.
;-
; MODIFICATION HISTORY:
;	Created in September 1991 by A.Csillaghy,
;		Inst. for Astronomy, ETH Zurich
;		Original fortran subroutine: M. Gudel.
;


  image = imageP
  nx = N_Elements( image( *, 0 ) )
  ny = N_Elements( image( 0,* ) )

  IF N_Elements(dir) EQ 0 THEN dir = 'X'
  IF dir NE 'X' THEN BEGIN
    image = Transpose( image )
    temp = nx & nx = ny & ny = temp
  ENDIF
 
  wLen = Fix(wLenP) > 1 < nx
  halfEnv = wLen / 2
  
; 1. computing minimum envelope

  back = FltArr( nx, ny )
  FOR i = 0, nx-1 DO back(i,*) = MinVect( $
	image( (i-halfEnv)>0:(i+halfEnv)<nx-1, * ) )

; 2. weighted averaging of envelope

  FOR i=0,nx-halfEnv-1 DO BEGIN
    leastIndex = (i - halfEnv) > 0
    highestIndex = (i+halfEnv) < (nx-1)
    span = highestIndex - leastIndex + 1
    indexes = IndGen( span ) + leastIndex
    weights = 1./(ABS( leastIndex + FIndGen( span ) - i )  + 1)
    IF ny LE 1 THEN $
      back( i ) = Total( weights * back(indexes) )/ Total( weights ) $
    ELSE $
      back(i,*) = (weights # back( indexes, * ) )/ Total( weights )
  ENDFOR

  IF dir EQ 'X' THEN   RETURN, image - back $
  ELSE RETURN, Transpose( image - back )

END ; MinEnvBack
