function [chi2, pval] = stuartmaxwell( data )
% Example of use
%    eyes=[...
%            1520   266     124      66  ; ... 
%            234     1512     432      78  ;... 
%            117     362  1772     205 ; ...
%             36      82   179    492];
% stuartmaxwell (eyes)
%    %chi2 = 11.9566
%     %pval =0.0075
[k,l] = size(data);
if (k ~= l) 
     error('Data Matrix Needs to be Square') 
end
k1 = k-1;
ndoti = sum(data);
nidot = sum(data');
n=sum(sum(data));
di = ndoti - nidot;
di1 = di(1:k1);
for i = 1:k1
    for j = 1: k1
        if(i == j)
                 si(i,j) = nidot(i) + ndoti(i) - 2 * data(i,i); 
                 bsi(i,j) = (nidot(i) + ndoti(i) - 2 * data(i,i) - ...
                     (ndoti(i) - nidot(i))^2)/n;               
        else
            si(i,j) = -(data(i,j) + data(j,i));
            bsi(i,j)= (-(data(i,j) + data(j,i)) - ...
                  (ndoti(i) - nidot(i))*(ndoti(j)-nidot(j)))/n;
        end
    end
end
chi2 = di1 * inv(si) * di1' ;
bchi2 = n * di1 * inv(bsi) * di1';

pval = 1 - chi2cdf(chi2, k-1);

chi2/(1-chi2/n);