function stripzeros(foldername)
% STRIPZEROS strips off an array of samples that equal zero at the 
% beginning and end of an audio file. 
%
% by Brecht De Man at Centre for Digital Music on 17 November 2014

    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

    for i = 1:length(list) % go over each file in the folder
        [audio, fs] = audioread([foldername '/' list(i).name]);

        numSamples  = size(audio,1);
        numChannels = size(audio,2);
        bitDepth    = 24; % not automated here
        startIndex  = zeros(numChannels, 1);
        stopIndex   = zeros(numChannels, 1);

        % first and last non-zero elements (for all channels)
        for channel = 1:numChannels
            % ? more efficient way to find first and last non-zero sample?
            indexOfNonZeroSamples = find(audio(:,channel)); % returns indices non-zero elements
            startIndex(channel) = min(indexOfNonZeroSamples);
            stopIndex(channel)  = max(indexOfNonZeroSamples);
        end

        start = max(startIndex);
        stop  = min(stopIndex);

        % if startIndex and stopIndex are both equal to first and last sample: 
        % do nothing.
        % else: 
        if start>1 || stop<numSamples
            audiowrite([foldername '/' list(i).name], audio([start:stop], :), ...
                fs, 'BitsPerSample', bitDepth);
            % debugging/monitoring: 
            startCrop = (start-1)/fs; %
            stopCrop  = (size(audio,1)-stop)/fs;
            disp([num2str(startCrop) 's (start) / ' num2str(stopCrop) 's (end) stripped off ' list(i).name]);
        else
            disp(['Nothing stripped off ' list(i).name]);
        end

        
    end

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

end