function [ax,hl,hr,rangel,datal,timel,ranger,datar,timer] = plotyy(varargin)
% plotyy  Line plot function with LHS and RHS axes for time series.
%
% Syntax
% =======
%
%     [ax,lhs,rhs,range] = plotyy(x,y,...)
%     [ax,lhs,rhs,range] = plotyy(range,x,y,...)
%
% Input arguments
% ================
%
% * `range` [ numeric ] - Date range; if not specified the entire range of
% the input tseries object will be plotted.
%
% * `x` [ tseries ] - Input tseries object whose columns will be plotted
% and labelled on the LHS.
%
% * `y` [ tseries ] - Input tseries object whose columns will be plotted
% and labelled on the RHS.
%
% Output arguments
% =================
%
% * `ax` [ numeric ] - Handles to the LHS and RHS axes.
%
% * `lhs` [ numeric ] - Handles to lines belonging to the LHS axis.
%
% * `rhs` [ numeric ] - Handles to lines belonging to the RHS axis.
%
% * `range` [ numeric ] - Actually plotted date range.
%
% Options
% ========
%
% * `'conincident='` [ `true` | *`false`* ] - Make the LHS and RHS y-axis grids
% coincident.
%
% * `'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.
%
% * `'freqLetters='` [ char | *'YHQBM'* ] - Five letters to represent the
% five date frequencies (yearly, half-yearly, quarterly, bi-monthly, and
% monthly).
%
% * `'lhsPlotFunc='` [ @area | @bar | *@plot* | @stem ] - Function that will
% be used to plot the LHS data.
%
% * `'lhsTight='` [ `true` | *`false`* ] - Make the LHS y-axis tight.
%
% * `'rhsPlotFunc='` [ @area | @bar | *@plot* | @stem ] - Function that will
% be used to plot the RHS data.
%
% * `'rhsTight='` [ `true` | *`false`* ] - Make the RHS y-axis tight.
%
% Description
% ============
%
% Example
% ========
%

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

% AREA, BAR, PLOT, CONBAR, PLOTCMP, PLOTYY, STEM

% Range for LHS time series.
if isnumeric(varargin{1})
    rangel = varargin{1};
    varargin(1) = [];
else
    rangel = Inf;
end

% LHS time series.
xl = varargin{1};
varargin(1) = [];

% Range for RHS time series.
if isnumeric(varargin{1})
    ranger = varargin{1};
    varargin(1) = [];
else
    ranger = rangel;
end

% RHS time series.
xr = varargin{1};
varargin(1) = [];

[opt,varargin] = passvalopt('tseries.plotyy',varargin{:});

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

% Check consistency of ranges and time series.
% LHS.
if ~all(isinf(rangel)) && ~isempty(rangel)
    if datfreq(rangel(1)) ~= get(xl,'freq')
        error('iris:tseries', ...
            'LHS range and LHS time series must have the same periodicity.');
    end
end
% RHS.
if ~all(isinf(ranger)) && ~isempty(ranger)
    if datfreq(ranger(1)) ~= get(xr,'freq')
        error('iris:tseries', ...
            'RHS range and RHS time series must have the same periodicity.');
    end
end

% Mimic plotting the RHS graph without creating axes object.
[ans,ranger,datar,timer,userranger,freqr] = ...
    tseries.gplot([],0,ranger,xr); %#ok<NOANS,ASGLU>

% Mimic plotting the LHS graph without creating axes object.
comprise = timer([1,end]);
[ans,rangel,datal,timel,userrangel,freql] = ...
    tseries.gplot([],0,{rangel,comprise},xl); %#ok<NOANS,ASGLU>

[ax,hl,hr] = plotyy(timel,datal,timer,datar, ...
    char(opt.lhsplotfunc),char(opt.rhsplotfunc));

% Apply line properties passed in by the user as optional arguments. Do it
% separately for `hl` and `hr` because they each can be different types.
if ~isempty(varargin)
    try %#ok<*TRYNC>
        set(hl,varargin{:});
    end
    try
        set(hr,varargin{:});
    end
end

setappdata(ax(1),'tseries',true);
setappdata(ax(1),'freq',freql);
setappdata(ax(2),'tseries',true);
setappdata(ax(2),'freq',freqr);

set(ax(2), ...
    'color','none', ...
    'box','off', ...
    'xticklabel','', ...
    'xtick',[]);

tseries.timeline(ax,timel,userrangel,freql,opt);

% For bkw compatibility only, not documented. Use of `highlight` outside
% `plotyy` is now safe.
if ~isempty(opt.highlight)
    highlight(ax(1),opt.highlight);
end

if opt.lhstight || opt.tight
    grfun.yaxistight(ax(1));
end

if opt.rhstight || opt.tight
    grfun.yaxistight(ax(2));
end

% Swap LHS and RHS axes in the list of current figure children.
parent = get(ax(1),'parent');
siblings = get(parent,'children');
lhspos = siblings == ax(1);
rhspos = siblings == ax(2);
siblings(lhspos) = ax(2);
siblings(rhspos) = ax(1);
set(parent,'children',siblings);
set(ax(2),'color',get(ax(1),'color'));
set(ax(1),'color','none');

if ~opt.coincident
    set(ax,'box','off','yTickMode','auto','layer','top');
    set(ax(2),'xAxisLocation','top','xTick',[],'xTickMode','manual');
end

end