
function [h pval] = fisherexactt(matr, alt, alpha)
%  [h pval] = fisherexactt(matr, alt, alpha)
% Input: matr -- matrix [a b; c d]
%             alternative -- '1' p1 > p2;  '0' p1 != p2; '-1'  p1 < p2
%             alpha -- significance level
%             default inputs: alternative '0' and alpha 0.05.
%  Output:  h  -- 0 if H0 is not rejected, 1 if H0 is rejected
%             pval - pvalue for the test against alternative
%   Example of Use
%            There are 22 subjects in a clinical trial and 9 are females.
%            There are 11 portions of drug and 11 placebos. Only
%            2 females received drug.
%            Are the proportions of males and females assigned to
%            a drug (statistically) equal? That is, is the assignment of
%            drug homogeneous wrt gender?
%
%            [u v]=fisherexactt([2 7 ; 9 4],'-1')
%            H0: p1=p2 vs H1: p1 < p2
%            u = 1
%            v = 0.0402
%     Reject H0; the assignment of drugs significantly 
%    violates homogeneity, p1 < p2

if nargin < 3
    alpha = 0.05;
end
if nargin < 2
    alt  = '0' ;
end
a = matr(1,1); b = matr(1,2); c = matr(2,1); d =matr(2,2);
n=a + b + c + d;
T = a;
       switch alt 
           case  '-1' 
            disp('H0: p1=p2 vs H1: p1 < p2')
            pval = hygecdf(T,n,a+c,a+b);   
            h= (pval < alpha);
          case '1'
            disp('H0: p1=p2 vs H1: p1 < p2')
            pval = 1-hygecdf(T-1,n,a+c,a+b);   
            h= (pval < alpha); 
           case '0'
            disp('H0: p1=p2 vs H1: p1 =/= p2')
             pa = hygepdf(T,n,a+c,a+b);
                              for  i = 1:min(a+b, a+c)+1
                                        p(i) = hygepdf(i-1,n,a+c,a+b) ;
                              end
             pval  = sum(p(p <= pa));
             h= (pval < alpha);
           otherwise
            disp('Error: alternative is one of -1, 0, or 1')
        end
 

 