function [d_out] = bin2dec(b_in, twos_complement)
% -------------------------------------------------------------------------
% MSc Project - MSc in Communications and Signal Processing
% Department of Electrical and Electronic Engineering
% Imperial College London, 2011
%
% Supervisor  : Dr Pier Luigi Dragotti
% Contributor : Andriy Gelman
% Author      : Jon Onativia Bravo
%
% File        : tree2bitstream.m
% -------------------------------------------------------------------------
% 
%
% [d_out] = bin2dec(b_in)
%
% INPUT:
%  - 
%
% OUTPUT:
%  - 
%

if nargin == 1
    twos_complement = true;
end

N = length(b_in);

d_out = 0;
n     = 0;
for b_i = b_in(end:-1:1)
    d_out = d_out + b_i*(2^n);
    n     = n + 1;
end

% Convert two's complement to negative value
if twos_complement == true && d_out >= 2^(N-1)
    d_out = d_out - 2^N;
end

end