% Code to parse JSON output from HEMVIP
% (c) Gustav Eje Henter 2020, 2022

function [results,seqnums] = json2result(trials,labelstrs,ignoreinitial)

seqidstartindex = length('NN_') + 1;

nc = numel(labelstrs);
np = numel(trials);
ns = numel(trials(1).responses);

results = -ones(np,nc);
seqnums = -ones(np,nc);

for p = (1+ignoreinitial):np
    for s = 1:ns
        if iscell(trials(p).responses)
            stimulus = trials(p).responses{s}.stimulus;
            scorestr = trials(p).responses{s}.score;
        else
            stimulus = trials(p).responses(s).stimulus;
            scorestr = trials(p).responses(s).score;
        end
        
        if contains(stimulus,'_att_')
        	continue; % This is an attention check; ignore this slider
        end
        
        % Detect system ID for this slider
        labelstr = stimulus(1:2);
        
        % Detect video ID (stimulus number) for this slider
        seqnumstr = stimulus(seqidstartindex:seqidstartindex+2);
        
        whichc = false(1,nc);
        for c = 1:nc
            whichc(c) = strcmp(labelstrs{c},labelstr);
        end
        if sum(whichc) ~= 1
            error('Failed to uniquely identify system!');
        end
        c = find(whichc);
        
        if results(p,c) >= 0
            warning('Overwriting existing rating. Duplicate system?');
        end
        
        score = str2double(scorestr);
        if isnan(score) || (score < 0) || (score > 100)
            error(['Invalid score "' scorestr '"']);
        end
        results(p,c) = score;
        
        seqnum = str2double(seqnumstr);
        if isnan(seqnum) || (seqnum < 0) || (seqnum > 100)
            error(['Invalid sequence number "' seqnumstr '"']);
        end
        seqnums(p,c) = seqnum;
    end
    
    okratings = sum(results(p,:) >= 0);
    if (okratings ~= ns) && (okratings ~= ns-1)
        warning('Number of ratings differs from what is expected.');
    end
end

% Set missing entries to NaN
results(results < 0) = NaN;
seqnums(seqnums < 0) = NaN;

% Crop out any intial screens that we are ignoring
results = results(1+ignoreinitial:end,:);
seqnums = seqnums(1+ignoreinitial:end,:);