function ADSRVector = Fx_GuitarADSR(target,gain,duration,fs)

% function ADSRVector = Fx_GuitarADSR(target,gain,duration,fs)
%
% This function calculates and returns a guitar ADSR envelope
% defined by the following parameters:
%
% target:   vector of attack, sustain, release target values
% gain:     vector of attack, sustain, release gain values
% duration: vector of attack, sustain, release durations in ms
% ADSRVector: vector of adsr envelope values

%  Author: Andreas Floros
%  Digital Audio Processing Applications Group
%  Dept. of Audiovisual Arts, Ionian University
%  v.1.0 - Last Modified: 22/03/2009.

% Calculate the total duration in msec
adsr_duration = sum(duration);

% Calculate the number of samples within the above duration
npoints = adsr_duration * fs / 1000;
% ... and the durations provided as inputs in samples
duration = floor(duration./1000.*fs);

% Initialize output
ADSRVector = zeros(npoints,1);

% Attack phase
start = 2;
stop = duration(1);
for n = [start:stop]
    ADSRVector(n) = target(1)*gain(1) + (1.0 - gain(1))*ADSRVector(n-1);
end

% Sustain phase
start = stop + 1;
stop = start + duration(2);
for n = [start:stop]
    ADSRVector(n) = target(2)*gain(2) + (1.0 - gain(2))*ADSRVector(n-1);
end

% Release phase
start = stop + 1;
stop = npoints ;
for n = [start:stop]
    ADSRVector(n) = target(3)*gain(3) + (1.0 - gain(3))*ADSRVector(n-1);
end

ADSRVector = ADSRVector';