function p4(nfaces, sfaces)

function f = standardize(faces) 
   mus = mean(faces,1);
   f = faces-repmat(mus,[size(faces,1) 1]);
   variances = diag(cov(f))';
   f = f./sqrt(repmat(variances,[size(faces,1) 1]));
end

function showFace(facevec)
  imagesc(reshape(facevec, [51 43]));
end;

function [score,idx] = recognize(face, candidates)

   fsub = repmat(face,[1 size(candidates,2)]);
   diff = fsub - candidates;
   dist = sqrt(sum(abs(diff).^2,1));

   [score,idx] = min(dist);

end;

% == main == 

nfaces = standardize(nfaces);
%showFace(nfaces(:,1));
%min(nfaces(:,1))
%hist(nfaces(:,2))

% == part b == 
sfaces = standardize(sfaces);
CORRECT = [];
for face_i=1:size(sfaces,2),
  [score,rec_idx]=recognize(sfaces(:,face_i),nfaces);
  if (face_i == rec_idx)
    CORRECT = [CORRECT face_i];
  end;
end;

CORRECT
size(CORRECT)

% == part c ==

meanface = mean(nfaces,2);
subplot(1,6,1);
showFace(meanface);
title('mean face');


[u s v] = svd((nfaces - repmat(meanface,[1 size(nfaces,2)])),0);
for f=1:5,
  eigenface = u(:,f);
  subplot(1,6,f+1);
  showFace(eigenface);
  title(sprintf('eigenface %d',f));
end;


plot(diag(s));


end