%%{
clear mov2;

mov = aviread('marcDavidSashi_cleaned');

numFrames = size(mov,2)
width = size(mov(1).cdata,2)
height = size(mov(1).cdata,1)

useLessMem = 0;

if (useLessMem == 1)
    
% This was actually ends up using something like 4x the memory!
%  it may be because of the var type being used..?
fprintf('Loading video data into 4D matrix...\n');
videoData = zeros(height,width,numFrames,3);
dot = floor(numFrames / 50);
for t = 1 : numFrames
    if (mod(t,dot) == 0) 
        fprintf('.');
    end
    videoData(:,:,t,:) = reshape(mov(t).cdata, [480 640 1 3]);
end
fprintf('\nfinished loading video data!\n');

else % else if (useLessMem == 0)

videoData = cat(4, mov(:).cdata);
% re-order our dimensions into y, x, t, c
videoData = permute(videoData, [1 2 4 3]);

end % end if (useLessMem == )

% free up some memory...
movi = mov(1);
clear mov;
 
% we'll use a value of 0 as a mask value later
videoData(videoData == 0) = 1;

%{
% look at the [y or x]-time slice at a fixed [x or y]
yslice = 370;
img = squeeze(videoData(yslice,:,:,:));
figure(1);
imshow(img);

energy = calcEnergy(img);

figure(2);
imshow(energy,[]);
colormap hot;
%}


% *** start looping ***

for iter = 1 : numFrames

tic

%%{
% calculate energy functin for every slice in y
fprintf('Calculating energy for slices...\n');
avgEnergy = zeros(size(squeeze(videoData(1,:,:,1))));
dot = floor(height / 50);
for i = 1 : height
	%fprintf('\tslice %i of %i\n', i, height);
    if (mod(i,dot) == 0) 
        fprintf('.');
    end
    img = squeeze(videoData(i,:,:,:));
    energy = calcEnergy(img);
    energy = medfilt2(energy,[3 3]);
    %avgEnergy = avgEnergy + energy;
    avgEnergy = max(avgEnergy,energy);
end
fprintf('\nfinished calculating!\n');
%}


% blur/filter energy to avoid video compression artifacts

%avgEnergy = filter2(fspecial('average',5),avgEnergy);
%avgEnergy = medfilt2(avgEnergy,[3 3]);
avgEnergy = filter2(fspecial('gaussian',3),avgEnergy);


figure(3);
imshow(avgEnergy, []);
colormap hot;

%figure(13);
%imshow(energy, []); % show the energy for just the last y slice
%colormap hot;
clear energy;
clear img;


summedArea = calcSummedArea(avgEnergy);

figure(4);
imshow(summedArea, []);
saveas(4,sprintf('summedArea%i.png',iter));

clear avgEnergy;

seam = findSeam(summedArea);

clear summedArea;

figure(3);
hold on;
%for i = 1 : width
%    plot(seam(i),i);
%end
plot(seam, [1:width], '-c');
saveas(3,sprintf('avgEnergy%i.png',iter));
hold off;

% let's remove the ribbon!
for i = 1 : width
    % mask out our ribbon in the data matrix
    videoData(:,i,seam(i),:) = 0;
end
clear seam;
% remove it now!
%{
                                           % start as  y x t c
videoData = permute(videoData, [3 1 2 4]); % now we're t y x c
videoData(videoData == 0) = [];            % collapse (in t dim)
numFrames = numFrames - 1;
videoData = reshape(videoData, [numFrames height width 3]);
videoData = permute(videoData, [2 3 1 4]); % back to  y x t c
%}
%%{
fprintf('Collapsing video data...\n');
numFrames = numFrames - 1;
dot = floor(numFrames / 50);
for t = 1 : numFrames
    %fprintf('\tframe %i of %i\n', t, numFrames);
    if (mod(t,dot) == 0) 
        fprintf('.');
    end
    %{
    for x = 1 : width
        for y = 1 : height
            if (videoData(y,x,t,1) == 0 & videoData(y,x,t,2) == 0 & videoData(y,x,t,3) == 0)
               videoData(y,x,t,:) = videoData(y,x,t+1,:);
               videoData(y,x,t+1,:) = 0;
            end
        end
    end
    %}
    frame = squeeze(videoData(:,:,t,:));
    frame1 = frame;
    frame2 = squeeze(videoData(:,:,t+1,:));
    frame1(frame==0) = frame2(frame==0);
    frame2(frame==0) = 0;
    videoData(:,:,t,:) = frame1;
    videoData(:,:,t+1,:) = frame2;
end
clear frame1;
clear frame2;
clear frame;
videoData = videoData(:,:,1:numFrames,:);
fprintf('\nfinished collapsing!\n');
%}

% this was to test editing our video data to see if changes copied back okay
% videoData(10:40,10:40,:,:) = 0;
% videoData(yslice - 1,:,:,:) = 0;
% videoData(yslice + 1,:,:,:) = 0;

% copy our video data back into a playable movie format
fprintf('Packing video data for output...\n');
videoData = permute(videoData, [1 2 4 3]);
resFrames = size(videoData,4);
clear mov2;
for i = 1 : resFrames
    mov2(i) = movi;
    mov2(i).cdata = videoData(:,:,:,i);
end
fprintf('finished packing!\n');

% MATLAB seems to playback avi's funkily sometimes
%figure(666);
%movie(mov2,1,24);

outputStr = sprintf('output%i.avi', iter);
movie2avi(mov2, outputStr);
%!output.avi

videoData = permute(videoData, [1 2 4 3]);

toc

end

