function x = bsxfun(fun,x,y)
% bsxfunc  Standard BSXFUN implemented for tseries objects.
%
% Syntax
% =======
%
%     Z = bsxfun(FUNC,X,Y)
%
% Input arguments
% ================
%
% * `FUNC` [ function_handle ] - Function that will be applied to the input
% series, `FUN(X,Y)`.
%
% * `X` [ tseries | numeric ] - Input time series or numeric array.
%
% * `Y` [ tseries | numeric ] - Input time series or numeric array.
%
% Output arguments
% =================
%
% * `Z` [ tseries ] - Result of `FUNC(X,Y)` with `X` and/or `Y` expanded
% properly in singleton dimensions.
%
% Description
% ============
%
% See help on built-in `bsxfun` for more help.
%
% Example
% ========
%
% We create a multivariate time series and subtract mean from its
% individual columns.
%
%     x = tseries(1:10,rand(10,4));
%     xx = bsxfun(@minus,x,mean(x));
%

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

% Validate input arguments.
inp = inputParser();
inp.addRequired('fun',@(x) isa(x,'function_handle'));
inp.addRequired('x',@(x) isa(x,'tseries') || isnumeric(x));
inp.addRequired('y',@(x) isa(x,'tseries') || isnumeric(x));
inp.parse(fun,x,y);

%**************************************************************************

if isa(x,'tseries') && isa(y,'tseries')
    range = min(x.start,y.start) : ...
        max(x.start+size(x.data,1),y.start+size(y.data,1))-1;
    data1 = rangedata(x,range);
    data2 = rangedata(y,range);
    nper = length(range);
    co = [];
    start = range(1);
elseif isa(x,'tseries')
    data1 = x.data;
    data2 = y;
    nper = size(x.data,1);
    co = x.Comment;
    start = x.start;
else
    data1 = x;
    data2 = y.data;
    nper = size(y.data,1);
    co = y.Comment;
    start = y.start;
end

data = bsxfun(fun,data1,data2);

if size(data,1) ~= nper
    utils.error('tseries', ...
        ['Result of BSXFUN must preserve ', ...
        'the size of the input tseries in 1st dimension.']);
end

x = replace(x,data,start,co);

end