function [At,Bt,Atmin,Btmin,o,Hd] = ss2essm(a,b,d,e,L,J,Enull);
% [At,Bt,Atmin,Btmin,o,Hd] = ss2essm(a,b,d,e,L,J,Enull);


[m,n]=size(d); [n,r]=size(b);

if nargin == 6; Enull=0; end
if nargin == 5; Enull=0; J=n-rank(d)+1; end

%Lmin=n-rank(d)+1;
if Enull == 0
 e=zeros(m,r); g=0;
else
 g=1;
end

Lmin=J;

%
for i=1:Lmin
  o((i-1)*m+1:i*m,:)=d*a^(i-1);
end

%
Atmin=o*a*pinv(o'*o)*o';

%
Hd=zeros(Lmin*m,(Lmin+g-1)*r);
for i=1:Lmin -(1-g)
  Hd((i-1)*m+1:m*i,(i-1)*r+1:r*i)=e;
  for j=i+1:Lmin
    Hd((j-1)*m+1:m*j,(i-1)*r+1:r*i)=d*a^(j-1-i)*b;
  end
end

%
Btmin=[o*b Hd]-Atmin*[Hd zeros(Lmin*m,r)];

Ld = L-Lmin;
At=[zeros(Ld*m,m) eye(Ld*m,(L-1)*m);zeros(Lmin*m,Ld*m) Atmin];
Bt = [zeros(Ld*m,(L+g)*r);zeros(Lmin*m,Ld*r) Btmin];
