function hh = pie(x,varargin)
%PIE    Pie chart.
%   PIE(X) draws a pie plot of the data in the vector X.  The values in
%   X are normalized via X/SUM(X) to determine the area of each slice of
%   pie.  If SUM(X) <= 1.0, the values in X directly specify the area of
%   the pie slices.  Only a partial pie will be drawn if SUM(X) < 1.
%
%   H = PIE(X,EXPLODE) is used to specify slices that should be pulled
%   out from the pie.  The vector EXPLODE must be the same size as X.
%   The slices where EXPLODE is non-zero will be pulled out.
%
%   H = PIE(...,LABELS) is used to label each pie slice with cell
%   array LABELS.  LABELS must be the same size as X and can only contain
%   strings.
%
%   H = PIE(...) returns a vector containing patch and text handles.
%
%   Example
%      pie([2 4 3 5],{'North','South','East','West'})
%
%   See also PIE3.

%   Clay M. Thompson 3-3-94
%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.14 $  $Date: 2000/06/02 04:30:49 $

if nargin==0, error('Not enough input arguments.'); end
if nargin>3, error('Too many input arguments.'); end

x = x(:); % Make sure it is a vector
if sum(x) > 1+sqrt(eps), x = x/sum(x); end

% Look for labels
if nargin>1 & iscell(varargin{end})
  txtlabels = varargin{end};
  varargin(end) = [];
else
  for i=1:length(x)
    if x(i)<.01,
      txtlabels{i} = '< 1%';
    else
      txtlabels{i} = sprintf('%d%%',round(x(i)*100));
    end
  end
end

% Look for explode
if isempty(varargin),
   explode = zeros(size(x)); 
else
   explode = varargin{1};
end

explode = explode(:); % Make sure it is a vector

if length(txtlabels)~=0 & length(x)~=length(txtlabels),
  error('Cell array of strings must be the same length as X.');
end

if length(x) ~= length(explode),
  error('X and EXPLODE must be the same length.');
end

ax = newplot;
next = lower(get(ax,'NextPlot'));
hold_state = ishold;

theta0 = pi/2;
maxpts = 100;
inside = 0;

h = [];
for i=1:length(x)
  n = ceil(maxpts*x(i));
  r = [0;ones(n+1,1);0];
  theta = theta0 + [0;x(i)*(0:n)'/n;0]*2*pi;
  if inside,
    [xtext,ytext] = pol2cart(theta0 + x(i)*pi,.5);
  else
    [xtext,ytext] = pol2cart(theta0 + x(i)*pi,1.2);
  end
  [xx,yy] = pol2cart(theta,r);
  if explode(i),
    [xexplode,yexplode] = pol2cart(theta0 + x(i)*pi,.1);
    xtext = xtext + xexplode;
    ytext = ytext + yexplode;
    xx = xx + xexplode;
    yy = yy + yexplode;
  end
  theta0 = max(theta);
  h = [h,patch('XData',xx,'YData',yy,'CData',i*ones(size(xx)), ...
               'FaceColor','Flat'), ...
         text(xtext,ytext,txtlabels{i},...
              'HorizontalAlignment','center')];
end

if ~hold_state, 
  view(2); set(ax,'NextPlot',next); axis equal, axis off
  axis([-1.2 1.2 -1.2 1.2])
end

if nargout>0, hh = h; end
