function MPEG_decode(stream_to_decode)
% decodes an MPEG stream previously encoded with MPEG_encode
% it creates a file named [stream_to_decode '_dec'] 

load(stream_to_decode)

load('Q.mat');
GOP_length = length(GOP_structure);
order = get_enc_order( GOP_structure );
Qi = interp_Q(Qi,B_size);
Qp = interp_Q(Qp,B_size);

decoded_stream = struct('frame_data',0,'frame_type',0,'motion_vector_x',0,'motion_vector_y',0);
ref_past = 0;
ref_future = 0;

wb = waitbar(0,'Decoding frames');
for n = 1 : length(encoded_stream)
    waitbar(n/length(encoded_stream),wb);
    
    m = mod(n-1,length(order))+1;
    orig_num =  floor((n-1)/GOP_length)*GOP_length+order(m);
    if (orig_num > length(encoded_stream))
        orig_num = n;
    end
    switch encoded_stream(n).frame_type
        case 'I'
            ref_past = ref_future;
            decoded_frame = decode_I_frame( encoded_stream(n).frame_data, B_size, MB_size, Wq*Qi  );
            ref_future  = decoded_frame;
            decoded_stream = add_frame( decoded_stream, decoded_frame, 'I', 0, 0, orig_num );
        case 'P'
            ref_past = ref_future;
            decoded_frame = decode_P_frame( encoded_stream(n).frame_data, ref_past, B_size, ...
                MB_size, Wq*Qp, encoded_stream(n).motion_vector_x,encoded_stream(n).motion_vector_y );
            ref_future  = decoded_frame;
            decoded_stream = add_frame( decoded_stream, decoded_frame, 'P', 0, 0, orig_num );
        case 'B'
            decoded_frame = decode_B_frame( encoded_stream(n).frame_data, ref_past, ref_future, B_size, MB_size, Wq*Qp,...
                encoded_stream(n).motion_vector_x(1:end/2,:),encoded_stream(n).motion_vector_y(1:end/2,:),...
                encoded_stream(n).motion_vector_x(end/2+1:end,:),encoded_stream(n).motion_vector_y(end/2+1:end,:));
            decoded_stream = add_frame( decoded_stream, decoded_frame, 'B', 0, 0, orig_num );
    end

end
close(wb);

save([stream_to_decode '_dec'], 'decoded_stream')

%%
% v = VideoWriter('proba.avi');
% open(v);
% for n = 1:length(decoded_stream)
%     writeVideo(v, decoded_stream(n).frame_data );
% end
% close(v);

