% Compute the segmental energy
%
% function energy = segmentalEnergy(data, windowlength)
%
% data = vector of samples (N by 1)
% Typically windowlength = 256 for 8 kHz samples
%                    512 for 16 kHz samples
%
% energy = a vector of energy values. 
%   Each value is obtained by summing the squares of (data(x:x + windowlength - 1) .* hammingwindow)
%   We calculate one value, shift the window of (.5 * windowlength) then calculate the next value.
%
% by Guillaume LATHOUD at IDIAP (lathoud@idiap.ch)

function energy = segmentalEnergy(data, windowlength)
    
    data = data';
    energy = [];
    half = floor(windowlength/2);
    window = 0.54 + 0.46 * cos(2 * pi * (-half : -half + windowlength - 1) / windowlength); % Hamming

    l = length(data);

    for i=1:half:l
        
        j = min(i + windowlength - 1, l);   % for the last (incomplete) frame
        
        if j-i < windowlength - 1       % for the last (incomplete) frame
            windowlength = j-i+1;
            window = 0.54 + 0.46 * cos(2 * pi * (-half : -half + windowlength - 1) / windowlength); % Hamming
        end
        
        energy = [energy sum( (data(i:j) .* window) .^ 2)];
        
    end
    