function p2 = bootstraptest(data1, data2, N)
%bootstrapTest(data1, data2, N)
%
%Statistical test for comparing the means in two data sets. See the manual
%at http://users.ics.aalto.fi/lijffijt/bootstraptest
% data1 = vector of normalised frequencies in data set 1
% data2 = vector of normalised frequencies in data set 2
% N = number of bootstrap repetitions
%
%This code is free to use for academic purposes. If you use this test,
%please cite the following paper: Jefrey Lijffijt, Terttu Nevalainen,
%Tanja Säily, Panagiotis Papapetrou, Kai Puolamäki, Heikki Mannila.
%/Forthcoming/. "Significance testing of word frequencies in corpora".

% Compute number of elements in the shortest vector
n1 = length(data1);
n2 = length(data2);
nmin = min(n1,n2);

% Compute (unnormalized) p1
pH = zeros(1,N);
parfor i = 1:N
    value1 = sum(data1(randi(n1,1,nmin))); %#ok<PFBNS>
    value2 = sum(data2(randi(n2,1,nmin))); %#ok<PFBNS>
    pH(i) = double(value1>value2) + 0.5*(value1 == value2);
end
p1 = sum(pH);

% Compute p2
p2 = (1+2*min(p1,N-p1))/(1+N);

end