function trackCentroidsLive(obj, event, filePointer)
%trackCentroids Track the centroids in a movie
%   this uses image dilation to estimate the background image

x = 144;
y = 176;
numframes = 8;

if obj.FramesAvailable > 30 % a second behind!
    flushdata(obj);
end

% Get the data from the buffer
grMov = getdata(obj,numframes);


% dilate the background through 10 frames
% the last parameter for imdilate should be around 10, even for numframes >
% 10
background = imdilate(grMov, ones(1,1,1,10));

se = strel('disk',10);
seErode = strel('disk',3);

numAq = 0;

% subtract the background and threshold the image
for k = 1:2:numframes
  diff = imerode(imabsdiff(grMov(:,:,1,k), background(:,:,1,k)),seErode); 
  thresh = max(graythresh(diff),.05); 
  
  bwdiff = im2bw(diff,thresh);

  L = bwlabel(bwdiff); 
  s = regionprops(L, 'area', 'centroid'); % this command is slow
  area_vector = [s.Area]; 
  [tmp, idx] = max(area_vector); 

  if size(idx,1)==1
      numAq = numAq+1;
      if numAq > 1
          centroid = (centroid(1,:)*(numAq-1) + s(idx(1)).Centroid)/(numAq); 
      else
          centroid = s(idx(1)).Centroid; 
      end
  end

end

I = grMov(:,:,1,numframes);
if numAq > 2 && size(area_vector,2) < 18
  xpos = int32(centroid(1,1)); 
  ypos = int32(centroid(1,2)); 
  I(max(ypos-5,1):min(ypos+5,x),max(xpos-5,1):min(xpos+5,y)) = 200;
  if xpos < 48
      fprintf(filePointer, 'l');
  elseif xpos > 96
      fprintf(filePointer, 'r');
  else
      fprintf(filePointer, 'f');
  end
else
    fprintf(filePointer, 's');
end

% Uncomment the next few lines if you want to record the video
%filename = ['file',num2str(obj.UserData),'.mat'];

% -v6 option speeds up save process to help prevent the buffer from filling
% during file write operation
%save(filename,'I','-v6');
%obj.UserData = obj.UserData + 1;

imagesc(I);

drawnow;
% force an update of the figure window