function [p2tailed,exact,zval]=onesamplebinom(n,k,po,usebinomial);
% format[pvalue,exact,zval]=onesamplebinom(n,k,po,usebinomial);
% Input n=number of cases
%       k=number of successes
%       po=expected proportion
%       usebinomial=1 for exact test [optional]
% Output: p2tailed  2-tailed p value
%         exact     1 if Exact binomial test used
%         zval = z statistic
% calls Bernoull.m demoivre.m
% Reference: Larsen & Marx (2006, p. 440) Theorem 6.3.1
% Uses bernoull.m
if nargin<4 | usebinomial==0
    usebernoull=logical(0);
else
    usebernoull=logical(1);
    exact=1;
end
if ~usebernoull
%     OUT=demoivre(n,po); % Old test, no longer used
    % Equation 6.3.1 in L&M 4th edition p. 631
   if 0 < n*po-3*sqrt(n*po*(1-po)) & n*po-3*sqrt(n*po*(1-po)) < ...
    n*po +3*sqrt(n*po*(1-po)) & n*po +3*sqrt(n*po*(1-po)) < n;  
        fprintf('Passed the test for the normal approximation\n')
        exact=logical(0); 
    else
        fprintf('Failed test for normal approximation, Must use the binomial test\n')
        exact=logical(1);
    end
end
Expected=n*po;
Varpo=po*(1-po);
zval=(k-Expected)/sqrt(n*Varpo);
if exact
    Expectedk=n*po;
    dev=abs(Expectedk-k);
    if Expectedk>=k
        i=0:k;
        lowertailp=sum(binopdf(i,n,po));
        i=ceil(Expectedk+dev):n;
        uppertailp=sum(binopdf(i,n,po));
        p2tailed=lowertailp+uppertailp;
    else
        i=k:n;
        uppertailp=sum(binopdf(i,n,po));
        i=0:floor(Expectedk-dev);
        lowertailp=sum(binopdf(i,n,po));
        p2tailed=lowertailp+uppertailp;
    end
else
    if zval<0
         p2tailed=2*(normcdf(zval));
    elseif zval>=0
        p2tailed=2*(1-normcdf(zval));
    end
end