function[minSSR,truebreaks]=dpcsd_gen_det(N,T,y,w,d,b,q,tr)
f=floor(tr*T);
for l=0:b-1
    for i=l*f+1:(l+1)*f
        for j=f+i-1:T-(b-l)*f
            wtilde=zeros(j-i+1,q,N);
            ytilde=zeros(j-i+1,1,N);
            I=eye(j-i+1);
            Zbar=[d(i:j,:,1) mean(w(i:j,:,:),3)];
            Q=I-Zbar*((Zbar'*Zbar)\Zbar');
            for s=1:N
                wtilde(:,:,s)=Q*w(i:j,:,s);
                ytilde(:,:,s)=Q*y(i:j,:,s);
            end
            WW=zeros(q,q);
            WY=zeros(q,1);
            YY=0;
            for s=1:N
                WW=WW+wtilde(:,:,s)'*wtilde(:,:,s);
                WY=WY+wtilde(:,:,s)'*ytilde(:,:,s);
                YY=YY+ytilde(:,:,s)'*ytilde(:,:,s);
            end
            SSR(i,j)=YY-WY'*(WW\WY);
        end
    end
end
for i=f*b+1:T-f+1
    for j=f+i-1:T
        wtilde=zeros(j-i+1,q,N);
        ytilde=zeros(j-i+1,1,N);
        I=eye(j-i+1);
        Zbar=[d(i:j,:,1) mean(w(i:j,:,:),3)];
        Q=I-Zbar*((Zbar'*Zbar)\Zbar');
        for s=1:N
            wtilde(:,:,s)=Q*w(i:j,:,s);
            ytilde(:,:,s)=Q*y(i:j,:,s);
        end
        WW=zeros(q,q);
        WY=zeros(q,1);
        YY=0;
        for s=1:N
            WW=WW+wtilde(:,:,s)'*wtilde(:,:,s);
            WY=WY+wtilde(:,:,s)'*ytilde(:,:,s);
            YY=YY+ytilde(:,:,s)'*ytilde(:,:,s);
        end
        SSR(i,j)=YY-WY'*(WW\WY);  
    end
end
%Dynamic Programming
if b==1
    l=0;
    for k=T
        for j=(l+1)*f:k-f  
            S(j,k,l+1)=SSR(1,j)+SSR(j+1,k);
        end
     end
    B=S(:,:,l+1);
    B(B==0)=NaN; 
    [minS,breaks]=min(B);
    minSSR=minS(1,T);
    truebreaks=breaks(1,T);
else if b>1
        S=zeros(T,T,b);
        %Initital subproblem
        l=0;
        for k=(l+2)*f:T-(b-l-1)*f
            for j=(l+1)*f:k-f
                S(j,k)=SSR(1,j)+SSR(j+1,k);
            end
        end
        B=S;
        B(B==0)=NaN;
        [Sstar,breakdate]=min(B);
        %Repeating subproblem
        for l=1:b-2
            for k=(l+2)*f:T-(b-l-1)*f
                for j=(l+1)*f:k-f
                    S(j,k,l+1)=Sstar(:,j,l)+SSR(j+1,k);
                end
            end
            B=S(:,:,l+1);
            B(B==0)=NaN;        
            [Sstar(:,:,l+1),breakdate(:,:,l+1)]=min(B);
        end
        %Final subproblem
        l=b-1;
        for k=T
            for j=(l+1)*f:k-f    
                S(j,k,l+1)=Sstar(:,j,l)+SSR(j+1,k);
            end
         end
        B=S(:,:,l+1);
        B(B==0)=NaN;
        [Sstar(:,:,l+1),breakdate(:,:,l+1)]=min(B);
    end
    minSSR=min(Sstar(:,:,l+1));
    breakdate(breakdate==1)=NaN;
    truebreaks(1,b)=breakdate(:,T,b);
    for i=1:(b-1)
        j=b-i;
        truebreaks(1,j)=breakdate(:,truebreaks(1,j+1),j);
    end
end