function [chi2, pval] = mantelhaenszel(data)
%
%
% Input data is stacked matrix of k matrices of 2x2,
% a matrix (2k x 2).
% Output MH - value of Mantel Haenszel stat,
% PMH corresponding p-value.
% example of use: Berkeley Admission Data
% [chi2 pval]=mantelhaenszel([512 89; 313 19; 
% 353 17; 207 8;  120 202; 205 391;   138 131; 279 244; 
% 53 94; 138 299;   22 24; 351 317])
% -------------------------------------------------------------------------
%
dims = size(data);
k2 = dims(1); %k2 = 2*k, k = number of 2x2 matrices
xi=[]; meani=[]; vari=[];
for i = 1:2:k2
    twobytwoi = data( i:(i+1), : );
    xi=[xi   twobytwoi(1,1)];
    ri = twobytwoi(1,1)+twobytwoi(1,2);
    ci = twobytwoi(1,1)+twobytwoi(2,1);
    ni = sum(sum( twobytwoi ));
    meani =  [meani ri*ci/ni];
    vari = [vari   ri*ci*(ni-ri)*(ni-ci) /(ni^2 *(ni-1))  ];
end
chi2 = (abs(sum(xi) - sum(meani)) -1/2 )^2 /sum(vari);
pval =  1 - chi2cdf(chi2, 1);
% ver 0.1 Gatech 2003