addpath('../../JSON');
addpath('../../Quaternions');

% To use the network: leave the variable below empty (''), otherwise, give
% the path of the filename to be processed.
if ~exist('JSON_filename','var') % This enables setting the filename externally to this main script (to run this script in parallel, on servers)
    JSON_filename = '';
    % '/vol/vssp/ucdatasets/s3a/vml/2015_02_17_XEF/20150217_111609_v2.json';  % 'received_data.json'; % ''; % 
end

% nTime0 = 0; % Time stamp of "previous" block of data;
if isempty(JSON_filename)
    fprintf('Getting stream from the network.');
    H = dsp.UDPReceiver('ReceiveBufferSize', 20000, 'LocalIPPort', 8888, 'MaximumMessageLength', 60000);
    
    json2data = {};
    
    while true,
        dataReceived = step(H);
        % fprintf(char(dataReceived));

        if ~isempty(dataReceived)
            json2data = loadjson(sprintf('%s',char(dataReceived)), 'NumbersAsNumbers', 1); % 'SimplifyCell',1, 
            json2StickManPlot(json2data);
            drawnow;
            % pause(0.0001)
            title(sprintf('nTime=%u', json2data.nTime));
        % else % Break this nicely if the stream finished. 
            % Trouble dataReceived is often empty at the beginning of the
            % sequence, so this does not work. Maybe the sender program
            % should include a flag saying that it has terminated sending
            % things.
        %     release(H);
        %     break;
        end
    end
else % Load data from a file recorded for offline use.
    [pathstr, filename, extension] = fileparts(JSON_filename);
    % Convert it to a MAT file, if this hasn't been done before.
    if isempty(pathstr),
        mat_filename = [filename, '.mat'];
    else
        mat_filename = [pathstr, filesep, filename, '.mat'];
    end        
    fprintf('Loading data from %s', [pathstr, filesep, filename]);
    tic;
    if ~exist(mat_filename, 'file'),
        fprintf('.json ...\n');
        % json2data = loadjson(JSON_filename,'SimplifyCell',1, 'ShowProgress',1, 'NumbersAsNumbers', 1);
        json2data = loadjson(JSON_filename, 'ShowProgress',1, 'NumbersAsNumbers', 1);
        save(mat_filename, 'json2data');
    else
        fprintf('.mat ...\n');
        load(mat_filename);
    end
	time = toc;
    fprintf('Done in %d min %5.3f seconds.\n', floor(time/60), rem(time,60));
        
    % nTime0 = json2data{1}.nTime;
    % jFirst = 1; % "pointer" to the beginning of the buffer of people who appear in the same frame;
    for c=1:length(json2data)
        json2StickManPlot(json2data{c});
        drawnow;
        % pause(0.0001)
    end
end
