function y = newlimit(x,lt,at,rt,fs) % name of the function

% function y = limiter(x, lt) 
% Author: M. Holters

TS = 1/fs;

delay = 5; % defines delay value to compensate sample delays 
xpeak = 0; % variables to provide infinite gain value.
g = 1; % setting up the gain value. 

buffer = zeros(1,delay); % buffer input sequence to smaller or larger frame size and creates an array of zeros
 
AT = 1 - exp((-2.2.*TS)./(at/1000)); %Set Attack Time

AR = 1 - exp((-2.2.*TS)./(rt/1000)); %Set Release Time

LT = 10.^(lt/20); %Set Limiter Threshold 


for n = 1:length(x) % identify the number of samples. 
  a = abs(x(n)); % telling matlab it's an absolute value and a complex magnitude
  if a > xpeak  % setting up the filter coefficient for the peak detection
    coeff = AT;
  else
    coeff = AR;
  end;
xpeak = (1-coeff) * xpeak + coeff * a;   % determine the level of peak detection (threshold)
f = min(1, LT./xpeak); % analyze the minimum values 

if f < g       % setting up the filter coefficients of the limiter. 
    coeff = AT;
  else
    coeff = AR;
  end;
g = (1-coeff) * g + coeff * f; % formula of the resulting gain 
y(n) = g * buffer(end); % multiply the gain value as a paramater and finish the input sequence
buffer = [x(n) buffer(1:end-1)]; % buffer the input sequence 
end;


