function [ output_args ] = checkResponseTime ( input_args )
clearvars;

fileFolder = '';
fileNames = dir(horzcat(fileFolder,'*.wav'));
[soundFiles, sampleFrequencies] = readFiles( fileFolder, fileNames );

responseTimes = [];

for i=1:length(fileNames)
    % Empty figure
    hold off;
    % Call functions
    [lengthAdjustedSoundFile, silencedSoundFile, Fs, responseTime] = readResponseTime(soundFiles{i}, sampleFrequencies{i});
    responseTimes = [responseTimes; i, responseTime];
    showSounds (lengthAdjustedSoundFile, silencedSoundFile, Fs, fileNames(i).name);
    playResponseSound(lengthAdjustedSoundFile, Fs);
end

writeToTextFile(responseTimes, fileNames)

end

function [ soundFiles, Fs ] = readFiles ( fileFolder, fileNames )
% Read wave files 
for i=1:length(fileNames)
    fileName = horzcat(fileFolder,fileNames(i).name);
    varname = strcat('x',num2str(i));
    [soundFiles{i}, Fs{i}] = audioread(fileName);
end

end

function [ ] = playResponseSound ( silencedSoundFile, Fs )
% Play silenced sound
soundPlayer = audioplayer(silencedSoundFile, Fs);
playblocking(soundPlayer);

end

function [ ] = showSounds ( soundFile, silencedSoundFile, Fs, fileName )
% Show original sound in blue and silenced in red
dt = 1/Fs;
t = 0:dt:(length(soundFile)*dt)-dt;
plot(t,soundFile,'b'); 
xlabel('Seconds'); 
ylabel('Amplitude');
title(fileName);
hold on;
plot(t,silencedSoundFile,'r');
end

function [ lengthAdjustedSoundFile, silencedSoundFile, Fs, responseTime ] = readResponseTime ( soundFile, Fs )
% Set sound to max amplitude
soundLevelFactor = 1/max(abs(soundFile));
soundFile = soundFile.*soundLevelFactor;

% Set threshold between silence and speech to RMS of sound file
thresHold = rms(soundFile);

% Check sound in 100ms sized chunks
chunkSize = round(Fs/100);
% Make sound of equal length as multiple of chunks by adding 0s in the
% end
lengthAdjustedSoundFile = [soundFile; zeros((abs(length(soundFile)-round(length(soundFile)/chunkSize)*chunkSize)),1)];
% Compare chunks to threshold
chunkComparison = [];
for i=1:length(lengthAdjustedSoundFile)/chunkSize
    tempChunkLevel = 0;
    for j=1+i*chunkSize-chunkSize:i*chunkSize
        if lengthAdjustedSoundFile(j) > thresHold
            tempChunkLevel = tempChunkLevel+1;
        end
    end
    chunkComparison = [chunkComparison, tempChunkLevel];
end

% Select wanted chunks
wrap = [0, chunkComparison, 0];
temp = diff(wrap ~= 0);
blockStart = find(temp == 1) + 1;
blockEnd = find(temp == -1);
blocksOfValues = arrayfun(@(bId) wrap(blockStart(bId):blockEnd(bId)), 1:numel(blockStart), 'UniformOutput', false);
[maxValue,maxPosition] = max(cellfun(@length,blocksOfValues));

% Set start sample for removing unwanted chunks
startSample = (blockStart(maxPosition)*chunkSize)-chunkSize*100;

% Set unwanted chunks to silence
silencedSoundFile = lengthAdjustedSoundFile;
silencedSoundFile(1:startSample) = 0;

% Count samples until soundlevel reaches threshold
samplesCounted = 0;

for i=1:length(silencedSoundFile)
    if (silencedSoundFile(i) < thresHold)
        samplesCounted = samplesCounted+1;
    else
        break;
    end
end

% Fine trim unwanted sounds
for i=1:samplesCounted
    silencedSoundFile(i) = 0;
end

% Calculate response time
responseTime = samplesCounted/Fs;
end

function [ ] = writeToTextFile( responseTimes, fileNames )

pos1 = 'Number';
pos2 = 'Sound file';
pos3 = 'ResponseTime (s)';
allData = [pos1, '\t', pos2, '\t', pos3, '\n'];

for i=1:length(fileNames)
    pos1 = num2str(responseTimes(i,1));
    pos2 = fileNames(i).name;
    pos3 = num2str(responseTimes(i,2));
    allData = [allData, pos1, '\t', pos2, '\t', pos3, '\n'];
end

% Create filename using date and time
dateForRunningCheck = datestr(now, 'dd-mmmm-yyyy_HH-MM');
filename = strcat('Responsetimes', dateForRunningCheck, '.txt');
fid = fopen(filename, 'w');
% Write to file
fprintf(fid, allData);

close all;
end