Viewing contents of file '../idllib/ghrs/pro/calfos_mean.pro'
function calfos_mean,in,width,first,last
;+
;			CALFOS_MEAN
;
; Mean filter routine
;
; CALLING SEQUENCE:
;	result = calfos_mean(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 returned as 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

	ns = n_elements(in)
;
; case where average of input vector is used
;
	out = in				;set up output vector
	if width ge ns then begin
		ave = total(in)/ns
		out(*) = ave
		return,out
	end

	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 needs filtered value
		d = in(i1:i2)		;region to smooth
;
; compute smoothed value for points that can use full filter width
;
		if np gt width then dout = smooth(d,width) else dout = d
;
; shrink filters near edges
;
		if (width gt 3) and (np gt 1) then begin
		    for i=1 , (hwidth-1) < ((np-1)/2) do begin
			shrink_width = i*2+1
			dout(i) = total(d(0:shrink_width-1))/shrink_width
			dout(np-i-1) = total(d(np-shrink_width:np-1)) $
						/shrink_width
		    endfor
		endif
		out(i1) = dout
	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