% FUNCTION Y = RUNNING_MEAN(X, MEAN_WIN)
%
% X: vector of data
% MEAN_WIN: odd integer
%
% Y: vector of same size as X
%
% by Guillaume LATHOUD at IDIAP (lathoud@idiap.ch)

function y = running_mean(x, mean_win)

if mod(mean_win, 2) < 1
  error('running_mean needs an odd window size');
end

if mean_win < 2
  y = x;
  return;
end

half_win = floor((mean_win-1) / 2);

% Mirror signal at borders
aux = x(:);
aux = [aux((1+half_win):-1:2); aux; aux((end-1):-1:(end-half_win))];

% shift it in both directions
for a = 1:half_win
  zz = zeros(a,1);
  aux(:,end+1) = [aux((1+a):end, 1); zz];
  aux(:,end+1) = [zz; aux(1:(end-a), 1)];
end

% Mean
y = nanmean(aux .') .';

% Remove mirrored samples
y = y((1+half_win):(end-half_win));
if size(x,2) > 1
  y = y';
end
