function theLines = TernPlot(x, y, z, c)

% TernPlot -- Ternary Plot.
%  TernPlot(x, y, 'c') draws a ternary plot of the
%   three variables (x, y, z) in the current figure,
%   where z = 1-x-y.  'c' is the color.  The handles
%   of the plotted line-objects are returned.
%  TernPlot(x, y, z, 'c') draws a tetrahedral plot of
%   (x, y, z, w), where d = (1-x-y-z).
%  TernPlot(x, 'c') plots the two or three columns of x.
%  TernPlot (no argument) demonstrates itself.  Same
%   as TernPlot('demo').
 
% Copyright (C) 1996 Dr. Charles R. Denham, ZYDECO.
% All Rights Reserved.
 
% Version of 11-Sep-96 at 17:03:03.989.

if nargin < 1, x = 'demo'; end

if nargin == 3
   if isstr(z)
      c = z; z = [];
     else
      c = 'o';
   end
  elseif nargin == 2
   if isstr(y)
      c = y; y = []; z = [];
     else
      c = 'o';
   end
  elseif nargin == 1
   c = 'o'; y = []; z = [];
end

if strcmp(x, 'demo')
   help TernPlot, 
   figure('Name', 'TernPlot Demo');
   x = 10; y = 4; c = 'o';
   hold off
   TernBox(gca, y, '-y');
   TernView(gca)
   TernAxes(gca)
   hold on
   TernTics(gca, y, '-y');
   TernPlot(x, y, c)
   TernText('x', 'Albite')
   TernText('y', 'Diopside')
   TernText('z', 'Hypersthene')
   if y ==  4
      TernText('w', 'Anorthite')
   end
   hold off
%   Begets('TernPlot', 1, '''demo''', 'See Plot')
   return
end

if isempty(x), return, end

if length(x) == 1
   m = x;
   n = 3;
   if length(y) == 1, n = y; end
   nDimensions = n;
   x = rand(m, n);
   s = sum(x.').' * ones(1, n);
   x = x ./ s;
   x = x(:, 1:n-1);
   h = TernPlot(x, c);
   if nargout > 0, theLines = h; end
   return
end

if isempty(y)
   [m, n] = size(x);
   if n > 2
      z = x(:, 3);
   end
   y = x(:, 2);
   x = x(:, 1);
end

[x, y, z, w] = TernMap(x, y, z);

h = plot3(x, y, z, c);

theOldUnits = get(gca, 'Units');
set(gca, 'Units', 'pixels')
pos = get(gca, 'Position');
dx = pos(3);
dy = pos(4);
pos(3) = min(dx, dy);
pos(4) = min(dx, dy);
if (0)
   set(gca, 'Position', pos)
end
set(gca, 'Units', theOldUnits)

figure(gcf)

if nargout > 0, theLines = h; end
