function eval_adsr(Ta, Td, Vs, Tr, ks)

% eval_adsr(0.1, 0.2, 0.2, 0.2)

fs = 1000;

a_a = -log(1-ks)/(Ta*fs);
a_d = 5/(Td*fs);
a_r = 5/(Tr*fs);
state = 0;
s = 0;
tol = 1E-4;
n = 1;
p = 0;
k = 1/ks;
while (1),
    
    if state == 0       % Attack
        s = a_a + (1-a_a)*s;
        y(n) = k*s;
        if s >= (ks-tol)
            state = 1;
            s = 1-ks;
        end;
    end;
    if state == 1       % Decay
        s = (1-a_d)*s;
        y(n) = s/(1-ks);
        if s <= (Vs+tol)
            state = 2;
            p = 0;
        end;
    end;
    if state == 2       % sustain
        y(n) = Vs;
        if p >= 1*fs
            state = 3;
            s = Vs;
        end;
        p = p + 1;
    end;
    if state == 3       % Release
        s = (1-a_r)*s;
        y(n) = s;
        if s <= (tol)
            break;
        end;
    end;
    n = n + 1;
end;

plot((0:n-1)/fs, y); grid;
set(gca,'xtick',[0:0.1:(n-1)/fs])
