% Matlab code to verify the recovered DTMF sequences
% Usage: [recovered_DTMF,recovered_index] = decode_DTMF(y, y_index,subject,condition)
% Bowon Lee 08/19/2004
% Modified for speech and hearing science data collection 11/22/2004


function [recovered_DTMF,recovered_index] = decode_DTMF(y, y_index,subject)

K = length(y);
Fs = 48000;
M = 4;

k = 2;

while k <= K
    buff = fliplr(y(max(1,k-M):(k-1)));
    a = 0;
    n = 1;
    for m=1:min(k-1,M)
        if strcmp(y(k),y(k-m)) & ~strcmp(y(k),'#')
            a(n) = m;
            n = n + 1;
        end
    end
%    if a ~= 0 & buff ~= '#154'
    if a ~= 0 & ~strcmp(buff,'#154')
        if length(a) > 1
            a = a(end);
        end
        y(k-a) = '#';
        y = [y(1:k-a),y(k:end)];
        y_index = [y_index(1:k-a),y_index(k:end)];
%        disp(sprintf('[%s, %d] %s: %s',y(k),a,buff,y));  % Test
%        pause;  %Test
    end
    k = k + 1;
    K = length(y);
end

k = 2;
while k <= K
    if y(k) == y(k-1)
        y = [y(1:k-2),y(k:end)];
        y_index = [y_index(1:k-2),y_index(k:end)];
    end
    k = k + 1;
    K = length(y);
end

n = 1;
k = 1;
while k < K
    if y(k) == '#'
%        disp_txt = sprintf('Detected a pause...');
%        disp(disp_txt);
        if n > 1
            recovered_index((n-1),2) = y_index(k);        
        end
    else
%        disp_txt = sprintf('Detected %s...',y(k));
%        disp(disp_txt);     
        recovered_DTMF(n) = y(k);
        recovered_index(n,:) = [y_index(k), y_index(k+1)];
        n = n + 1;
    end
    k = k + 1;
end
