function [boundaries,levels] = dynprog(X,k,p);

%% Dynamic programming of (k,k)-segmentation
%% X data matrix
%% k = amount of segments we are looking for
%% p = 1 (median used), p = 2 (mean used)

if (k<1) 
    best = NaN;
    boundaries = NaN;
    return
end

[d,n] = size(X)

    
for i=1:n
    lastpiece(1,i,1) = 1;
    for j=i:n
      cost(i,j,1) = Lperror(X(:,i:j),representative(X(:,i:j),p),p);
    end
end

for b=2:k
    for i=1:n
        cost(1,i,b) = cost(1,i,b-1);
        lastpiece(1,i,b) = -1;
        for j=1:i-1
            if cost(1,j,b-1)+cost(j+1,i,1)<=cost(1,i,b)
                cost(1,i,b) = cost(1,j,b-1)+cost(j+1,i,1);
                lastpiece(1,i,b) = j+1;
            end
        end
    end
end

ind = n+1;
boundaries(k+1) = n+1;

while ind > 0 && k>0
prevind = ind;
ind = lastpiece(1,ind-1,k);
    boundaries(k) = ind;
    levels(k,:) = representative(X(:,ind:prevind-1),p)';
    k = k-1;
end;
