function [h,p,ci,zval] = ztest(x,m,sigma,alpha,tail)
%ZTEST  Hypothesis test: Compares the sample average to a constant.
%   [H,P,CI,ZVAL] = ZTEST(X,M,SIGMA,ALPHA,TAIL) performs a Z-test
%   to determine whether a sample from a normal distribution (in X)
%   could have mean M when the standard deviation, SIGMA, is known.
%   ALPHA = 0.05 and TAIL = 0 by default.
%
%   Null hypothesis is: "mean is equal to M".
%   For TAIL =  0, alternative: "mean is not M".
%   For TAIL =  1, alternative: "mean is greater than M."
%   For TAIL = -1, alternative: "mean is less than M."
%
%   ALPHA is the desired significance level. 
%   P is the p-value, or the probability of observing the given result
%     by chance given that the null hypothesis is true. Small values
%     of P cast doubt on the validity of the null hypothesis.
%   CI is a confidence interval for the true mean.  Its confidence
%     level is 1-ALPHA.
%   ZVAL is the test statistic.
%
%   H=0 => "Do not reject null hypothesis at significance level of alpha."
%   H=1 => "Reject null hypothesis at significance level of alpha."

%   References:
%      [1] E. Kreyszig, "Introductory Mathematical Statistics",
%      John Wiley, 1970, page 206. 

%   Copyright 1993-2000 The MathWorks, Inc. 
%   $Revision: 2.11 $  $Date: 2000/05/26 18:53:59 $

if nargin < 3, 
    error('Requires at least three input arguments.'); 
end

[m1 n1] = size(x);
if (m1 ~= 1 & n1 ~= 1) 
    error('First argument has to be a vector.');
end
x = x(~isnan(x));

if nargin < 5, 
    tail = 0; 
end 

if nargin < 4, 
    alpha = 0.05; 
end 

if (prod(size(alpha)>1)), error('ALPHA must be a scalar.'); end
if (alpha<=0 | alpha>=1), error('ALPHA must be between 0 and 1.'); end

samplesize  = length(x);
xmean = mean(x);
ser = sigma ./ sqrt(samplesize);
zval = (xmean - m) ./ ser;
p = normcdf(zval,0,1);

% the p-value just found is for the tail = -1 test
if (tail == 0)
    p = 2 * min(p, 1-p);
    crit = norminv(1 - alpha/2,0,1) .* ser;
    if (nargout>2), ci = [(xmean - crit) (xmean + crit)]; end
else
    crit = norminv(1 - alpha,0,1) .* ser;
    if tail == 1
        p = 1 - p;
        if (nargout>2), ci = [(xmean - crit), Inf]; end
    else
        if (nargout>2), ci = [-Inf, (xmean + crit)]; end
    end
end



% Determine if the actual significance exceeds the desired significance
h = 0;
if p <= alpha, 
    h = 1; 
end 

if isnan(p), 
    h = NaN; 
end
