%function y = fmclar(f0, A, I, dur, fs);
% CLARINET FM Clarinet instrument
% Y = CLARINET(F0, A, I, DUR, FS) where F0 is the fundamental frequency,
% A is a vector with the amplitude envelope, I is a vector with the
% modulation index envelope. DUR is the duration of the signal.  FS is
% the sampling rate.

if 0
if nargin < 5
disp('Too few arguments');
end

if nargin > 5
disp('Too many arguments');
end
end

fs = 44100;
f0 = 220;
dur = 1;

%The ratio fc:fm is 3:2 for woodwinds.  
% Therefore fc is 3f0 and fm is 2f0.

fc = 3*f0;
fm = 2*f0;

nT = 0:1/fs:dur-1/fs;
N = length(nT);


% construct envelope for A and I 
% (could make these an input parameter)
att = 0.1;           % attack, seconds
rel = 0.05;          % release, seconds

%attack
anT = 0:1/fs:att;
a = exp(anT/(att*0.5))-1;
a = a/max(a);        

% decay
rnT = 0:1/fs:rel-1/fs;
r = exp((rel-rnT)/(rel*.25))-1;
r = r/max(r);

% sustain

s = ones(1, N-length(a)-length(r));


A = [a s r];
I = [-a+1 zeros(1, length(s)+length(r))];

I = I*2+2; % scale according to Chowning, IMIN=2 and IMAX=4;

phim = 0;
phic = 0;

y = A.*cos(2*pi*fc*nT + I.*cos(2*pi*fm*nT + phim) + phic);

