function ola( filePath, fileName )
%--------------------------------------------------------------------------
% OverLap Add
%
% Cooper Baker - 2014
%--------------------------------------------------------------------------

close all;

% Settings
%--------------------------------------------------------------------------
grainSize     = 1024;
overlap       = 4;
stretchFactor = 2;
window        = hann( grainSize, 'periodic' );
tag           = 'ola';

% Initializations
%--------------------------------------------------------------------------
if any( exist( 'fileName' ) ~= 1 )
    [ fileName, filePath ] = uigetfile( '*.wav', 'Audio File' );
end

grainHopSize   = ( grainSize / overlap ) / stretchFactor;
stretchHopSize = grainSize / overlap;
[ input, sr ]  = audioread( [ filePath, fileName ] );
input          = [ zeros( grainSize, 1 ) ; input ; zeros( grainSize - mod( length( input ), grainHopSize ), 1 ) ];
output         = [ zeros( length( input ) * stretchFactor + ( grainSize / 2 ), 1 ) ];
grainIndex     = 0;
grainMax       = length( input ) - grainSize;
stretchIndex   = 0;

% create progress bar dialog box
bar = waitbar( 0, '0%', 'Name', sprintf( '%s: processing %s...', mfilename, fileName ) );

% Processing Loop
%--------------------------------------------------------------------------
while grainIndex < grainMax
    
	% randomize input grain location within hop to mitigate robotization
    grainRand = grainIndex + randi( grainHopSize );

    grain = input( grainRand + 1 : grainRand + grainSize ) .* window;

    % write grain to output buffer
    output( stretchIndex + 1 : stretchIndex + grainSize ) = output( stretchIndex + 1 : stretchIndex + grainSize ) + grain;

    % increment grain indices
    grainIndex = grainIndex + grainHopSize;
    stretchIndex = stretchIndex + stretchHopSize;

    % update the progress bar
    progress = ( grainIndex / grainMax );
    waitbar( progress, bar, sprintf( '%2.3f%%', progress * 100 ) )
end

% close progress bar dialog box
close( bar );

% Output
%--------------------------------------------------------------------------
% crop output buffer
output = output( grainSize + 1 : length( output ) );

% normalize output
normCoeff = 1 / max( abs( output ) );
output    = output * normCoeff;

% make comments for file
commentString = sprintf( 'WinSize: %.0f,\nOverlap: %.0f,\nStretch: %.2f,\nWindow: %s', grainSize, overlap, stretchFactor, 'Hann' );

% save output to file
% write audio file to disk
[ a, fileName, b ] = fileparts( fileName );
outFile = sprintf( '%s.%s.wav', fileName, tag );
audiowrite( outFile, output, sr, 'BitsPerSample', 32, 'Artist', 'NormCoeff', 'Title', num2str( normCoeff ), 'Comment', commentString );

% plot output
timevector = linspace( 0, length( output ) / sr, length( output ) );
plot( timevector, output );

% EOF
