function sorted_data_tae = tae_sort_data(cfg)

data = cfg.data;

data_all        = cell(length(cfg.subjects),1);
data_prev_left  = cell(length(cfg.subjects),1);
data_prev_right = cell(length(cfg.subjects),1);


for iSubject = 1:length(cfg.subjects)
    
        
    %% All trials
    
    tmp_data = [];
    
    for j = 2:size(data{iSubject},1)
        
        if (data{iSubject}(j,2) == data{iSubject}(j-1,2)) && ~isnan(data{iSubject}(j,9)) && ~isnan(data{iSubject}(j-1,9)) && ~isnan(data{iSubject}(j,8)) && ~isnan(data{iSubject}(j-1,8))
            
            prev_stim_ori = data{iSubject}(j-1,5);
            prev_decision = data{iSubject}(j-1,9);
            stim_ori = data{iSubject}(j,5);
            decision = data{iSubject}(j,9);
            
            tmp_data = [tmp_data; ...
                prev_stim_ori, prev_decision, stim_ori, decision];
            
        end
        
    end
    
    data_all_tae{iSubject,1} = tmp_data;
    
    clear tmp_data
    
    %{
    %% Previous response = left
    
    tmp_data = [];
    
    for j = 2:size(data,1)
        
        if (data(j,2) == data(j-1,2)) && (~isnan(data(j,8))) && (data(j-1,8) == 0)
            
            stim_ori = data(j,5);
            response = data(j,8);
            
            tmp_data = [tmp_data; ...
                stim_ori, response];
            
        end
        
    end
    
    data_prev_left{iSubject,1} = tmp_data;
    
    clear tmp_data
    
    
    %% Previous response = right
    
    tmp_data = [];
    
    for j = 2:size(data,1)
        
        if (data(j,2) == data(j-1,2)) && (~isnan(data(j,8))) && (data(j-1,8) == 1)
            
            stim_ori = data(j,5);
            response = data(j,8);
            
            tmp_data = [tmp_data; ...
                stim_ori, response];
            
        end
        
    end
    
    data_prev_right{iSubject,1} = tmp_data;
    
    clear tmp_data
    %}

    %% Output data
    
    sorted_data_tae = data_all_tae;
    %sorted_data.data_prev_left      = data_prev_left;
    %sorted_data.data_prev_right     = data_prev_right;

end

end