function D = blkdiag2(V, varargin)

%BLKDIAG2  column/row decomposition of matrix V to the block-diagonal D.
%          dim ... decomposition dimension 
%                  dim = [] preserves original matrix. 
%                  dim = 1  decomposition along rows (preserve columns).
%                  dim = 2  decomposition along columns (preserve rows).
%          N ..... optional parameter number of repetiotions along diagonal (see examples below).
%
% D = BLKDIAG2(V, dim, N)    produces  |3 0|
%
%
%              |1 2|                   |1 0|
% D = BLKDIAG2(|3 4|, 1)     produces  |3 0|
%                                      |0 2| 
%                                      |0 4|
% 
%              |1 2|                   |1 2 0 0|
% D = BLKDIAG2(|3 4|, 2)     produces  |0 0 3 4|
%
%     
%              |1 2|                   |1 2 0 0 0 0 0 0|
% D = BLKDIAG2(|3 4|, 2, 2)  produces  |0 0 3 4 0 0 0 0|
%                                      |0 0 0 0 1 2 0 0| 
%                                      |0 0 0 0 0 0 3 4|
%
%              |1 2|                   |1 2 0 0|
% D = BLKDIAG2(|3 4|, [], 2) produces  |3 4 0 0|
%                                      |0 0 1 2| 
%                                      |0 0 3 4|


if ndims(V)>2,
    V = squeeze(V);
end;

[M N] = size(V);

if isempty(varargin{1})
     D=V; 
elseif (varargin{1}==1)
    u = mat2cell(V, M ,ones(1,N));
    D = blkdiag(u{:});
elseif (varargin{1}==2)
    u = mat2cell(V, ones(1,M), N);
    D = blkdiag(u{:}); 
end;   

if nargin ==3,
    v = repmat({D},1,varargin{2}); 
    D = blkdiag(v{:});
end;



