function [ oClass MeanArr ConfHist vSError] = BlockClassification( imBlock, nDictionary )
%--------------------------------------------------------------------------
% This function returns the result of classification using Matching Persuit
% Algorithm
% oClass    : result of classification
% Mean Arr  : Mean of inner product regarding classes of dictionary
% ConfHist  : Histogram of classification confidence
% vSError    : Classification Error calculated from the difference between a query and the best matched element. 

% Last mofification: 20 January 2013  
% Programmed by Thirapiroon Thongkamwitoon 
% Communications and Signal Processing Research Group
% Department of Electrical and Electronic Engineering
% Imperial College London, South Kensington Campus, London SW7 2AZ
%
% Email : tt1410@imperial.ac.uk, thirapiroon@yahoo.com 
%-------------------------------------------------

%-- read the number of elements
NumOfDict=size(nDictionary,1);


% Read the block of input image - imBlock  

% Iterations every horizontal line of block
 TotalRows=size(imBlock,1);
 TotalCols=size(imBlock,2);

 
 
for i=1:TotalRows
    

X=double(imBlock(i,:));  % Read each line 


% Interpolation by 4 in order to increase resolution 
%--------------------------------------------------------
ti=1/4:1/4:TotalCols; 
Xi = interp1(1:TotalCols,X(1:TotalCols),ti,'spline'); %'linear'); --slow?

%--------- Calculate derivative --------------

Y=diff(Xi);
Y(size(Xi,2))=0;
Y=abs(Y)/norm(Y);  % Flip graph 

%========== Projection =============

%---- loop for 8 dictionaryies ------
for k=1:NumOfDict
 DicProjection(k,:)= squeeze(nDictionary(k,:,:))*Y';
end

for k=1:NumOfDict
[MaxDic(k) IDic(k)]=max(DicProjection(k,:));
end
%--------------------------------------

MaxCandidate(i,:)= MaxDic(:); % collect in order to find average 


[ClassMax ClassI]=max(MaxCandidate(i,:));
%------ mean -------------
ClassResult(i)=ClassI; % Classification result for the line i

%------------- Compute Error -----------------
MatchedKernel=squeeze(nDictionary(ClassI,IDic(ClassI),:))';
vSError=sum((Y-MatchedKernel).^2);

end

%=========== Show results ===========================
format long;

%------------------------------------------------
%   Active when using the result from maximum mean of projections 
%   Change result to IClassFromMean
 MaxMeanArray=100*mean(MaxCandidate);
[ClassFromMean IClassFromMean] = max(MaxMeanArray); 
%-------------------------------------------------

ConfHist=hist(ClassResult,1:NumOfDict);  % Histogram over 1 block
[MaxConf oClass] = max(ConfHist);  % This case, classification by confidence
MeanArr=MaxMeanArray;

end

