function legend_add(varargin)
% Adds a new legend entry to an existing legend.

% Copyright 2013 Levente Hunyadi

narginchk(2,3);
n = 1;

h = varargin{n};
validateattributes(h, {'numeric'}, {'real','scalar'}, n);
if ishandle(h) && strcmp('axes', get(h, 'Type'))
    ax = h;
    n = n + 1;
else
    ax = get(gcf,'CurrentAxes');
end

h = varargin{n};
validateattributes(h, {'numeric'}, {'real','scalar'}, n);
if ishandle(h) && (strcmp('line', get(h, 'Type')) || strcmp('hggroup', get(h, 'Type')))
    line = h;
    n = n + 1;
else
    error('legend:add','A line object expected.');
end

text = varargin{n};
validateattributes(text, {'char'}, {'nonempty','row'}, n);

% get handle of existing legend to add new entry to
h = legend(ax);
if isempty(h) 
    % if the figure has no legend, create a new legend
    legend(ax,'show');
    
    % do not use the automatically generated text strings
    handles = [];
    strings = {};
else
    % get object handles
    [~,~,handles,strings] = legend(ax);
end

% add object with new handle and new legend string to legend
legend(ax, [handles;line], strings{:}, text);