function logz = lognormcdf(x,tail)
%LOGNORMCDF Log of the standard normal CDF.
%   LOGZ=LOGNORMCDF(X,-1) returns log of the standard normal CDF.
%
%   LOGZ=LOGNORMCDF(X,1) returns log of the upper tail of the standard
%   normal CDF.
%
%   See also normcdf, erfc.

flower = @(x) -x.^2/2 + log(erfcx(abs(x)/sqrt(2))) - log(2); 

fupper = @(x) log1p( -erfc(abs(x)/sqrt(2))/2 );

logz = zeros(size(x));

lower = x*tail > 0;
upper = ~lower;

logz(lower) = flower(x(lower));
logz(upper) = fupper(x(upper));

end
