function [ frame_encoded, u_f, v_f, u_b, v_b ] = encode_B_frame(  frame_in, ref_forw, ref_back, B_size, MB_size, Q,  search_width )

[Y,chroma] = RGB_to_YCbCr(frame_in);
[Y_ref_f, chroma_ref_f] = RGB_to_YCbCr(ref_forw);
[Y_ref_b, chroma_ref_b] = RGB_to_YCbCr(ref_back);

Nmb = size(Y)/MB_size;

Y_mb = mat2cell(Y, repmat(MB_size,1,Nmb(1)), repmat(MB_size,1,Nmb(2)));
Y_encoded = cell(size(Y_mb));

chroma_mb = mat2cell(chroma, repmat(MB_size/2,1,Nmb(1)), repmat(MB_size/2,1,Nmb(2)),2);
chroma_encoded = cell(size(chroma_mb));

u_f = zeros(size(Y_mb));
v_f = zeros(size(Y_mb));
u_b = zeros(size(Y_mb));
v_b = zeros(size(Y_mb));

for n = 1 : Nmb(1)
    for m = 1 : Nmb(2)
    
        
        [u_f(n,m), v_f(n,m)]  = get_motion_vector( Y_mb{n,m}, n,m, Y_ref_f, MB_size, search_width );
        [u_b(n,m), v_b(n,m)]  = get_motion_vector( Y_mb{n,m}, n,m, Y_ref_b, MB_size, search_width );
        Y_forw_pred = motion_prediction( Y_mb{n,m}, Y_ref_f, u_f(n,m), v_f(n,m), n, m );
        Y_back_pred = motion_prediction( Y_mb{n,m}, Y_ref_b, u_b(n,m), v_b(n,m), n, m );
        chroma_forw_pred = motion_prediction( chroma_mb{n,m}, chroma_ref_f, u_f(n,m), v_f(n,m), n, m );        
        chroma_back_pred = motion_prediction( chroma_mb{n,m}, chroma_ref_b, u_b(n,m), v_b(n,m), n, m );
        
        Y_encoded{n,m}      =  quantize(  (Y_forw_pred+Y_back_pred)/2 , MB_size, B_size, Q ); 
        chroma_encoded{n,m} =  quantize(  (chroma_forw_pred+chroma_back_pred)/2 , MB_size, B_size, Q ); 

    end
end

Y_encoded = cell2mat(Y_encoded);
chroma_encoded = cell2mat(chroma_encoded);
frame_encoded = struct('encoded_luma',Y_encoded,'encoded_chroma',chroma_encoded);

end


