function [Fi,Fc,Gi,Gc] = carlbilinsp(F1i,F1c,G1i,G1c,G11,P,K,D,Dg)
%CARLBILINSP computes the non-redundant Carleman Bilinearization of a
%linear-analytic system, using sparsity
%
% [Fi,Fc,Gi,Gc] = CARLBILINSP(F1i,F1c,G1i,G1c,G11,P) computes the
% Pth order direct Carleman Bilinearization v' = Fv + G[1; v]u of the
% linear-analytic system x'= f(x) + g(x)u from its Taylor expansion
% coeficients [0 F1] and [G11 G1]. The procedure takes advantage of the
% sparsity of the matrices involved. Input and output arguments
% are in a sparsity oriented representation.
%
% [Fi,Fc,Gi,Gc] = CARLBILINSP(F1i,F1c,G1i,G1c,G11,P,K,D,Dg) uses
% pre-computed matrices thar depend only on P and the dimension of the
% state vector x
%
% See also evtaylorsp, precbsp

%   CBVK Toolbox
%   JHMG, PMSB 2016


m = length(F1i);
if nargin<7
    [D,Dg,K]=precbsp(m,P);
end


% Conversion from cell to matrix format
F1im=zeros(m,1);
F1cm=F1im;
G1im=F1im;
G1cm=F1im;
for i=1:m
    F1im(i,1:length(F1i{i}))=F1i{i};
    F1cm(i,1:length(F1i{i}))=F1c{i};
    
    G1im(i,1:length(G1i{i}))=G1i{i}+1;
    G1cm(i,1:length(G1i{i}))=G1c{i};
    
    if G11(i) ~=0
        G1im(i,1:length(G1im(i))+1)=[1 G1im(i)];
        G1cm(i,1:length(G1cm(i))+1)=[G11(i) G1cm(i)];
    end
     
end
ND=length(Dg);

allterms = fliplr(calcnumterms(P,m));
MP = sum(allterms);

F1im=[F1im zeros(m,1)];
F1cm=[F1cm zeros(m,1)];

% Bilinearization
[Fi,Fc,Gi,Gc,NA]=cbnrsp(F1im',F1cm',G1im',G1cm',m,MP,K',D',Dg',ND);



