Viewing contents of file '../idllib/ghrs/pro/calfos_median.pro'
function calfos_median,in,width,first,last
;+
;			CALFOS_MEDIAN
;
; FOS median filter routine
;
; CALLING SEQUENCE:
;	result = calfos_median(in,width,first,last)
;
; INPUTS:
;	in - input spectrum
;	width - filter width (if greater than the number of points
;		in the input spectrum the output spectrum will have
;		the average of the input spectrum at each point)
; OPTIONAL INPUTS:
;	first - vector of first data point in regions not to
;		be filtered.  If first(0)<0 then no regions will
;		be excluded in the filter.
;	last - vector of last data point in regions not to be
;		filtered
; OUTPUTS:
;	filtered spectrum is returned as the function result
;
; HISTORY:
;	version 1.0  D. Lindler  Jan 1990
;-
;--------------------------------------------------------------------
	if n_params(0) lt 3 then first = intarr(1)-1

	if width le 1 then return,in		;no filtering

	out = in				;set up output vector
	ns = n_elements(in)
	nregions = n_elements(first)

	if first(0) lt 0 then begin
		nregions = 0		;no exclude regions
	   end else begin
		sub = sort(first)
		sfirst = first(sub)	;sort into ascending order
		slast = last(sub)
	end

	width = fix(width)/2*2 + 1	;make sure width is odd
	hwidth = width/2
;
; loop on sections not excluded
;
	i1 = 0				;first point to process
	region = 0			;next region to exclude

next_region:
	if region lt nregions then i2 = sfirst(region)-1 else i2=ns-1

	np = i2-i1+1			;number of points in region to smooth
	if np gt 2 then begin		;at least one point to filter
		d = in(i1:i2)		;region to smooth
;
; loop on points
;
		for i=1,np-2 do begin
			hw = hwidth < i < (np-1-i)
			dd = d(i-hw:i+hw)
			dd = dd(sort(dd))
			out(i1+i) = dd(hw)
		endfor
	endif

	if i2 lt (ns-1) then begin		;not done?
;
; get next good region
;
		i1 = slast(region)+1
		region = region + 1
		goto,next_region
	endif
return,out
end