function TernRot(theAxes, theRot)

% TernRot -- Rotate TernPlot data.
%  TernRot(theAxes, theRot) rotates the ternary plot in
%   theAxes by exchanging x-y-z for z-x-y (theRot = 3)
%   or x-y-z-w for w-x-y-z (theRot = 4).  If theRot is
%   'flip', the x and y data are exchanged.
 
% Copyright (C) 1996 Dr. Charles R. Denham, ZYDECO.
% All Rights Reserved.
 
% Version of 17-Sep-96 at 10:53:36.55.

if nargin < 1, theAxes = gca; end
if nargin < 2, theRot = 3; end

if isstr(theRot), theRot = lower(theRot); end

axes(theAxes)

h = findobj(theAxes, 'Type', 'line');

for i = 1:length(h)
   x = get(h(i), 'XData');
   y = get(h(i), 'YData');
   z = get(h(i), 'ZData');
   if isempty(z), z = 0 .* x + 0; end
   w = 1 - x - y - z;
   if theRot == 3
      temp = z; z = y; y = x; x = temp;
     elseif theRot == -3
      temp = x; x = y; y = z; z = temp;
     elseif theRot == 4
      temp = z; z = y; y = x; x = w; w = temp;
     elseif theRot == -4
      temp = x; x = y; y = z; z = w; w = temp;
     elseif strcmp(theRot, 'flip')
      temp = x; x = y; y = temp;
   end
   set(h(i), 'XData', x, 'YData', y, 'ZData', z)
end

theTitle = get(theAxes, 'Title');
theXLabel = get(theAxes, 'XLabel');
theYLabel = get(theAxes, 'YLabel');
theZLabel = get(theAxes, 'ZLabel');

theLabels = [theTitle, theXLabel, theYLabel, theZLabel];

h = findobj(gca, 'Type', 'text');
for i = 1:length(h)
   if ~any(h(i) == theLabels)
      pos = get(h(i), 'Position');
      x = pos(1); y = pos(2); z = pos(3);
      w = 1 - sum(pos);
      if theRot == 3
         pos = [z x y];
        elseif theRot == -3
         pos = [y z x];
        elseif theRot == 4
         pos = [w x y];
        elseif theRot == -4
         pos = [y z w];
        elseif strcmp(theRot, 'flip')
         pos = [y x z];
      end
      set(h(i), 'Position', pos)
   end
end
