function y = adsr(A, D, sus, R, N)
% ADSR Attack, Decay, Sustain, Release envelope.
%   Y = ADSR(A, D, SUS, R, N)
%
%   - Y is the envelope vector, with values between 0 and 1.
%   - A, D, and R are the lengths of the attack, decay and release 
%     segments, respectively, expressed as a fraction of N, the vector
%     length in samples. 
%   - SUS is the level of the sustain, between 0 and 1.
%
%   Example use:
%   y = adsr(.2, .1, .8, .3, 128);

% make sure each segment has an integer number of samples
Na = round(A*N);    % attack length, samples
Nd = round(D*N);    % decay length, samples
Nr = round(R*N);    % release length, samples
Ns = N-Na-Nd-Nr;    % sustain length, samples

%create each segment
att = 0:1/Na:1-1/Na;
dec = 1:-(1-sus)/Nd:sus;
sus = sus*ones(1, Ns-2);
rel = sus:-sus/Nr:0;

y = [att dec sus rel];
