% The script uses Ouellette's tracking software* to track tracers. It reads TIFF images and outputs
%  (1) background.tif: Image Background
%  (2) Tracking.mat: Tracking results including tracer velocities in each frame
%
% Usage:
%  (1) Copy the script to the same directory as the image folder
%  (2) Fill the parameters in "Set parameters" section
%  (3) Execute the script by pressing F5
%
% *Ouellette's tracking software is available to download from Environmental Complexity Laboratory, 
%  Stanford University (http://web.stanford.edu/~nto). Ensure each Matlab files are in the same folder. 
%
% Written by Kun-Ta Wu, June 2019

%% Set parameters
clc; clear all; close all;

trackingSoftwareDirectory=;                                         % Input the directory storing files for Ouellette's tracking software
imageDirectory=;                                                    % Input the directory storing image files

%% Track tracers

addpath(trackingSoftwareDirectory);                                 % Include the directory of the tracking software to Matlab path
imageFiles=fullfile(imageDirectory,'*.tif');                        % Paths to the images

bg = BackgroundImage(imageFiles,'background.tif');                  % Generate background image
[vtracks,ntr,lm,lrms] = PredictiveTracker(imageFiles,50,9,...       % Track tracers. Details for inputs and outputs can be found in PredictiveTracker.m
                                          'background.tif',0,0,0); 
[u,v,x,y,t]=Velocities(vtracks,[0 inf],0);                          % Calculate tracer velocities at each frame

disp('Sorting Time Indices');
totalFrame=length(dir(imageFiles));                                 % Determine the number of frames

% Group indices with the same frame number into the same cell
% timeIndices(10) contains indices at Frame #10
timeIndices=cell(totalFrame,1);
for frame=min(t):max(t)
    timeIndices{frame}=find(t==frame);
end
clear frame;

% Save tracking results
disp('Saving the Data');
save('Tracking.mat');
clc;
disp('Tracking job is completed. The results are saved in Tracking.mat');
