clear
close all

load('Xmen2.mat');

MB_size = 16;
i_ind = 1;
I = crop_pic(  grayscale( frames(i_ind).cdata ), MB_size );

%%
Nmb = size(I)/MB_size;
I_mb = mat2cell(I, repmat(MB_size,1,Nmb(1)), repmat(MB_size,1,Nmb(2)));
iI_mb = cell(size(I_mb));   
residual_MB = cell(size(I_mb));
type = cell(size(I_mb));

wb = waitbar(0,'Wait');
i = 0;

for n = 1 : size(I_mb,1)
    waitbar(i/prod(Nmb),wb);
    for m = 1 : size(I_mb,2)
        i = i+1;
        if (n == 1)&&(m==1)
            iI_mb{n,m} = I_mb{n,m};
            type{n,m} = '16';
        else
            [ upper_neighbour, left_neighbour ] = get_neigbours( I_mb, MB_size, n,m );
            [iI_mb{n,m}, type{n,m} ]  = intra_predict( I_mb{n,m}, upper_neighbour ,left_neighbour );
        end
    end
end
close(wb);
iI = cell2mat( iI_mb );
residual = I-iI;
%%
load demo

figure('units','normalized','outerposition',[0 0 1 1])

subplot(1,2,1);
imshow(uint8(iI));

subplot(1,2,2);
pcolor(flipud(residual));shading interp;colormap gray
caxis([-1e1,1e1]*10)
axis equal tight
%%
figure
pcolor( iI )
axis equal tight
shading interp;colormap gray
caxis([0,255])
hold on
v = (0:16);
for y = 1 : size(I_mb,1)
    for x = 1 : size(I_mb,2)
        
        O = [(x-1)*MB_size+1, (y-1)*MB_size+1, ];
        
        plot( O(1)+v, O(2)+zeros(17,1), 'k' );
        plot( O(1)+zeros(17,1), O(2)+v, 'k' );
        
        if strcmp( type{y,x}, '4' )
            
            plot( O(1) +v,             O(2)+4+zeros(17,1), 'k' );
            plot( O(1)+4+zeros(17,1),  O(2)+v, 'k' );
            plot( O(1) +v,             O(2)+8+zeros(17,1), 'k' );
            plot( O(1)+8+zeros(17,1),  O(2)+v, 'k' );
            plot( O(1) +v ,            O(2)+12+zeros(17,1), 'k' );
            plot( O(1)+12+zeros(17,1), O(2)+v, 'k' );
            
        end
        
    end
end
set(gca,'ydir','reverse')