% A Matlab function to detect DTMF tone
% Usage: [y, y_index] = detect_DTMF(subject,condition);
% Created by Bowon Lee 08/18/2004

function [y, y_index] = detect_DTMF(subject,condition)

filename = sprintf('../%s/Track-1-%s-%s.wav',subject,subject,condition);
fprintf('Loading %s...\n',filename);
[inputWave, Fs] = wavread(filename);

L = length(inputWave);

windowSize =  64;
hopSize = 32;

threshold = .0001;
energy_threshold = 1;

n_begin = 480;
n_end = L;
tone_interval = [-ceil(.01*Fs):(ceil(0.11*Fs)-1)]';
tone_length = length(tone_interval);

n = n_begin;
k = 1;

figure(1);
DTMF_tone_energies = 0;
while n < (L-tone_length-windowSize)
    chunk = inputWave(n:(n+windowSize-1));
    chunk_sq = chunk.^2;
    if max(chunk_sq) > threshold
        t_begin = (n-1)/Fs;
        Fx = gradient(chunk_sq);
        [t_max, nOnset] = max(Fx);
        onsetTime(k) = t_begin + nOnset/Fs;
        DTMF_tone = inputWave(n+nOnset+tone_interval);
        DTMF_tone_energy = sum(DTMF_tone.^2);
	DTMF_tone_energies = [DTMF_tone_energies;DTMF_tone_energy];
%        DF = diff(DTMF_tone(501:1500));   
        if DTMF_tone_energy > energy_threshold % & length(find(abs(DF) > 0.01)) > 550
            y(k) = dtmfdet(DTMF_tone,Fs);
            t = t_begin + [0:(tone_length-1)]/Fs;
            plot(t,DTMF_tone);
            axis([t(1), t(end), -0.1, 0.1]);
            grid on;
            title(sprintf('Detected tone is %s',y(k)));
%            title(sprintf('Detected tone is %s, Zero Crossing is %d times',y(k),length(find(abs(DF) > 0.01))));            
            drawnow;
            if (y(k) == 'A') | (y(k) == 'B') | (y(k) == 'C') | (y(k) == 'D')
%               disp(sprintf('Not a valid tone...'));
                disp_text = sprintf('Onset appears at time %.3f second: Unable to determine the detected tone.',onsetTime(k));
                disp(disp_text);
                n = n + 2 * tone_length;
            elseif (length(y(k)) == 1)    
                disp_text = sprintf('Onset appears at time %.3f second: Detected tone is %s.', onsetTime(k), y(k));
                disp(disp_text);
                y_index(k) = n + nOnset;   
                k = k + 1;
                n = n + 2 * tone_length;
%                pause;
            else 
            end
        end
    end
    n = n + hopSize;    
end

%plot(DTMF_tone_energies(1:1000));
%close(1);

disp(sprintf('Recovered sequence is %s',y));
K = length(y);
E_index = find(y == 'X');
for e=1:length(E_index)
    disp(sprintf('A part of sequence containing an error is [%s]',y(max(1,E_index(e)-4):min(K,E_index(e)+4))));
    C = input('Enter a valid DTMF tone (S to skip): ','s');
    if C == 'S'
        y = [y(1:(max(1,E_index(e)-1))) y(min(K,E_index(e)+1):end)];
        E_index(e+1:end) = E_index(e+1:end)-1;
    else
        y(E_index(e)) = C;
    end
end

filename = sprintf('../%s/%s_%s.mat',subject,subject,condition);
disp(sprintf('Saving time index file %s...',filename));
save(filename, 'y', 'y_index');
