function x = cat(n,varargin)
% cat  Tseries object concatenation along n-th dimension.
%
% Backend IRIS function.
% No help provided.

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

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

if length(varargin) == 1
   % Matlab calls horzcat(x) first for [x;y].
   x = varargin{1};
   return
end

% Check classes and frequencies.
[inputs,ixtseries] = catcheck(varargin{:});

% Remove inputs with zero size in all higher dimensions.
% Remove empty numeric arrays.
remove = false(size(inputs));
for i = 1 : length(inputs)
   si = size(inputs{i});
   if all(si(2:end) == 0), remove(i) = true;
   elseif isnumeric(inputs{i}) && isempty(inputs{i}), remove(i) = true;
   end
end
inputs(remove) = [];
ixtseries(remove) = [];

if isempty(inputs)
   x = tseries([],[]);
   return
end

ninput = length(inputs);
% Find earliest startdate and latest enddate.
start = nan([1,ninput]);
finish = nan([1,ninput]);
for i = find(ixtseries)
   start(i) = inputs{i}.start;
   finish(i) = start(i) + size(inputs{i}.data,1) - 1;
end

% Find startdates and enddates.
minstart = min(start(~isnan(start)));
maxfinish = max(finish(~isnan(finish)));
start(~ixtseries) = -Inf;
finish(~ixtseries) = Inf;

% Expand data with pre- or post-sample NaNs.
if ~isempty(minstart)
   for i = find(start > minstart | finish < maxfinish)
      dim = size(inputs{i}.data);
      if isnan(inputs{i}.start)
         inputs{i}.data = nan([round(maxfinish-minstart+1),dim(2:end)]);
      else
         inputs{i}.data = [nan([round(start(i)-minstart),dim(2:end)]);inputs{i}.data;nan([round(maxfinish-finish(i)),dim(2:end)])];
      end
   end
   for i = find(isnan(start))
      dim = size(inputs{i}.data);
      inputs{i}.data = nan([maxfinish-minstart+1,dim(2:end)]);
   end
   nper = maxfinish - minstart + 1;
else
   nper = 0;
end

% Struct for resulting tseries.
x = tseries();
if ~isempty(minstart)
   x.start = minstart;
else
   x.start = NaN;
end

% Concatenate individual inputs.
empty = true;
for i = 1 : ninput
   if ixtseries(i)
      if empty
         x.data = inputs{i}.data;
         x.Comment = inputs{i}.Comment;
         empty = false;
      else
         x.data = cat(n,x.data,inputs{i}.data);
         x.Comment = cat(n,x.Comment,inputs{i}.Comment);
      end
   else
      data = inputs{i};
      si = size(data);
      if si(1) < nper
         data = data(:,:);
         data = [data;data(ones([1,nper-si(1)])*end,:)];
         data = reshape(data,[nper,si(2:end)]);
      end
      comment = cell([1,si(2:end)]);
      comment(:) = {''};
      if empty
         x.data = data;
         x.Comment = comment;
         empty = false;
      else
         x.data = cat(n,x.data,data);
         x.Comment = cat(n,x.Comment,comment);
      end
   end
end

end
