function [h1,h2,range,data,grid] = plotpred(varargin)
% plotpred  Plot Kalman filter predictions.
%
% Syntax
% =======
%
%     [H1,H2] = plotpred([X,Y],...)
%     [H1,H2] = plotpred(AX,[X,Y],...)
%     [H1,H2] = plotpred(AX,RANGE,[X,Y],...)
%
% Input arguments
% ================
%
% * `X` [ tseries ] - Input data with time series observations.
%
% * `Y` [ tseries ] - Input data with predictions calculated in a Kalman
% filter run with an `'ahead='` option.
%
% * `AX` [ numeric ] - Handle to axes object in which the data will be
% plotted.
%
% * `RANGE` [ numeric | Inf ] - Date range on which the input data will be
% plotted.
%
% Output arguments
% =================
%
% * `H1` [ numeric ] - Handle to a line object showing the time series
% observations.
%
% * `H2` [ numeric ] - Handle to line objects showing the Kalman filter
% predictions.
%
% Options
% ========
%
% See help on [`plot`](tseries/plot) and on the built-in function
% `plot` for options available.
%
% Description
% ============
%
% Example
% ========
%

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

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

if isempty(varargin)
    return
end

% Handle to axes object.
if isnumericscalar(varargin{1}) && ishandle(varargin{1})
    ax = varargin{1};
    varargin(1) = [];
else
    ax = gca();
end

% Range.
if isnumeric(varargin{1})
    range = varargin{1};
    varargin(1) = [];
else
    range = Inf;
end

% Input data.
x1 = varargin{1};
varargin(1) = [];
if ~isempty(varargin) && isa(varargin{1},'tseries')
    % Old syntax plotpred(X,Y).
    x2 = varargin{1};
    varargin(1) = [];
else
    % Standard syntax plotpred([X,Y]).
    x2 = x1;
    x2.data = x2.data(:,2:end);
    x1.data = x1.data(:,1);
end

[data,range] = rangedata([x1,x2],range);
nper = size(data,1);
ahead = size(data,2);
data = [data;nan(ahead-1,ahead)];

data2 = nan(nper+ahead-1,nper);
for t = 1 : nper
    data2(t+(0:ahead-1),t,:) = diag(data(t+(0:ahead-1),:));
end

x2 = replace(x2,data2(1:nper,:),range(1));
[h1,ans,data1] = plot(ax,range,x1,varargin{:}); %#ok<NOANS,ASGLU>
hold('all');
[h2,ans,data2,grid] = plot(ax,range,x2,varargin{:}); %#ok<NOANS,ASGLU>
set(h2,'tag','plotpred');
hold('off');

if ~isempty(h1) && ~isempty(h2)
    %set(h1,'linewidth',get(h2(1),'linewidth')*3);
    set(h2,'linestyle','--');
end

data = [data1,data2];

end