function [y rmsbuff] = holtcomp(x, CT, CS, at, rt)
%HOLTCOMP is derived from M-file 4.2 from DAFX Second Edition
% original code by M. Holters
% edited by McLean Pierce
% commented by D CUTHBERTSON

tav=0.01; % time averaging variable

% attack_time=0.03;
% release_time=0.003;
delay=150;

xrms=0; % sets xrms to 0 for first sample
g=1; % sets g to 1
buffer=zeros(1,delay); % delay compensating buffer for x
rmsbuff=zeros(1,delay); % buffer for storing rms values

for n=1:length(x)
    xrms=(1-tav)*xrms+tav*x(n)^2; % calculates the time averaged rms value of x
    rmsbuff=[xrms rmsbuff(1:end-1)]; % vector of rms values stored
    X=10*log10(xrms); % calculates dB rms of x in dB
    G=min([0,CS*(CT-X)]); % calculate the gain reduction in dB 
    f=10^(G/20); % returns the gain factor to magnitude
    if f < g
        coeff=at; % if the gain factor is less than 1, use at for smoothing
    else
        coeff=rt; % if the gain facotr is = or > 1, use rt for smoothing 
    end;
    
    
    g=(1-coeff)*g+coeff*f; % applies the smoothing coefficient 
    y(n)=g*buffer(end); % returns output by multiplying delayed x by g
    buffer=[x(n) buffer(1:end-1)]; 
    


end

