function [h chi2 pval stats] = mcnemart(matr, alpha)
%McNemar Test
% Use
% [h chi2 pval stats] = mcnemart(matr, alpha)
% Input:    matr is 2x2 table matrix [A B; C D].
%                alpha - significance level, 1-alpha confidence level
% Output: h=0/1 (null/alternative), chi2= chi^2 statistic;
%               pval = p-value; stats - structure consisting of
%               various estimators of risk and confidence intervals.

if  nargin==1, alpha=0.05 ; end   

A=matr(1,1); B= matr(1,2); C= matr(2,1); D=matr(2,2);
% If any entry is 0, add 0.5 to all cells
if( A*B*C*D==0 )
    matr = matr + 0.5;
end
N = A + B + C + D;   stats.N =N;
%TEST

chi2 = (B-C)^2/(B+C);
pval = 1- chi2cdf(chi2, 1);
h = chi2 > chi2inv(1-alpha, 1);

p1 = (A + B)/N; stats.p1=p1;%prob row 
p2 = (A + C)/N; stats.p2=p2;%prob column

p11 = A/N;
p12 = B/N; 
p21 = C/N; 
p22 = D/N;

% risk difference 
stats.diffp1p2 = p1 - p2;
   delta = p11*p22 - p12*p21;
s = sqrt( p1*(1-p1)/N + p2*(1-p2)/N + 2*delta/N );
ssel = sqrt( ((B+C)*N  - (B-C)^2)/N^3 );
   lbd =  p1 - p2 - norminv(1-alpha/2)*s;
   ubd = p1 - p2 + norminv(1-alpha/2)*s;
stats.diffint = [lbd, ubd]; 
% risk ratio
stats.rr = (A+B)/(A+C);
varlrr = 1/(A+B) + 1/(A+C) - 2*A/((A+B)*(A+C));
    lblrr = log((A+B)/(A+C)) - norminv(1-alpha/2)*sqrt(varlrr) ;
   ublrr = log((A+B)/(A+C)) + norminv(1-alpha/2)*sqrt(varlrr) ;
stats.rrlint = [lblrr, ublrr];
stats.rriint = [exp(lblrr), exp(ublrr)];
% odds ratio
stats.or1 = B/C;
% miettinen approx
s2lor1 = (log(B/C))^2 * (B+C)/((abs(B-C)-1)^2 + 0.0000001);
slor1 = sqrt(s2lor1);
    lblor1 = log(B/C) - norminv(1-alpha/2)*slor1 ;
    ublor1 = log(B/C) + norminv(1-alpha/2)*slor1 ;
stats.miettlint = [lblor1, ublor1];
stats.miettint = [exp(lblor1), exp(ublor1)];

% RGB approx
slor2 = sqrt(1/B + 1/C);
lblor2 = log(B/C) - norminv(1-alpha/2)*slor2 ;
ublor2 = log(B/C) + norminv(1-alpha/2)*slor2 ;
rgblint = [lblor2, ublor2];
stats.rgbint = [exp(lblor2), exp(ublor2)];
% --------- exact method ------------------
 df1l = 2*C +2; df2l = 2*B;
 F1 = finv(1-alpha/2, df1l, df2l);
 tl = B/(B+(C+1)*F1 );
 orexactl = tl/(1-tl);
 
 df1u = 2*B +2; df2u = 2*C;
 F2 = finv(1-alpha/2, df1u, df2u);
 tu = (B+1)*F2/(C+(B+1)*F2 );
 orexactu = tu/(1-tu);
 stats.exactorci = [orexactl, orexactu];

%--------- approximate prob ---------
phat = B/(B+C);
pl = phat - norminv(1-alpha/2)*sqrt(phat * (1-phat)/(B+C)) - 1/(2*B+2*C);
pu = phat + norminv(1-alpha/2)*sqrt(phat * (1-phat)/(B+C)) + 1/(2*B+2*C);
stats.intor = [pl/(1-pl), pu/(1-pu)];

