function autoalign(foldername)
% AUTOALIGN aligns audio in folder with selected file by inserting zeros
%  at the start of the files. 
%
% by Brecht De Man at Centre for Digital Music on 17 November 2014

    % error('Work in progress, function not finished'); % while unfinished
    
    tic;                                % start measuring time
    list = dir([foldername '/*.wav']);  % get names of files
    
    % remove hidden files from list
    % see http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/258220
    for k = length(list):-1:1
        fname = list(k).name;
        if fname(1) == '.'
            list(k) = [ ];
        end
    end
    
    shiftvec = zeros(length(list), 1); 
    
    % first file: 
    masterAudioChannels = audioread([foldername '/' list(1).name]); % read file
    masterAudio         = sum(masterAudioChannels, 2); % sum to mono
    
    % for each other file:
    for i = 1:length(list)
        slaveAudioChannels = audioread([foldername '/' list(i).name]); % read file
        slaveAudio         = sum(slaveAudioChannels, 2); % sum to mono
        
        % check sampling rate is the same (or: express in terms of seconds)
        % ... 
        
        % crosscorrelation function
        [xc, timeaxis] = xcorr(masterAudio, slaveAudio);
        [value, lag] = max(abs(xc));
        shiftvec(i) = timeaxis(lag);
        
        % debugging plots
%         figure;
%         title(['Crosscorrelation file 1 vs ' num2str(i)]);
%         subplot(2,1,1);
%         plot(timeaxis, xc);
%         xlabel('Samples');
%         ylabel('Crosscorrelation');
%         subplot(2,1,2);
%         plot(timeaxis, abs(xc));
%         xlabel('Samples');
%         ylabel('Absolute value of crosscorrelation');
        
        % monitoring/debugging
        
    end
    
    % add absolute of largest negative lag worth of zeros to all; 
    % then add 'shiftvec' value to that
    maxlag = min(shiftvec); 
    for i = 1:length(list)
        [audio, fs] = audioread([foldername '/' list(i).name]);
        audiowrite([foldername '/SHIFT' list(i).name], ... % remove SHIFT
            [zeros(-maxlag + shiftvec(i), size(audio, 2)) ; audio], ...
            fs, 'BitsPerSample', 24);
    end

    elapsedTime = toc;  % stop measuring time
    disp(['autoalign took ' num2str(elapsedTime) ...
        ' seconds to align the files in folder ' foldername]);

end