function [ab,bb,cb,m,T] = dbalreal(a,b,c)
%DBALREAL  Discrete balanced state-space realization and model reduction.
%	[Ab,Bb,Cb] = DBALREAL(A,B,C) returns a balanced state-space 
%	realization of the system (A,B,C).
%
%	[Ab,Bb,Cb,M,T] = DBALREAL(A,B,C) also returns a vector M 
%	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 M indicate states that can be
%	removed to reduce the model to lower order.
%
%	See also DMODRED, BALREAL and MODRED.

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

Gc = dgram(a,b);
Go = dgram(a',c');
R = chol(Gc);
% [V,D] = eig(R*Go*R');
% Fix because symmetric matrix does not have orthogonal eigenvalues
[u,D,V] = svd(R*Go*R');
D = D.*sign(u'*V);
T = R'*V*diag(diag(D).^(-.25));
ab = T\a*T;
bb = T\b;
cb = c*T;
if nargout > 3
	m = diag(dgram(ab,bb))';
end
