function [D,Dg,K]=precbsp(m,P);
%Pre-calculation of matrices for Carleman Bilinearization
%
% [D,Dg,K]=PRECBSP(M,P) calculates matrices used in the non-redundant Pth
% order Carleman Bilinearization (using sparsity) of a system with state
% vector of dimension n
%
% See also carlbilinsp

%   CBVK Toolbox
%   JHMG, PMSB 2016

%------------------------------------

allterms = fliplr(calcnumterms(P,m));
[Mvars, Mpos, D] = mapsvarspos(m, P);
Dg = D(1:end-allterms(end),1:end-allterms(end));
Dg(Dg > size(Dg,1)) = 0;

MP = nchoosek(m+P,P);
K = zeros(MP,2);

for p=2:P
    lin0 = sum(allterms(1:p-1));
    mp = allterms(p);
    for linp=1:mp
        lin = lin0+linp;
        vars = Mvars{lin+1};
        [v1,v2] = splithalf(vars);
        posv1 = posrecur(Mpos, v1);
        posv2 = posrecur(Mpos, v2);
        K(lin0+linp+1,:)=[posv1 posv2];
        
    end;
end;    

D=D-1;
D=D.*(D~=-1);
K=K(2:end,:);


