function plotFinalize(l, tRange, stateLevs, pctTol, pctRef)
%PLOTFINALIZE plot reference levels, legend, and release plot
%
% This function is for internal use only.
  function plotPctRefLevel(S, label, pct)

%   Copyright 2011-2013 The MathWorks, Inc.

    if ~isnan(pct)
      amp = diff(stateLevs) * [1 1];
      l = signal.internal.plotItem(l,['signal:internal:plotFinalize:' label], ...
                                   tRange, stateLevs(1) + pct * amp / 100, S);
    end
  end
  % Plot reference, state, and state boundary levels
  plotPctRefLevel('r:', 'LegendUpperStateUpperBound', 100+pctTol);
  plotPctRefLevel('k:', 'LegendUpperStateLevel',      100);
  plotPctRefLevel('r:', 'LegendUpperStateLowerBound', 100-pctTol);

  plotPctRefLevel('r--','LegendUpperReferenceLevel',  pctRef(3));
  plotPctRefLevel('k--','LegendMiddleReferenceLevel', pctRef(2));
  plotPctRefLevel('g--','LegendLowerReferenceLevel',  pctRef(1));

  plotPctRefLevel('g:', 'LegendLowerStateUpperBound', pctTol);
  plotPctRefLevel('k:', 'LegendLowerStateLevel',      0);
  plotPctRefLevel('g:', 'LegendLowerStateLowerBound',-pctTol);

  % Display legend  
  legend([l{2,:}],l(1,:),'Location','NorthEastOutside');
  
  % label axes
  xlabel(getString(message('signal:internal:plotFinalize:PlotLabelTime')));
  ylabel(getString(message('signal:internal:plotFinalize:PlotLabelLevel')));

  % let go of the plot
  hold off;    
end