%Function encodes image segmentation using the freeman algorithm. 
%28th May 2009, IC, Andriy Gelman 

%input = matrix array contains the non-zero values of the silhoutte, 
%all the input values in the matrix are set to one.

%output = cell output, containing the encoded data for the each
%segmentation map

function output = encode_layer(label, layer_number)

%Extract Single Line Pixels
label = double(label);
[r,c] = size(label);

%figure, imshow(uint8(label*255));
%function computes edge map of the label
%{
edge_map = compute_edge_map(label);

%Pad edge map - Useful when extracting a square block to deteremine next
%step
edge_map = padarray(edge_map, [1 1], 'both');

label = padarray(label, [1 1], 'both');
single_line_label = zeros(size(label));

%Obtain a list of coordinates (rows, columns) specifying the chain 
number_of_edge_maps = 1;
counter = 1;
%}
label = padarray(label, [1 1], 'both');

[c,h] = contour(label, [0 0]);
c = round(c);

%while(sum(sum(edge_map)) ~= 0)
number_of_edge_maps = 1;
while ~isempty(c)      
      length_sig = c(2,1);
      sig = c(:, 2:2+length_sig-1);
      
      c = c(:, 2+length_sig:end);
      %remove repeated values
      sig = sub2ind(size(label), sig(2,:), sig(1,:));
      l=1;
      while l<length(sig)
            if sig(l) == sig(l+1)
                sig = sig([1:l,l+2:end]);
            else 
                l = l+1;
            end
      end
      [sig(2,:), sig(1,:)] = ind2sub(size(label), sig);
      
      %calculate direction
      %add something here
        
      if length(sig(1,:))>1
        for l = 1:length(sig)-1
                direction(:,l) = sig(:,l+1) - sig(:,l); 
        end
        direction = direction(1,:) + i*direction(2,:);
        angle_direction = angle(direction);
        angle_direction = angle_direction/(2*pi)*360;
        angle_direction = angle_direction + 360;
        angle_direction = mod(angle_direction, 360);
        angle_direction = floor(angle_direction/45);
      
        direction_list = angle_direction;
  
        variational_direction = compute_variational_direction(direction_list);
      else
          direction = [];
          variational_direction = [];
          direction_list = [];
      end
      variational_direction = round(variational_direction);
      hcode = encode_variational_direction(variational_direction);
      output{number_of_edge_maps} = construct_bit_stream_with_header(direction_list, layer_number, hcode, sig(2,:), sig(1,:));

      number_of_edge_maps = number_of_edge_maps + 1;
        
      clear direction angle_direction direction_list variational_direction hcode 
end
  
    
  
%end


end



