function [md, ds, dq] = meandiffpermutation(x, y, nperm, alpha)
% Permutation test for difference of means of two independent samples.
%
% [md, ds, dq] = meandiffpermutation(x, y, nperm, alpha);
%
% Arguments:
%   x: vector with the samples of the x data set.
%   y: vector with the samples of the y data set.
%   nperm: number of permutations run.
%   alpha: significance level.
%
% Returns:
%   md: difference of the means 
%   ds: vector containing the differences of the means of the resampled data sets
%   dq: difference of the means at a significance of alpha.

  md = mean(x) - mean(y);             % measured difference
  xy = [x; y];                        % merge data sets
  % permutations:
  ds = zeros(nperm, 1);
  for i = 1:nperm
      xyr = xy(randperm(length(xy))); % shuffle xy
      xr = xyr(1:length(x));          % random x sample
      yr = xyr(length(x)+1:end);      % random y sample
      ds(i) = mean(xr) - mean(yr);
  end
  % significance:
  dq = quantile(ds, 1.0 - alpha);
end