function LabelLinePlots(LegendArray,h)
% Author ---> Software Techniques Inc. (www.stiwww.com)
% Syntax LabelLinePlots(LegendArray,h)
% LegendArray is a string array containing 1 label per row
% LegendArray can be created using the function makemat
% h is the handle to the graph using for example h = plot(x,y)

% h = findobj(gca,'Type','line'); % Finds all line objects in the current figure
c = get(h,'XData');
d = get(h,'YData');
% Top (100 - BottomSlopePercent) percent of the points with the highest slope are excluded for placement of labels
BottomSlopePercent = 80;
% EdgeProtectPercent can produce undesired results so it has been set to 0.
% However it can be changed to a non-zero value by the user
EdgeProtectPercent = 0; % Minimum percentage of the full scale to keep away from the axes
axis(axis*(1+1.2*EdgeProtectPercent/100));
XLimits = get(gca,'XLim');
YLimits = get(gca,'YLim');
XMin = XLimits(1);
XMax = XLimits(2);
YMin = YLimits(1);
YMax = YLimits(2);
LowerX = XMin * (1+EdgeProtectPercent/100);
UpperX = XMax * (1-EdgeProtectPercent/100);
LowerY = YMin * (1+EdgeProtectPercent/100);
UpperY = YMax * (1-EdgeProtectPercent/100);

if size(LegendArray,1) ~= size(c,1)
    return
end

for i = 1:size(c,1)
    if size(c,1) == 1
        Xvalues = c;
        Yvalues = d;
    else
        Xvalues = c{i};
        Yvalues = d{i};
    end
    % Restrict limits to those visible on the graph and protect the edges
    IndicesInView = find((Xvalues >= XMin) & (Xvalues <= XMax) & (Yvalues >= YMin) & (Yvalues <= YMax) & (Xvalues >= LowerX) & (Xvalues <= UpperX) & (Yvalues >= LowerY) & (Yvalues <= UpperY));
    if ~isempty(IndicesInView)
        YInView = Yvalues(IndicesInView);
        XInView = Xvalues(IndicesInView);
        [YDiffInView,YDiffInViewIndices] = sort(diff(YInView));
        YDiffInViewIndices = fliplr(YDiffInViewIndices);
        % Do not include the points in the top 
        OptimalYIndicesLength = floor(BottomSlopePercent/100*(length(YDiffInViewIndices)));
        OptimalYIndices = YDiffInViewIndices(1:OptimalYIndicesLength);
        % Exclude areas where slope is steep
        RandIndex = rchoose(OptimalYIndices,1);
        XLoc = XInView(RandIndex);
        YLoc = YInView(RandIndex);
        text(XLoc,YLoc,deblank(LegendArray(i,:)));
    end
end
