function out = derive_speech_rate(y, fs, desc)

% out = derive_speech_rate(y, fs, desc)
% 
% This function calculates some characteristics related to the speech rate
% and pausing.
% 
% y             - input column vector
% fs            - sampling frequency
% desc          - description of text to parse
% 
% out.TST       - Total Speech Time (TST) [seconds]
% out.NST       - Net Speech Time (NST) [seconds]
% out.TPT       - Total Pause Time (TPT) [seconds]
% out.TSR       - Total Speech Rate (TSR) [phonemes per second]
% out.NSR       - Net Speech Rate (NSR) [phonemes per second]
% out.TPT_50    - Total Pause Time (TPT)(> 50 ms) [seconds]
% out.AR        - Articulation Rate (AR) [phonemes per second]
% out.SPIR      - Speech Index of Rhytmicity (SPIR) [number per minute]
% 
% Implemented according to
% S. G. Fletcher, "Time-by-count Measurement of Diadochokinetic Syllable
% Rate," J Speech Hear Res, vol. 15, no. 4, pp. 763–70, 1972.
% 
% S. Skodda, H. Rinsche, and U. Schlegel, "Progression of Dysprosody in
% Parkinson's Disease Over Time - A Longitudinal Study," Movement
% Disorders, vol. 24, p. 716–22, 2009.
% 
% A. M. Goberman, "Correlation between Acoustic Speech Characteristics 
% and Non-speech Motor Performance in Parkinson Disease," Med Sci Monit, 
% vol. 11, no. 3, pp. CR109–16, 2005.

%% Paths and variables
win_len = 0.010;

%% Get harmonicity
hnr = praat_harmonicity(y, fs, win_len, 75, 0.1, 1);
hnr(hnr > -200)  = 1;
hnr(hnr <= -200) = 0;

%% Get the statistics about pauses
sp_brd = [1; (find(hnr(1:(end - 1)) - hnr(2:end)) + 1); length(hnr) + 1];
sp_val = hnr(sp_brd(1:(end - 1)));
sp_len = sp_brd(2:end) - sp_brd(1:(end - 1));

length_pauses = sp_len(sp_val == 0);

%% Delete the non-phoneme characters
desc = regexprep(desc, '\W', '');

%% Calculate the basic characteristics
%  1. Calculate Total Speech Time (TST)
out.TST = length(y)/fs;

%  2. Calculate Net Speech Time (NST)
out.NST = sum(hnr > 0)*win_len;

%  3. Calculate Total Pause Time (TPT)
out.TPT = out.TST - out.NST;

%% Calculate the speech rates and pausing
%  1. Calculate the Total Speech Rate (TSR)
out.TSR = length(desc)/out.TST;

%  2. Calculate the Net Speech Rate (NSR)
out.NSR = length(desc)/out.NST;

%  3. Calculate the Articulation Rate (AR)
n_frames_50 = ceil(0.050/win_len);
paus_50     = length_pauses(length_pauses >= n_frames_50);

if (length(paus_50) > 1)
    out.TPT_50 = sum(paus_50)*win_len;
    out.AR     = length(desc)/out.TPT_50;
else
    out.TPT_50 = inf;
    out.AR     = inf;
end

%  4. Calculate the Speech Index of Rhytmicity (SPIR)
if (length(paus_50) > 1)
    out.SPIR = length(paus_50)/(60*out.TST);
else
    out.SPIR = inf;
end