%trails.m : add motion trails (sort of) to video

%fname      input avi name
%a          exponent base to use
%l          number of frames to consider for each calculation
%outname    output avi name

%Notes: 
%
% * If you cancel this function, you'll have to run 'clear mex' to close the
%output file if you want to run it again!
%
% * The output files are BIG!

function trails(fname,a,l,outname)

%get info about the avi
ainfo = aviinfo(fname);
h = ainfo.Height;
w = ainfo.Width;
fr = ainfo.NumFrames;

%set up our arrays
data = zeros(h*w*3,l);
ex = (a .^(l-1:-1:0))';

%set up the output avi writer
aviobj = avifile(outname);
aviobj.fps = ainfo.FramesPerSecond;
aviobj.compression = 'none';

%for each frame. . .
for i=0:fr-1

    %read in the next frame
    index = mod(i,l) + 1;
    mov = aviread(fname,i+1);
    data(:,index) = double(reshape(mov(1).cdata,h*w*3,1)) / 255;

    %the actual calculation
    im = (data * ex) ./ sum(ex,1);

    %show results, and save them    
    image(reshape(im, h,w,3));
    aviobj = addframe(aviobj,getframe);

    %rotate the exponent vector, to keep up the the data circle buffer
    ex = circshift(ex,[1,1]);

end

aviobj = close(aviobj);