%
% WAVELET_DIST Computes the wavelet distance between signals and enrolled
%   templates.
%
% wdist = wavelet_dist(signal,template,threshold)
%
% Author Adrian Chan
%
% Wavelet disance was used for ECG biometrics as described in:
%
% Chan ADC, Hamdy MM, Badre A, Badee V, "Wavelet distance measure for
% person identification using electrocardiograms", IEEE Transactions on
% Instrumentation and Measurement, vol. 57, no. 2, pp. 248-253, 2008.
%
% Inputs
%    signal: ECG that need to be identified (each column is a signal)
%    template: enrolled ECGs (each column is a signal)
%    threshold: tau value (eq. 3 in reference) that is used to remove
%       relatively small wavelet coefficients.
%
% Outputs
%    wdist: wavelet distance (each row corresponds to a signal, each column
%       corresponds to the template; person in row i should be identified
%       as the person associated with column j, where entry (i,j) is the
%       smallest value in row i.
%
% Modifications
% 13/02/05 AC First created.
function wdist = wavelet_dist(signal,template,threshold)

if nargin < 3, threshold = 0.25; end

Nsignal = size(signal,2); % length of ECG signals
Nsample = size(signal,1); % number of signals to test (number of signal to identify)
Ntemplate = size(template,2); % number of templates (number of people enrolled)

wdist = zeros(Nsignal,Ntemplate); %

A = zeros(Nsignal,Ntemplate);
B = zeros(Nsignal,Ntemplate);
e = zeros(Nsignal,Ntemplate);

for i = 1:Nsignal
    w = 'db3';
    for j = 1:Ntemplate
        [ct,L]=wavedec(template(:,j),5,w);
        [cs,L]=wavedec(signal(:,i),5,w);

        index = (L(1)+1):length(ct);
        cs = cs(index);
        ct = ct(index);
        
        wdist(i,j) = sum(abs(ct-cs)./max(abs(cs),threshold));
    end
end

