function [r, valididx, clip_ids] = ranking_from_comparison_Stober_all_constraints(comparison, comparison_ids)
% returns rankings for compared songs.
% rankings are genrerated using a Multigraph analysis of the comparison
% data 
% 
% r(idx,1) = clip being similar to clip idx
% r(idx,2) = clip being less similar to clip idx
% r(idx,3) = weight of this ranking
%
% the indices in clipids correspond to the indices in comparison_ids

% create similarity graph

cprint(2, 'Generating Stober Multigraph for Similarity Constraints')
% Gstob = ClipSimGraphStober();
% Gstob.random_all_constraints_graph;
% G = ClipSimGraphMulti(Gstob.to_DiGraph());
load('comp_SimGraphStob_ac1.mat', 'G');


% inverse comparison index
inv_comparison = sparse(comparison_ids,1, 1:numel(comparison_ids));

% ---
% derive similarity information: this
% returns the weights of edges meaning sim(a,b) > sim(a,c)
% ---   
[weights, a, b, c] = G.similarities();
% --- 
% NOTE: it is yet unclear which index 
% (the comparison or the mtt clip index) 
% is best to use
% 
% The lines below transform the MTT ids from the graph into comparison ids
% ---
a = inv_comparison(a);
b = inv_comparison(b);
c = inv_comparison(c);

% ---
% reformat into ranking: the first 1019 clips are ordered
% as in comparison_ids. then, clips mentioned more than once 
% are attached. 
% ---
[a, idx] = sort(a);
b = b(idx);
c = c(idx);


clip_ids = zeros(numel(a), 1);

% ---
% NOTE: r may grow over its allocated size
% ---
r = cell(numel(a),1 );

% keep track of constraints which have been attached
visited = zeros(1, numel(a));
for i = 1:numel(comparison_ids)
    
    % ---
    % get first occurence of this index,
    % and save the data into ranking
    % ---
    tmp_idx = find(a == i, 1, 'first');
    
    clip_ids(i) = i; % == a(tmp_idx)
        
    if ~isempty(tmp_idx)
        visited(tmp_idx) = true;
        
        r{i,1} = b(tmp_idx);
        r{i,2} = c(tmp_idx);
        r{i,3} = weights(tmp_idx);
        
        valididx(i) = true;
    else
        % invalid ranking
        valididx(i) = false;
        r{i,3} = 0;
    end
end

% ---
% Now we attach the remaining constraints
% ---
remaining = find(~visited);
clip_ids( numel(comparison_ids)+1 : numel(comparison_ids)+numel(remaining)) = a(remaining);

for i = 1:numel(remaining)
    r{ numel(comparison_ids)+i, 1} = b(remaining(i));
    r{ numel(comparison_ids)+i , 2} = c(remaining(i));
    r{ numel(comparison_ids)+i , 3} = weights(remaining(i));
end

valididx(numel(comparison_ids)+1 : ...
    numel(comparison_ids)+numel(remaining)) = true;

