function [D,phat,z,pvalue,CI]=binom1sample(x,n,p,alpha)
%  1-sample binomial test.
% [D,phat,z,pvalue,CI]=binom1sample(x,n,p,alpha)
% Input: Sample 1: x successes in n trials
%        p=expected proportion
%        alpha level for CI, optional, 95% if not specified
% Output: D=x/n-p;
%         phat= expected p value
%         z=test statistic
%         p value, 2-sided, for z statistic
%         CI (1-alpha) percentile for D;95% CI if alpha not specified.
% Written by E. Gallagher; Eugene.Gallagher@umb.edu
% Revised 11/21/10
D=x/n-p;
phat=x/n;
z=D/sqrt(phat*(1-phat)/n);

if z>=0
    pvalue=(1-normcdf(z));
else
    pvalue=normcdf(z);
end
if nargin<5;
    alpha=0.05;
end
% find 95% CI for the difference D
HalfCI=norminv(1-alpha/2)*sqrt(((x/n)*(1-x/n)/n));
CI=[D-HalfCI D+HalfCI];