% Third Implementation (Comparison Subprogram)
% May 29-31, 2007
% (c) 2007 Christopher Mitchell
% All rights reserved

% First we need to load a bunch of images from file.
% Load them from the preexisting training file
load eigenCells eigenCells
[count] = size(eigenCells,1);

% first, input a file and pack into a vector
file =  input('Enter a filename to test:','s');
RGB9 =  imread(file);
RGB9 = RGB9./(max(max(RGB9))-min(min(RGB9)));
RGB9 = RGB9 - min(min(RGB9));
[dimY,dimX] = size(RGB9);
RGB9v = zeros(1,dimY*dimX);
for i = 1:dimY
    for j = 1:dimX
        RGB9v(1,((i-1)*dimX)+j) = RGB9(i,j);
    end
end

% now, transform from image space to face space
cellMatch = zeros(count);
for i=1:count
    cellMatch(i) = inner(RGB9v,eigenCells(i,:));
end
disp('EigenVector for this image:');
disp(cellMatch(:,1));

% next, convert back into image space
RGB9v2 = zeros(1,dimY*dimX);
for i=1:count
    RGB9v2 = RGB9v2 + cellMatch(i)*eigenCells(i,:);
end

%finally, find the mean-squared error between original and this image
MSE = sum(((RGB9v2-min(min(RGB9v2)))/(max(max(RGB9v2))-min(min(RGB9v2)))-RGB9v).^2);
disp('Mean squared error:');
disp(MSE);
RGB92 = zeros(dimY,dimX);
for i = 1:dimY
    for j = 1:dimX
        RGB92(i,j) = RGB9v2(1,j+dimX*(i-1));
    end
end
figure
imshow(RGB9);
figure
imshow((RGB92-min(min(RGB92)))/(max(max(RGB92))-min(min(RGB92))));
disp('Program termination (normal): completed.');
