function v = fillgaps(v, imeth, extrapol)
%  1.  NAME
%
%  fillgaps - Fill gaps within a vector
%
%  2.  SYNOPSIS
%
%  v = fillgaps(v, imeth, extrapol )
%
%  3.  DESCRIPTION
%
%  Gaps within a vector are NaN data. Data gaps inside the elements of
%  the vector are filled using interpolation function interp1, and the
%  method specified by imeth. If extrapolation is required, then gaps at
%  the beginning and end of the vector are filled with the nearest non-
%  NaN value.
%
%  4.  PARAMETERS
%
%     v  Data vector.
%
%     imeth
%        Interpolation method,as those used for interp1. If zero,then
%        default method linear is used.
%
%     extrapol
%        If non-zero then also extrapolate data at the vector extremi-
%        ties."
%
%  5.  RETURNS
%
%     v  Data vector with gaps filled.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Default method:
if ~imeth,
	imeth = 'linear';
end

%--- Transform v in a column vector:
transpose = 0;
if size(v,1) > size(v,2),
	v = v';
	transpose = 1;
end

%--- Interpolate gaps inside vector:
ig = find(~isnan(v));
ix = 1:length(v);
iv = v;
if length(ig) > 2,
	iv = interp1(ix(ig), v(ig), ix, imeth);
end

%--- Extrapolate gaps:
if extrapol,
	ib = find(isnan(iv));
	ig = find(~isnan(iv));
	if (length(ib) > 0) & (length(ig) > 0),
		for i=ib,
			if i < min(ig),
				iv(i) = iv(min(ig));
			elseif i > max(ig),
				iv(i) = iv(max(ig));
			end
		end
	end
end

%--- Reshape vector:
v = iv;
if transpose,
	v = iv';
end

return;

			
