function Y=ksloop(f,length, fs, excitation, B, A)
%Karplus-Strong model withfancy new loop filter
%   ks(f,length) 
%   f=frequency
%   length=time (seconds)
%   fs = sampling freqency
%   excitation=string excitation signal
%   B = numerator coefficients of loop filter
%   A = denominator coefficients of loop filter


fs=44100;

N=fix(fs/f);

%modify length of excitation signal to match desired duration
if(max(size(excitation)) <= length*fs)
  X = [excitation zeros(1,length*fs - max(size(excitation)))];
else
  X = excitation(1:length*fs) ;
end


hnum = B;
hden = A;

%lagrange interpolation filter to account for fractional delay
% (keeps the string in tune with the desired frequency)
l=lagrange(3,f/fs);

%     Hd(z)L(z)z^-N               
b1=[zeros(1,N) conv(l, hden)];

%                Hd(z) - Hn(z)L(z)z^-N
a1=[hden zeros(1,N-max(size(hden))) -1*conv(hnum,l)];

%no initial conditions
y=filter(b1,a1,X);

Y = y;
