function D = makeSIDmatrix(sid, N)
% makeSIDmatrix   Make sparse matrix D from Shift Invariant Dictionary 
%
% use:   D = makeSIDmatrix(sid, N);
% -------------------------------------------------------------------------
%   D     A dictionary matrix of size NxK  (K is calculated from sid)
%   sid   The Shift Invariant Dictionary, a struct as in initSID
%   N     Size for first dimension in D
% -------------------------------------------------------------------------
% ex:   Qm = [8,8,16,32,64]; Pm = [1,1,2,4,8]; sid = initSID(Qm,Pm);
%       D = makeSIDmatrix(sid, 100);

%--------------------------------------------------------------------------
% Made by Karl Skretting, University of Stavanger (UiS), 
% Department of Electrical Engineering and Computer Science (IDE)
% Mail:  karl.skretting@uis.no   Homepage:  http://www.ux.uis.no/~karlsk/
% 
% HISTORY:  dd.mm.yyyy
% Ver. 1.0  28.10.2015  KS: made file 
%--------------------------------------------------------------------------

if ~isstruct(sid) || ~isfield(sid,'Type') || ~strcmp(sid.Type, 'SID')
    disp([mfilename,': First argument not a SID structure.']);
    D = [];
    return;
end

Km = floor( (N+sid.Pm-sid.Qm)./sid.Pm );
K = sum(Km);
k2 = cumsum(Km);
k1 = [1; k2(1:(sid.M-1))+1];
nnZeros = sum((k2-k1+1).*sid.Qm);
% disp(['Number of non-zeros in D (',int2str(N),'x',int2str(K),') is ',int2str(nnZeros),'.']);

D = sparse([],[],[],N,K,nnZeros);
for m = 1:sid.M
    atom = sid.freeVar(sid.i1(m):sid.i2(m));
    n = 1:sid.Qm(m);
    for k = k1(m):k2(m)
        D(n,k) = atom; %#ok<SPRIX>
        n = n+sid.Pm(m);
    end
end

end
    
