function [ax,li] = spy(varargin)
% spy  Visualise tseries observations that pass a test.
%
% Syntax
% =======
%
%     [AA,LL] = spy(X,...)
%     [AA,LL] = spy(RANGE,X,...)
%
% Input arguments
% ================
%
% * `X` [ tseries ] - Input tseries object whose non-NaN observations will
% be plotted as markers.
%
% * `RANGE` [ tseries ] - Date range on which the tseries observations will
% be visualised; if not specified the entire available range will be used.
%
% Output arguments
% =================
%
% * `AA` [ tseries ] - Handle to the axes created.
%
% * `LL` [ tseries ] - Handle to the marks plotted.
%
% Options
% ========
%
% * `'dateformat='` [ char | *irisget('plotdateformat')* ] - Date format for
% the tick marks on the x-axis.
%
% * `'datetick='` [ numeric | *`Inf`* ] - Vector of dates locating tick marks
% on the x-axis; Inf means they will be created automatically.
%
% * `'names='` [ cellstr ] - Names that will be used to annotate individual
% columns of the input tseries object.
%
% * `'test='` [ function_handle | *@(x)~isnan(x)* ] - Test applied to each
% observations; only the values returning a true will be displayed.
%
% Description
% ============
%
% Example
% ========
%

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

if all(ishghandle(varargin{1})) ...
        && strcmpi(get(varargin{1}(1),'type'),'axes')
    ax = varargin{1}(1);
    varargin(1) = [];
else
    ax = gca();
end

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

X = varargin{1};
varargin(1) = [];

% Parse input arguments.
P = inputParser();
P.addRequired('range',@isnumeric);
P.addRequired('x',@(x) isa(x,'tseries'));
P.parse(range,X);

% Parse options.
[options,varargin] = passvalopt('tseries.spy',varargin{:});
freq = get(X,'freq');

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

[x,range] = rangedata(X,range);
x = x(:,:,1);
x = options.test(x.');
if ~islogical(x)
    x = logical(x);
end
time = dat2grid(range);
xcoor = repmat(1 : size(x,2),size(x,1),1);
xcoor = time(xcoor);
ycoor = repmat(1 : size(x,1),1,size(x,2));
li = plot(ax,xcoor(x),ycoor(x),'lineStyle','none','marker','.');
set(gca(),'YDir','reverse','yLim',[0,size(x,1)+1]);
tseries.timeline(ax,time,range,freq,options);

set(ax,'gridLineStyle',':');
yLim = [1,size(x,1)];
if ~isempty(options.names)
    set(ax,'yTick',yLim(1):yLim(end),'yTickMode','manual', ...
        'yTickLabel',options.names,'yTickLabelMode','manual', ...
        'yLim',[0.5,yLim(end)+0.5],'yLimMode','manual');
else
    yTick = get(ax,'yTick');
    yTick(yTick < 1) = [];
    yTick(yTick > size(x,1)) = [];
    set(ax,'yTick',yTick,'yTickMode','manual');
end

xlabel('');
setappdata(ax,'tseries',true);
setappdata(ax,'freq',freq);
set(li,varargin{:});

end