% Input:
% L: Matrix (containing direction vectors)
% results: Matrix (evaluation results for the directions from L)
% x_param: integer (dimension to plot)
% y_param: integer (dimension to plot)

% Output:
% L: nx2 Matrix (containing direction vectors)
% results: Matrix (evaluation results for the directions from L)

% Description:
% Reduces L and results to the directions to plot (x_param,y_param) and sorts them such
% they are stored ordered and intersections have only to be computed
% between lines of neighboar directions in L

function [L,results] = sortL(L,results,x_param,y_param)

L = L(:,[x_param y_param]);

L1iterator = 1;
L2iterator = 1;

L1 = [0 0];
L2 = L1;

spvalues1 = zeros(0,size(results,2));
spvalues2 = zeros(0,size(results,2));

% split L and spvalues into 2 parts such that the values of cos define the
% angle unambiguously for each half circle
for i=1:1:size(L,1)
    l = L(i,:);
    
    if ((l(1) ~= 0 ) || (l(2) ~= 0))
        
    if l(2) >= 0
        L1(L1iterator, :) = l;
               
        spvalues1(L1iterator,:) = results(i,:);
        
        L1iterator = L1iterator+1;
    else
        L2(L2iterator, :) = l;
                
        spvalues2(L2iterator,:) = results(i,:);
        
        L2iterator = L2iterator+1;
    end;
    
    end;    
end;
            
%sort sets of vectors
for i=1:1:size(L1,1)
        
    for j=i:-1:2
        l = L1(j,:); %vector under consideration
        lv = L1(j-1,:); %previous element in list
    
        if dot([1 0],l)/sqrt((l(1)^2)+(l(2)^2)) > dot([1 0],lv)/sqrt((lv(1)^2)+(lv(2)^2))
            %switch with previous
            L1(j,:)= lv;
            L1(j-1,:)= l;
            
            temp = spvalues1(j,:);
            spvalues1(j,:) = spvalues1(j-1,:);
            spvalues1(j-1,:) = temp;
        else
            %look at next
            break;
        end;
        
    end;
end;

for i=1:1:size(L2,1)
        
    for j=i:-1:2
        l = L2(j,:); %vector under consideration
        lv = L2(j-1,:); %previous element in list
    
        if dot([1 0],l)/sqrt((l(1)^2)+(l(2)^2)) < dot([1 0],lv)/sqrt((lv(1)^2)+(lv(2)^2))
            %switch with previous
            L2(j,:)= lv;
            L2(j-1,:)= l;
            
            temp = spvalues2(j,:);
            spvalues2(j,:) = spvalues2(j-1,:);
            spvalues2(j-1,:) = temp;
        else
            %look at next
            break;
        end;
        
    end;
end;

if isequal([0 0],L1)
    fprintf('no l in upper direction defined !');
end;

if isequal([0 0],L2) 
    fprintf('no l in lower direction defined !');
end;

% concatenate L and spavalues
L = vertcat(L1,L2);
results = vertcat(spvalues1,spvalues2);