function [ab,bb,cb,g,t] = balreal(a,b,c)
%BALREAL  Balanced state-space realization and model reduction.
%	[Ab,Bb,Cb] = BALREAL(A,B,C) returns a balanced state-space 
%	realization of the system (A,B,C).
%
%	[Ab,Bb,Cb,G,T] = BALREAL(A,B,C) also returns a vector G containing
%	the diagonal of the gramian of the balanced realization, and 
%	matrix T, the similarity transformation used to convert (A,B,C) 
%	to (Ab,Bb,Cb).  If the system (A,B,C) is normalized properly, 
%	small elements in gramian G indicate states that can be removed to
%	reduce the model to lower order.

%	J.N. Little 3-6-86
%	Revised 12-30-88
%	Copyright (c) 1986-93 by the MathWorks, Inc.

%	See:
%	 1) Moore, B., Principal Component Analysis in Linear Systems:
%	    Controllability, Observability, and Model Reduction, IEEE 
%	    Transactions on Automatic Control, 26-1, Feb. 1981.
%	 2) Laub, A., "Computation of Balancing Transformations", Proc. JACC
%	    Vol.1, paper FA8-E, 1980.

gc = gram(a,b);
go = gram(a',c');
r = chol(gc);
rgr = r*go*r';
rgr = tril(rgr) + tril(rgr,-1)';  % Make rgr exactly symmetric.
[v,d] = eig(rgr);
t = r'*v*diag(diag(d).^(-.25));
ab = t\a*t;
bb = t\b;
cb = c*t;
g = diag(gram(ab,bb))';

% Sort so g is in descending order
[gg,i]=sort(g);
i = i(length(g):-1:1);
ab = ab(i,i);
bb = bb(i,:);
cb = cb(:,i);
t = t(:,i);
g = g(i);
