pp = dir('train_fisher/');
testdir = dir('test_fisher/');

cd train_fisher;


numclass = 10;

names = zeros(size(pp,1)-2,15);
for i = 1: size(pp,1)-2
  names(i,:) = pp(i+2).name;
end
names = char(names);

imdim = size(imread(names(5,:)));

cimg = zeros(imdim(1)*imdim(2),size(names,1));
for i = 1:size(names,1)
  timg = imread(names(i,:));
  cimg(:,i) = timg(:);
  
end
%%loaded training set

cd ../test_fisher;

namest = zeros(size(testdir,1)-2,15);
for i = 1: size(testdir,1)-2
  namest(i,:) = testdir(i+2).name;
end
namest = char(namest);

testimg = zeros(imdim(1)*imdim(2),size(namest,1));
for i = 1:size(namest,1)
  timg = imread(namest(i,:));
  testimg(:,i) = timg(:);
  
end
%%loaded test
cd ..


%%%%%%%%%%% TRAINING %%%%%%%%%%%%%%%%%%%%

meanimg = mean(cimg')';

dimg = zeros(size(cimg));
for i = 1:size(cimg,2)
  dimg(:,i) = cimg(:,i) - meanimg;
end
%%%dimg is the normalized images

[U,S,V] = svd(dimg,0);


%%%ignore the first 4 which are light variation indicators
%P = U(:,5:13);
P = U(:,1:9);

%%get the weights of all the training examples
trainimg_wt = P'*dimg;

%label = kmeans(trainimg_wt',numclass);
label = meshgrid(1:10,1:19);
label = label(:);

%%%%%%%% get the classes in our 9d space
lcent  = zeros(9,numclass);

for i = 1:numclass
  lcent(:,i) = mean(trainimg_wt(:,(label == i))')';
end

%%%%% TEST SET STARt%%%%%%%%%%%%%%


mtestimg = mean(testimg')';

dtestimg = zeros(size(testimg));
for i = 1:size(testimg,2)
  dtestimg(:,i) = testimg(:,i) - mtestimg;
end



testimg_wt = P'*dtestimg;

%keyboard
dist = zeros(size(lcent,2),size(testimg_wt,2));
for i = 1:size(lcent,2)
  for j = 1:size(testimg_wt,2)

    dist(i,j) = sqrt(sum((testimg_wt(:,j)-lcent(:,i)).^2));

  end
end

[~,b] = min(dist);
% b is predicted labels of the test set
lshap = reshape(b,[26,10])
slabel = reshape(label,[19,10]);
mlsha = padarray(median(slabel),[25,0],'replicate','post');
floor(mlsha);
%    mlsha = meshgrid(1:10,1:26);
err = sum(sum(lshap ~= mlsha))
sum(sum(slabel ~= mlsha(1:19,:)))

