function [clabel, err_rate] = mdist_classify(centers, ulabel, tdata, tlabel)
% classification using minimum-distance classifier
% input: class centers (DxJ) and their corresponding labels (Jx1)
%        testing data (DxN) and testing label (if available)
% output: class labels (Nx1) and error rate (if available)
% 2008-04-21, xlx@ee.columbia.edu

if nargin<4, tlabel=[]; end

[d, n2] = size(tdata);
un = length(ulabel);

t2 = sum(tdata.^2, 1)';
u2 = sum(centers.^2, 1)';
dist = t2*ones(1,un) + ones(n2,1)*u2' - 2*tdata'*centers;

[md, mi] = min(dist, [], 2);
clabel = ulabel(mi(:));

if ~isempty(tlabel)
    err_rate = sum(clabel~=tlabel)/n2 ;
else 
    err_rate = -1.0;
end