function env=adenv(v1,v2,v3)
% ADENV Attack/Decay envelope generator
%  ADENV(dur,fs) generates an attack/decay envelope of length 'dur' seconds
%  at a sampling frequency of 'fs'. The transition between the attack phase
%  and the decay phase occurs at the midpoint of the envelope.
%
%  ADENV(dur,trans,fs) uses 'trans' to specify the transition point of the
%  attack and decay phases; 'trans' is expressed as a percentage. For example,
%  using 33 as the value for 'trans' causes the transition point to occur 
%  one third of the way into the envelope.
%
%  Example 1: One-second envelope with transition at 10%, sampling freq = 10kHz
%    fs=10e3;
%    dur=1;
%    tt=0:1/fs:dur;
%    y=adenv(dur,10,fs).*sin(2*pi*440*tt);
%    plot(tt,y)
%    soundsc(y,fs)
%
%  Example 2: Compositional experiment -- sequence of notes where duration
%  varies from 0.1 to 1 second, and transition point varies from early to late
%    fs=10e3;
%    y=[];
%    for i=0.1:0.1:1,
%       y=[y adenv(i,(i*i/2)*100,fs)];
%    end
%    tt=(0:length(y)-1)/fs;
%    y=env.*sin(2*pi*440*tt);
%    plot(tt,y)
%    soundsc(y,fs)

% EC497 Electronic Music Synthesis (S98)
% Department of Electrical and Computer Engineering
% Rose-Hulman Institute of Technology
%
% Ed.Doering@Rose-Hulman.Edu

%--------------------------------------------------------------------------
% Assign default values as needed
%--------------------------------------------------------------------------
switch nargin
   case 2
      dur=v1;
      fs=v2;
      trans=50;
   case 3
      dur=v1;
      trans=v2;
      fs=v3;
   otherwise
      disp('ADENV: Error - Please enter "help adenv" to review syntax')
      return
end

%--------------------------------------------------------------------------
% Internal parameters
%--------------------------------------------------------------------------

% Find time at which transition should occur; also convert to nearest
% time sample
atime=(trans/100)*dur;
atime=round(atime*fs)/fs;

% Time constants of attack and decay phases
Atau=atime/5;
Dtau=(dur-atime)/5;

%--------------------------------------------------------------------------
% Build the envelope
%--------------------------------------------------------------------------

% time vector
tt=0:1/fs:dur;

% build the attack portion of the envelope
env = 1-exp(-(0:1/fs:atime)/Atau);

% append the delay portion (use endpoint of attack as beginning of decay)
% Also, use one less sampling interval widths to generate correct number of
% of samples in the envelope.
env = [env env(length(env))*exp(-(1/fs:1/fs:dur-atime)/Dtau)];

return