function str = convertCell2Str(chain,varNames)
% convertCell2Str Print the chain multiply permutation expression.
%
% chain is a vector cell array of 3-element vector indices
% describing the chain multiplication.
%
% varNames is an optional cell string array containing one
% string per variable name.  These variable names are used
% during construction of the MATLAB string expressions.
% If omitted, variable names are 'A', B', ...


% Author: D. Orofino
% Copyright 1984-2000 The MathWorks, Inc.
% $Revision: 1.4 $ $Date: 2000/05/02 13:52:56 $

% Ex:
%  {[4 5 -1] [3 -1 -2] [2 -2 -1] [1 -1 0]} % A * (B * (C*(D*E)))
%  {[3 4 -1] [-1 5 -2] [2 -2 -1] [1 -1 0]} % A * (B * ((C*D)*E))
%  {[2 3 -1] [-1 4 -2] [-2 5 -1] [1 -1 0]} % A * (((B*C)*D) * E)
%  {[3 4 -1] [2 -1 -2] [-2 5 -1] [1 -1 0]} % A * ((B*(C*D)) * E)
%  {[2 3 -1] [4 5 -2] [-1 -2 -3] [1 -3 0]} % A * ((B*C) * (D*E))

if nargin<2 | isempty(varNames),
    % Generate as many default variable names as required
    %
    % xxx Find max non-temporary (positive) index specified
    % across all input vectors:
	varNames = cellstr(char(double('A') + (0:25))');
end

str = '';
temp_strs = {};

for i=1:length(chain),
   x1_idx  = chain{i}(1);  % x1 matrix index
   x2_idx  = chain{i}(2);  % x2 matrix index
   
   if length(chain{i})==3,    % skip single-input case
      x12_idx = chain{i}(3);  % x12 result index
      
      % Get size vectors of x1 and x2
      % Each size vector specifies [rows cols]
      ch1 = getMatrixStr(x1_idx, temp_strs, varNames);
      ch2 = getMatrixStr(x2_idx, temp_strs, varNames);
      
      % Multiply these together:
      
      if x12_idx == 0,
         % Last operation:
         str = ['Y = ' ch1 '*' ch2 ';'];
      else
         temp_strs{-x12_idx} = ['(' ch1 '*' ch2 ')'];
      end
   else
      % 2-input case:
      ch1 = getMatrixStr(x1_idx, temp_strs, varNames);
      str = ['Y = ' ch1 ';'];
   end
end


% -----------------------------------------------------------
function x_str = getMatrixStr(x_idx, temp_strs, varNames)
% getMatrixStr Return string for i'th matrix chain operation
% temp_strs is a list of string expressions describing the
% contents of each generated temp.

if x_idx<0,
   % Get temporary-variable string expression:
   x_str = temp_strs{-x_idx};
   
elseif x_idx>0,
   % Return variable name of i'th input matrix
   % 1st = A, 2nd = B, etc.
   if x_idx>26,
      error('Too many input variables for prettyPrintVars.');
  end
   
   % Get name for x_idx'th variable:
   % x_str = char(double('A') + x_idx-1);
   x_str = varNames{x_idx};
   
else
   error(['Input index to matrix multiplier pair cannot be ' ...
         'specified as the output matrix (index 0).']);
end

% [EOF] convertCell2Str.m
