% Ronan O'Malley
% September 19th 2005
% delay_loop.m
% M Script that creates a multiple delay effect using a loop
% Possibility for extension:
%   - do calculations with sampling frequency to convert delay in samples into miliseconds (need 44.1kHz samples)
%   - exchange amplitude co-efficients and number of delays for a deterioration rate and shape
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% parameters to vary the effect %

% number of samples first delay is offset
% should be greater than 1000 to produce an audible effect
samp_delay = 2000;         

zero_padding = 10*samp_delay;   % length in samples of silence added to end of in-sample to hear the delays

no_delays = 10;      % number of delays to apply max of 1/dim


dim = 0.1;      % diminishing amplitude between subsequent delays, deterioration rate

infile='sample.wav';
outfile='out.wav';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if (no_delays>(1/dim))
    sprintf('ERROR: no_delays must be less than or equal to 1/dim!')
end

% read the sample waveform
[wave,Fs,bits] = wavread(infile);

% if this is a stereo sample
if(size(wave,2) == 2)
    wave=wave(:,1); % convert to mono (add this to all m files)
end


wave = vertcat([wave;zeros(zero_padding,1)]);    % add zero's to the end of the wave to hear trailing delays

out_wave = zeros(length(wave),1);       % create empty out vector

out_wave(1:(length(wave)))=wave;    % copy initial signal to an out signal


for j = 1:no_delays,            % calculate amplitudes
    amp(j) = 1-(j*dim);
end

% for each sample
for i = samp_delay:length(wave),
    %   for each delay
    for j = 1:no_delays,
         if(i>(j*samp_delay))   % causality
             if(amp(j)>0),     % no multiplying by negative amplitudes
                out_wave(i) = out_wave(i) + ((amp(j))*wave(i-(j*samp_delay)));    % add a delayed diminished sample
            end
        end
    end
end

% write output
wavwrite(out_wave,Fs,outfile);