function snd = drum_KS(amplitude, b, p, wavetable_type, envelope)
% DRUM_KS: Generate drum sound based on Karplus-Strong algorithm.
%
%   Notation:
%     snd = drum_KS(amplitude, b, p, wavetable_type, number_of_samples)
%
%   Defaults:
%     amplitude: volume of output sound (default = 1)
%     b: blend factor (default = 0.5)
%     p: length of wavetable (default = 200)
%     wavetable_type: type of wavetable (default = 'r')
%       'r' = random
%       'c' = constant
%       's' = sine
%     envelope: amplitude envelope (default = ones(1,8000))
%
%   Notes: 
%     To increase the length of the output sound, increase the evelope length.


% Set defaults:
if (nargin < 5),
  if (nargin < 4),
    if (nargin < 3),
      if (nargin < 2), 
        if (nargin < 1),
          amplitude = 1;
         end
        b = 0.5;
       end
      p = 200;
     end
    wavetable_type = 'r';
   end
  envelope = ones(1,8000);
 end
switch wavetable_type
  case 'r', x = 2*rand(1,p) - 1;
  case 'c', x = ones(1,p);
  case 's', x = sin(0 : 2*pi/p : 2*pi - 2*pi/p);
 end

for i = 1:length(envelope),
  x(i+p) = 0.5 * x(i)  +  ((b < rand(1)) - 0.5) * x(i+1);
 end

snd = amplitude*x(p+1:length(x)).*envelope;

if (nargout == 0),
  sound(snd);
 end
