clear
close all

load('foreman.mat');
load('Q.mat');

I = grayscale(frames(1).cdata);
P = grayscale(frames(2).cdata);
%%
B_size  = 8;
MB_size = 16;
Wq = 2;

[N,D]= rat(B_size/8);
Qp = resample(resample(Qp,N,D)',N,D)';
Nmb = size(I)/MB_size;

I = crop_pic( I, MB_size );
P = crop_pic( P, MB_size );
search_width = 8; 


%% Encoder
P_mb = mat2cell(P, repmat(MB_size,1,Nmb(1)), repmat(MB_size,1,Nmb(2)));
P_encoded = cell(size(P_mb));
u = zeros(size(P_mb));
v = zeros(size(P_mb));
for n = 1 : Nmb(1)
    for m = 1 : Nmb(2)

    %    P_q = quantize( P_mb{n,m}, MB_size, B_size, Wq*Q );
     %   P_iq = inverse_quantize( P_q, MB_size, B_size, Wq*Q );
        [u(n,m), v(n,m)]  = get_motion_vector( P_mb{n,m}, n,m, I, MB_size, search_width );
        P_encoded{n,m} =  quantize(  motion_prediction( P_mb{n,m}, I, u(n,m), v(n,m), n, m ), MB_size, B_size, Wq*Qp );
        
        
    end
end


%% Decoder
P_decoded = cell(size(P_mb));

for n = 1 : Nmb(1)
    for m = 1 : Nmb(2)
        P_iq = inverse_quantize( P_encoded{n,m}, MB_size, B_size, Wq*Qp );
        P_decoded{n,m} = motion_compensation( P_iq, I, u(n,m), v(n,m), n, m  );  
    end
end
%%
figure
subplot(1,3,1)
pcolor(flipud( P ));shading interp;axis equal tight;colormap gray
subplot(1,3,2)
pcolor(flipud( cell2mat(P_decoded) ));shading interp;axis equal tight;colormap gray
subplot(1,3,3)
pcolor(flipud( cell2mat(P_decoded) - P));shading interp;axis equal tight;colormap gray
