function x = vertcat(varargin)
% vertcat  Vertical concatenation of tseries objects.
%
% Syntax
% =======
%
%     x = [x1;x2;...;xn]
%
% Input arguments
% ================
%
% * `x1`, ..., `xn` [ tseries ] - Input tseries objects that will be
% vertically concatenated; they all have to have the same size in 2nd and
% higher dimensions.
%
% Output arguments
% =================
%
% * `x` [ tseries ] - Output tseries object created by overlaying `x1` with
% `x2`, and so on.
%
% Description
% ============
%
% Example
% ========
%
%}


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

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

if length(varargin) == 1
    x = varargin{1};
    return
end

% Check classes and frequencies.
[inputs,ixtseries] = catcheck(varargin{:});
if any(~ixtseries)
    error('iris:tseries', ...
        ['Cannot vertically concatenate tseries objects ', ...
        'with non-tseries objects.']);
end

ninput = length(inputs);
x = inputs{1};
xsize = size(x.data);
x.data = x.data(:,:);

for i = 2 : ninput
    y = inputs{i};
    ysize = size(y.data);
    y.data = y.data(:,:);
    xsize2 = size(x.data,2);
    ysize2 = size(y.data,2);
    if xsize2 ~= ysize2
        if xsize2 == 1
            x.data = x.data(:,ones([1,ysize2]));
            xsize = ysize;
            %xsize2 = ysize2;
        elseif ysize2 == 1
            y.data = y.data(:,ones([1,xsize2]));
            y.Comment = y.Comment(1,ones([1,xsize2]));
            %ysize2 = xsize2;
        else
            error('iris:tseries', ...
                ['Sizes of vertically concatenated time series ', ...
                'must be consistent in 2nd and higher dimensions.']);
        end
    end
    startdate = min([x.start,y.start]);
    enddate = max([x.start+size(x.data,1)-1,y.start+size(y.data,1)-1]);
    range = startdate : enddate;
    xdata = rangedata(x,range);
    ydata = rangedata(y,range);
    index = ~isnan(ydata);
    xdata(index) = ydata(index);
    x.data = xdata;
    x.start = startdate;
end

x.data = reshape(x.data,[size(x.data,1),xsize(2:end)]);
x.Comment = y.Comment;
if ~isempty(x.data) && any(any(isnan(x.data([1,end],:))))
    x = mytrim(x);
end

end
