function ln = zeroline(varargin)
% zeroline  Add zero line if Y-axis limits include zero.
%
% Syntax
% =======
%
%     LN = zeroline(...)
%     LN = zeroline(AX,...)
%
% Input arguments
% ================
%
% * `AX` [ numeric ] - Handle to an axes object (graph) to which the zeroline
% will be added; if not specified the current axes will be used.
%
% Output arguments
% =================
%
% * `LN` [ numeric ] - Handle to the line ploted (line object).
%
% Options
% ========
%
% Any options valid for the standard `plot` function.
%
% Description
% ============
%
% Example
% ========
%

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

if isempty(varargin)
   h = gca();
else
   if isnumeric(varargin{1})
      h = varargin{1};
   else
      h = [varargin{1}{:}];
   end
   varargin(1) = [];
end

default = { ...
   'zero',0,@isnumericscalar, ...
};
[options,varargin] = passvalopt(default,varargin{:});

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

if strcmp(get(h,'type'),'figure')
   fg = h;
   h = [];
   for i = 1 : numel(fg)
      tmp = findobj(fg(i),'type','axes','parent',fg(i));
      h = [h,tmp(:)']; %#ok<AGROW>
   end
end

ln = nan(size(h));
for i = 1 : numel(h)
   ax = h(i);
   yLim = get(ax,'yLim');
   if yLim(1) < options.zero && yLim(2) > options.zero
      xlim = get(ax,'xlim');
      nextplot = get(ax,'nextPlot');
      set(ax,'nextPlot','add');
      ln(i) = plot(ax,xlim,options.zero*[1,1],'color',[0,0,0]);
      if ~isempty(varargin)
         set(ln(i),varargin{:});
      end
      
      % Move zero line to background right below the last line.
      ch = get(ax,'children');
      if length(ch) > 1
         set(ax,'children',ch([2:end,1]));
      end
      
      % Update zeroline x-data whenever the parent axes x-lims change.
      grfun.listener(ax,ln(i),'zeroline');
      
      set(ax,'nextPlot',nextplot);
   end
end
ln(isnan(ln)) = [];

% Tag the zeroline for `qstyle`.
set(ln,'tag','zeroline');

if ~isempty(ln)
   % Exclude zerolines from legend.
   grfun.excludefromlegend(ln);
end

end
