function [path_struct,group1]=extract_paths(x_path,y_path,time,mode)

close all;

pathvalid = false;
path_num = 0;
path_struct.x = 0;
path_struct.y = 0;
path_struct.time = 0;
time_offset = 0;
j=1;
grp_i = [];
l = 5; %time normalization (5s)

H = figure('name','original path');
hold on, grid on, axis equal;
%set(H,'pos',[800   200   500   400]);

%plot path and get input for grouping
plot(x_path,y_path);
coordinates = ginput(2);
min_x = coordinates(1,1);
max_x = coordinates(2,1);


I = figure('name','decomposed path');
hold all, grid on, axis equal;
%set(H,'pos',[800   200   500   400]);

for i=1:length(time)
    %check if valid based on x position
    if (x_path(i) > min_x && x_path(i) < max_x)
        %check if it is a new path
        %if pathvalid is false, this is a new path
        if ~pathvalid 
            pathvalid = ~pathvalid;
            path_num = path_num + 1;
            
            %%check time offset
            time_offset = time(i); 
            j = 1;
        end
        
        %feed paths structure
        path_struct(path_num).x(j) = x_path(i);
        path_struct(path_num).y(j) = y_path(i);
        path_struct(path_num).time(j) = time(i)-time_offset;
%         plot(path_struct(path_num).x,path_struct(path_num).y,'o');
        j = j + 1;
    
    %in case not valid    
    else
        %only change value if previous was true
        %used to create a new path
        if pathvalid
            pathvalid = ~pathvalid;
        end
    end
end

for i = 1:path_num
    plot(path_struct(i).x,path_struct(i).y,'o');
end

%group same traj paths
for i = 1:path_num %first diag and first straight
    if(mode == 1)
        if(path_struct(i).y(1) > 300 && path_struct(i).y(end) > 200);
            grp_i(end+1) = i;
        end
    elseif(mode == 0)
        if(path_struct(i).y(1) > 300 && path_struct(i).y(end) < 300);
            grp_i(end+1) = i;
        end        
    end
end


J = figure('name','grouped path');
xlabel('x'), ylabel('y');
hold all, grid on, axis equal;

%supposing indexes same group path traj
for i=1:length(grp_i)
        group1(i).x = path_struct(grp_i(i)).x;
        group1(i).y = path_struct(grp_i(i)).y;
        group1(i).time = path_struct(grp_i(i)).time;
        factor = l/group1(i).time(end);
        group1(i).time_normalized = group1(i).time .* factor ;
        %plot(group1(i).x,group1(i).y,'o');
end

%remove small paths (at leas 3 times smaller then ref)
if((length(group1(2).time)/length(group1(1).time))>3)
    group1(1) = [];
end
if((length(group1(2).time)/length(group1(end).time))>3)
    group1(end) = [];
end    
    
for i=1:length(group1)
    plot(group1(i).x,group1(i).y,'o');
end
    
    