function M = fillends(M, varargin)
     % M = fillends(M, varargin);
%% for use with vectors that were tabled too far out
%
% M was tabled, dir (optional) indicates which direction to fill.  
% varargin: name                 default                what
%           dir               longest dimension     direction to fill
%                                              'col' (fill down columns)
%                                              (eg. if interpolated in depth) 
%                                              'row' (fill across rows)
%                                              (eg. if interpolated in time)
%           fill                  1             interpolate NaNs in center
%
% eg. newtemp = fillends(tabled_temp)
% eg. to fill vertically (as in velocity with holes):
%     newvel = fillends(holey_vel, 'dir', 'col' );

   
% work with it as Nx1 vectors


cfg.fill = 1;
cfg.dir = [];

cfg = fillstruct(cfg, varargin, 0);

[row, col]=size(M);
if (isempty(cfg.dir) & (col > row)) | strcmp(cfg.dir, 'row')  
   M=M.';
   switched = 1;
else
   switched = 0;
end


% it is a single column vector.
% this is the engine
if (length(M(1,:)) == 1)
%fprintf('running engine\n')
   nanmask = isnan(M);

   % return if all NaNs or no NaNs
   if (sum(nanmask) == length(M)) | ...
          (sum(nanmask)==0);
      return
   end

   % do the top
   if isnan(M(1))
      endi = find(diff(nanmask) < 0);
      endi = endi(1);
      M(1:endi) = M(endi+1);
      nanmask(1:endi) = 0;
   end

   %do the bottom
   if isnan(M(end))
      M = flipud(M);
      nanmask = flipud(nanmask);
      
      endi = find(diff(nanmask) < 0);
      endi = endi(1);
      
      M(1:endi) = M(endi+1);
      nanmask(1:endi) = 0;
      
      M = flipud(M);
      nanmask = flipud(nanmask);
   end

   %do the middles
   if cfg.fill
      if sum(nanmask > 0) %there are nans in the middle
         bins = cumsum(ones(size(nanmask)));
         M = table1([ bins(~nanmask) M(~nanmask)], bins);
      end
   end
else
   for coli = 1:length(M(1,:))
      %fprintf('coli = %d, calling engine\n', coli);
      M(:,coli) = fillends(M(:,coli), 'fill', cfg.fill);
   end
end


if (switched)
   M=M.';
end




