function sp_out = bin(wv_in, sp_in, wv_out, interp_method)
%	function bin(wv_in, sp_in, wv_out)

%	LAST MODIFIED:	July 14 / 00
%
%	ARGUMENTS:
%		wv_in		input wavelength grid, on which sp_in is binned
%		sp_in		input spectrum, binned on wv_in
%		wv_out	output wavelength grid
%		interp_method		string with interpolation method 
%								(use "help interp1" to see the options)
%	CALLS:			none
%
%	CALLED BY: 		resid.m
%
%	COMMENTS:
%		All that this function really does is call MatLab's interp1
%	function, but it adds a range check on the wv vectors. Using this
% 	function just makes the code in RESID.M much shorter and less
%	repetitive.

%	PROBLEM: cannot modify ref from within function. Makes range check useless.
%	fix? (July 14)

% Bandaid for interpolation falling of end of range:
while min(wv_in) > min(wv_out)
   [t1 tlow] = min(wv_out);
   wv_out(1:tlow) = [];
   %ref(1:t2) = [];
end
while max(wv_in) < max(wv_out)
   [t1 t2] = max(wv_out);
   wv_out(t2:length(wv_out)) = [];
   %ref(t2:length(wv_out)) = [];
end
% This ensures that the range of wv_in exceeds the range of wv_out. If
% the range of wv_out is greater than that of wv_in, the interpolating
% function (interp1) will produce NaN values at the ends of cal_sp, 
% resulting in an error when polyfit is called.

% Rebin sp onto the wavelength grid of sp:
sp_out = interp1(wv_in, sp_in, wv_out, interp_method);
