function [trainT, validT] = loadPerformance(csvFile, trainVarNames)
    % Written by
    %   Alessandro Motta <alessandro.motta@brain.mpg.de>
    if ~exist('trainVarNames', 'var')
        trainVarNames = {'loss'};
    end
    
    trainVarNames = reshape( ...
        trainVarNames, 1, []);
    validVarNames = cellfun( ...
        @(name) sprintf('%s_valid', name), ...
        trainVarNames, 'UniformOutput', false);
    
    data = readtable(csvFile);
    
    trainT = filterTable(data(:, [ ...
        {'step', 'weight_count'}, trainVarNames]));
    trainT.Properties.VariableNames{2} = 'weightCount';

    validT = filterTable(data(:, [{'step'}, validVarNames]));
    validT.Properties.VariableNames(2:end) = trainVarNames;

    % Add weight count to validation table
    assert(issorted(trainT.weightCount, 'descend'));
   [uniWeights, uniSteps] = unique(trainT.weightCount, 'stable');
    uniSteps = trainT.step(uniSteps);

    curIds = arrayfun(@(s) find(uniSteps <= s, 1, 'last'), validT.step);
    validT.weightCount = uniWeights(curIds);

    % Same column order for training and validation tables
    validT = validT(:, trainT.Properties.VariableNames);
end

function t = filterTable(t)
    v = t.Properties.VariableNames;
    v = setdiff(v, 'step', 'stable');
    
    m = true(height(t), 1);
    for curV = v; m = m & ~isnan(t.(curV{1})); end
    t = t(m, :);
    
    t = flip(t, 1);
   [~, i] = unique(t.step, 'stable');
    t = flip(t(i, :), 1);
end
