function y = randomeffectproc(x,beats,fs)

% Written by Peregrin Chiara with audio effects functions adapted as below:
% 1. ringmod - from ...
% 2. iircomb - from DAFx ...
% 3. wah_wah - from ...
% 4. noisegt - from DAFx ...

% This function is optimised for audio loops and works particularly well for 
% percussive loops. This version takes a monaural input signal, stereo input 
% will be added in a future version.

% if you wish to run the function directly, uncomment the next 3 lines of code.
% [x,fs] = audioread('OGBK037.wav'); 
% beats = 16; % vary depending on loop length and subdivision sought 
% gate = 2;

% some optional preset gate times that might work for different beat subdivisions
% depending on the loop length. These are to be used or edited at the 
% discretion of the user.

% a gate creates more rhythmic separation between beats. 
% the gate ltrhold particularly may need to be adjusted.
% function y=noisegt(x,holdtime,ltrhold,utrhold,release,attack,a,fs)

beatlength = round(length(x)/beats); 
% round beatlength to an integer value. Due to round off errors this may 
% result in more or less samples than x. Residual samples are addressed below. 

hsr = dsp.SignalSource; % Create a signal source matlab object.
hsr.Signal = x; % % assign input to signal field of the SignalSource object.
hsr.SamplesPerFrame = beatlength; % specify samples per frame as equal to beatlength

idx = 1; % cyclical loop steps through each beat
while ~isDone(hsr);
    y(:,idx) = step(hsr); % step = beatlength  
    idx = idx+1;
end
release(hsr);

y = y(:,1:beats); % truncate columns larger than 'beats'.

for i = 1:beats
    effect = randi(9,1,1); % pseudo-randomly selected positive integer value
% to call each audio effect function for the total number of beats.

    switch effect;
        case 1
            y(:,i) = ringmod(y(:,i),600,0.7, fs);
        case 2
             y(:,i) = ringmod(y(:,i),1000,0.7, fs);
        case 3
             y(:,i) = ringmod(y(:,i),2000,0.7, fs);
        case 4
            y(:,i) = iircomb(y(:,i),31,0.7,fs);
        case 5
            y(:,i) = iircomb(y(:,i),63,0.7,fs); 
        case 6
            y(:,i) = iircomb(y(:,i),125,0.7,fs); 
        case 7
            y(:,i) = wah_wah(y(:,i),500,3000,750,fs);
        case 8
            y(:,i) = wah_wah(y(:,i),1200,3600,1500,fs);
        case 9
            y(:,i) = wah_wah(y(:,i),1000,3000,2000,fs);
    end
end

y = reshape(y,size(y,1)*size(y,2),1); % concatenate into single column