%EUSIPCO 2012
%Imperial College London 
%Andriy Gelman, Jon Onativia and Pier Luigi Dragotti 

function output = construct_bit_stream_with_header(direction_list, layer_number, hcode, row_list, column_list)

%The Initial Point must also be encoded in the header. 
%The first four bits contain the layer number. 
%The next 24 bits will contain the initial_point. (12 bits for the row,
%12bits for the columns). 
%The next 4 bits contain the initial direction. 
%The next 12 bits contain the length of the encoded huffman code - in bytes. 

if ~isempty(hcode)
    remainder = rem(length(hcode),8);
    length_of_huffman_code = 8-remainder + length(hcode);
    %length of the huffman code in bytes
    length_of_huffman_code = length_of_huffman_code/8; 
    
    %Turn initial direction into bits
    
    initial_direction = mod(double(dec2bin(direction_list(2), 4)),2);
    %direction_sign = sign(initial_direction + 1);
    
    %if (direction_sign == -1)
    %    direction_sign = 0;
    %end      
    %initial_direction = abs(initial_direction);
    
else
    initial_direction = [0 0 0 0 0];
    length_of_huffman_code = 0;    
    direction_sign = [];
end

initial_row = row_list(1);
initial_column = column_list(1);

layer_header = mod(double((dec2bin(layer_number, 4))),2);
row_header = mod(double(dec2bin(initial_row, 12)),2);
column_header = mod(double(dec2bin(initial_column,12)),2);

length_header = mod(double(dec2bin(length_of_huffman_code, 12)),2);

%header =  [layer_header, row_header, column_header, direction_sign, initial_direction, length_header];
header =  [layer_header, row_header, column_header, initial_direction, length_header];
if ~isempty(hcode)
    buffer = zeros(1,length(hcode));
    buffer(1,:) = hcode;
else
    buffer = [];
end

output = [header, buffer];

end
