function dataOut = import_trackmate_xml(filename)
%IMPORT_TRACKMATE_XML  Import data from TrackMate XML
%
%  S = IMPORT_TRACKMATE_XML(filename) imports data from the XML file
%  specified. The XML data should be generated using the ImageJ TrackMate
%  program.

%Read the file
XMLdoc = xmlread(filename);

%Read the 'Tracks' tag to see how many tracks are present
tracks = getElementsByTagName(XMLdoc, 'Tracks');
nTracks = str2double(tracks.item(0).getAttribute('nTracks').toString);

%Initialize a struct to hold the data
dataOut = struct('ParticleID', 'Time', 'X', 'Y');
dataOut(nTracks).ParticleID = nTracks;

%Read the 'particle' tag
particles = tracks.item(0).getElementsByTagName('particle');

%Read data from each particle
for kk = 0:(particles.getLength - 1)
    
    %Select current particle
    currParticle = particles.item(kk);
    
    %Check how many timepoints is in this track
    timepts = currParticle.getAttribute('nSpots');
    timepts = str2double(timepts.toString);
    
    %Initialize matrices to store data
    currX = zeros(1, timepts);
    currY = zeros(1, timepts);
    currT = zeros(1, timepts);
    
    %Read 'detection' tag
    thisdetection = currParticle.getElementsByTagName('detection');
    
    %Collect data from this particle
    for jj = 0:(thisdetection.getLength - 1)
        
        currX(jj + 1) = str2double(thisdetection.item(jj).getAttribute('x').toString);
        currY(jj + 1) = str2double(thisdetection.item(jj).getAttribute('y').toString);       
        currT(jj + 1) = str2double(thisdetection.item(jj).getAttribute('t').toString);
        
    end
    
    dataOut(kk + 1).ParticleID = kk;
    dataOut(kk + 1).Time = currT;
    dataOut(kk + 1).X = currX;
    dataOut(kk + 1).Y = currY;
    
end

dataOut = struct2table(dataOut);



