function [ output_args ] = normSounds ( functionSelection, fileFolder)

if ~(exist('functionSelection','var'))
    fprintf('Usage: normSounds(''function'',''foldername'')\nUse ''norm'' for RMS normalization and level adjustment to 75%%,\nor ''fade'' for a 50 ms fade in and fade out, or ''all'' for RMS\nnormalization and fade in and out.\nIf no folder name is defined, the current file folder will be\nused. Files will be saved in a new name, with the selected\nfunction as amendment to the file name.\n');
    return
end

if ~(exist('fileFolder','var'))
    fileFolder = '';
end

fileNames = dir(horzcat(fileFolder,'*.wav'));
listofRMS = [];
listofnewRMS = [];
listofMaxes = [];
listofnewMaxes = [];
Fs = 44100;

soundFiles = readFiles( fileFolder, fileNames );

switch lower(functionSelection)
    case 'norm'
        normalizedSounds = normalizeSounds( soundFiles );
        saveFiles( functionSelection, normalizedSounds, Fs, fileFolder, fileNames );
    case 'fade'
        fadedSounds = fadeSounds ( soundFiles, Fs );
        saveFiles( functionSelection, fadedSounds, Fs, fileFolder, fileNames );
    case 'all'
        normalizedSounds = normalizeSounds( soundFiles );
        fadedSounds = fadeSounds ( normalizedSounds, Fs );
        saveFiles( functionSelection, fadedSounds, Fs, fileFolder, fileNames );
end

end

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

end

function [ normalizedSounds ] = normalizeSounds ( soundFiles )

% Check RMS values
for i=1:length(soundFiles)
    % Get original RMS and max values
    listofRMS(i) = [sqrt(mean(soundFiles{i}.^2))];
    listofMaxes(i) = [max(abs(soundFiles{i}))];
    % Get max RMS and create a vector of RMS factors
    maxRMS = max(listofRMS);
    factorRMS = (maxRMS./listofRMS);
end

% Adjust RMS values using the RMS factor vector and read out new max values
for i=1:length(soundFiles)
    adjustedToRMS{i} = soundFiles{i}.*(factorRMS(i));
    listofnewMaxes(i) = [max(abs(adjustedToRMS{i}))];
    listofnewRMS(i) = [sqrt(mean(adjustedToRMS{i}.^2))];
end

% Get max value
maxLevel = max(listofnewMaxes);
setLevel = .5;

% Adjust to .75 (i.e. 75% of max sound level), attenuate saturated sounds,
% amplify less strong sounds (adjusting after peak values)
maxlevelAdjust = (setLevel/maxLevel);
for i=1:length(soundFiles)
    normalizedSounds{i} = adjustedToRMS{i}.*maxlevelAdjust;
end

end

function [ fadedSounds ] = fadeSounds ( soundFiles, Fs )

% Fade in and out
for i=1:length(soundFiles)
    fadeTime = 50; % Sets fade time in milliseconds
    
    % Create fade time, and up and down ramps
    timeVector = (0:Fs*(fadeTime/1000))*(1/Fs);
    sin2factor = (.25/fadeTime)*1000;
    upRamp = 1*(sin(pi*2*sin2factor*timeVector) .* sin(pi*2*sin2factor*(timeVector)));
    
    % Create and apply amplitude envelope
    originalGain = ones(1,length(soundFiles{i})-(length(upRamp)*2));
    soundEnvelope = [upRamp originalGain fliplr(upRamp)]';
    fadedSounds{i} = soundFiles{i}.*soundEnvelope;
end

end

function [] = saveFiles ( functionSelection, processedSounds, Fs, fileFolder, fileNames )

switch lower(functionSelection)
    case 'norm'
        soundProcessing = 'RMSnormaliztion';
    case 'fade'
        soundProcessing = '50ms_fades';
    case 'all'
        soundProcessing = 'RMSnormaliztion_&_50ms_fades';
end
% Save audiofiles
for i=1:length(fileNames)
    temp = (fileNames(i).name);
    actualName = temp(1:(length(temp)-4));
    newfileName = horzcat(actualName,'_',fileFolder,soundProcessing,'.wav');
    audiowrite(newfileName, processedSounds{i}, Fs);
end

end

