function [result,perm] = check_hurwitz(Ac)

%Checks Hurwitz condition for all column permutations
%
%   [result,perm] = check_hurwitz(Ac)  where
%         Ac - cell array with the A_j matrices in it
%     result - TRUE (all matrices are Hurwitz), FALSE if not
%       perm - indices of all the permutations of colums for
%              which the condition is violated
%

% Florian Knorn, florian@knorn.org, 14 April 2011

% Some error catching
if nargin ~= 1
	error('Please provide cell array with matrices');
end
if ~iscell(Ac)
	error('Please provide *cell* array with matrices');
end

% Initialisation
result = true;
N = length(Ac);
n = length(Ac{1});
perm = [];
maxrho = -1e10;
rhoperm = [];
sigmas = char(zeros(N^n,n));

% Generate permutations
for i = 1:length(sigmas) % count from 1 to N^n in base N
	sigmas(i,:) = dec2base(i-1,N,n);
end

% Convert strings generated by dec2base back to numbers
sigmas = abs(sigmas) - 47;                 % numbers
sigmas(sigmas>10) = sigmas(sigmas>10) - 7; % letters

% Iterate through permutations
for i = 1:length(sigmas)

	% create A_sigma for Hurwitz test
	A_sigma = zeros(n,n);
	for j = 1:n % columns
		temp = Ac{sigmas(i,j)};
		A_sigma(:,j) = temp(:,j);
	end
	
	% perform Hurwitz test
	rho = max(real(eig(A_sigma)));
	if rho > maxrho
		maxrho = rho;
		rhoperm = sigmas(i,:);
	end
	if max(real(eig(A_sigma)))>0
		result = false;
		perm = [perm;sigmas(i,:)];
	end
	
end