function f = beta(mu,sgm)
% beta  Create function proportional to log of beta distribution.
%
% Syntax
% =======
%
%     F = logdist.beta(MEAN,STD)
%
% Input arguments
% ================
%
% * `MEAN` [ numeric ] - Mean of the beta distribution.
%
% * `STD` [ numeric ] - Std dev of the beta distribution.
%
% Output arguments
% =================
%
% * `F` [ function_handle ] - Handle to a function returning a value that
% is proportional to the log of the beta density.
%
% Description
% ============
%
% See [help on the logdisk package](logdist/Contents) for details on
% using the function handle `F`.
%
% Example
% ========
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

a = (1-mu)*mu^2/sgm^2 - mu;
b = a*(1/mu - 1);
if a > 1 && b > 1
    mode = (a - 1)/(a + b - 2);
else
    mode = NaN;
end
f = @(x,varargin) xxbeta(x,a,b,mu,sgm,mode,varargin{:});

end

% Subfunctions.

%**************************************************************************
function y = xxbeta(x,a,b,mu,sgm,mode,varargin)

y = zeros(size(x));
index = x > 0 & x < 1;
x = x(index);
if isempty(varargin)
    y(index) = (a-1)*log(x) + (b-1)*log(1-x);
    y(~index) = -Inf;
    return
end

switch lower(varargin{1})
    case {'proper','pdf'}
        y(index) = x.^(a-1).*(1-x).^(b-1)/beta(a,b);
    case 'info'
        y(index) = -(b - 1)./(x - 1).^2 - (a - 1)./x.^2;
    case {'a','location'}
        y = a;
    case {'b','scale'}
        y = b;
    case 'mean'
        y = mu;
    case {'sigma','sgm','std'}
        y = sgm;
    case 'mode'
        y = mode;
    case 'name'
        y = 'beta';
    case 'draw'
        y = betarnd(a,b,varargin{2:end});
end

end
% xxbeta().