function [vertices] = tree2contour(tree, depth)
% -------------------------------------------------------------------------
% 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        : tree2contour.m
% -------------------------------------------------------------------------
% Create a list of vertices for each contour for a given contour tree.
%
% [vertices] = tree2contour(tree[, depth)
%
% INPUT:
%  - tree     :
%  - depth    : 
%
% OUTPUT:
%  - vertices : List of vertices (2xN) with first element of each 
%               segment corresponding to [0; segment_length].
%

if nargin == 1
    depth = length(tree{1});
end

num_of_contours = length(tree);
contour_lengths = zeros(1, num_of_contours);

% Obtain the lengths of each contour
for ith_tree = 1 : num_of_contours
    if iscell(tree{ith_tree}{depth})
        contour_lengths(ith_tree) = size(cell2mat(tree{ith_tree}{depth}), 2);
    else
        contour_lengths(ith_tree) = size(tree{ith_tree}{depth}, 2);
    end
end

% Create the output vertices array
verts_len = num_of_contours + sum(contour_lengths);
vertices  = zeros(2, verts_len);

% Fill the vertices array
i = 1;
for ith_tree = 1 : num_of_contours
    
    cur_len = contour_lengths(ith_tree);
    
    % Insert length of the contour
    vertices(2, i) = cur_len;
    i = i + 1;
    
    % Insert the vertices
    if iscell(tree{ith_tree}{depth})
        vertices(:, i:i+cur_len-1) = cell2mat(tree{ith_tree}{depth});
    else
        vertices(:, i:i+cur_len-1) = tree{ith_tree}{depth};
    end
    
    i = i + cur_len;
end

