% plot_ptrack.py
%
% Plot particle track(s) from ptrack.txt files.
% User should configure the following variables:
%	- fname: path to ptrack.txt file
%
% Parsed data for N tracks is provided in the following variables
% 	- time: Cell array of N arrays. Each array contains the
%	  elapsed time in seconds since the start of the track. 
%	- x: Cell array of N arrays. Each array contains time series
%	  of particle x coordinates in pixels.
%	- y: Cell array of N array. Each array contains time series
%	  of particle x coordinates in pixels.
clear all; close all; clc;
fname = 'ptrack_test.txt';

% Open ptrack file
fid = fopen(fname, 'r');

% # Create data tuples
time = {};
x = {};
y = {};

% Loop until EOF
while true

    % Find start of track while checking for EOF
    line = fgetl(fid);
    if line == -1
        break
    end
    while ~startsWith(line,'$NEW')
        line = fgetl(fid);
        if line == -1
            break
        end
    end

    % Consume header
    line = fgetl(fid);
    while ~startsWith(line, 'HR')
        line = fgetl(fid);
    end

    % Parse data
    track_time = [];
    track_x = [];
    track_y = [];
    line = fgetl(fid);
    while ~startsWith(line, '$$END')
        data = split(line);
        if length(data) == 6
            track_time(end+1) = str2double(data(1))*3600 + ...
                str2double(data(2))*60 + str2double(data(3)) + ...
                str2double(data(4))/1000;
            track_x(end+1) = str2double(data(5));
            track_y(end+1) = str2double(data(6));
        end
        line = fgetl(fid);
    end

    % Add data to tuples
    delta_time = track_time - track_time(1);
    time{end+1} = delta_time;
    x{end+1} = track_x;
    y{end+1} = track_y;
    
end

fclose(fid);

% Plot overhead view of tracks
figure; hold on;
labels = {};
for i = 1:length(time)
    plot(x{i}, y{i});
    labels{i} = sprintf('Track %d', i);
end
xlabel('x (pixels)')
ylabel('y (pixels)')
title('Overhead view')
axis equal
legend(labels)

% Plot time series of x coordinate
figure; hold on;
labels = {};
for i = 1:length(time)
    plot(time{i}, x{i});
    labels{i} = sprintf('Track %d', i);
end
xlabel('Elapsed time (s)')
ylabel('x (pixels)')
title('Time series')
legend(labels)

