function y=gen4(v,dur,fs)
% gen4 function (Moore p. 184, and p. 514)
%GEN4 Emulates the cmusic 'gen4' envelope generator
%	env=GEN4(vlist,dur,fs) accepts a matrix 'vlist' where each row is a triple indicating
%  time (arbitrary units), value (usually between 0 and 1), and transition type.
%  'dur' is the envelope duration in seconds, and 'fs' is the sampling frequency in Hz.
%
%  See p. 184 and p. 514 of F. Richard Moore's text ("Elements of Computer Music", 1990, 
%  Prentice-Hall) for more details.

%  Created 1998 March 31
%  Ed.Doering@Rose-Hulman.Edu
%  Department of Electrical and Computer Engineering
%  Rose-Hulman Institute of Technology
%  Terre Haute, IN 47803-3999
%
%  Copyright (c) 1998 by Ed Doering.

% Find the number of vertices
numv=size(v,1);

% Set the time column to occur over duration
v(:,1)=(v(:,1)/v(numv,1))*dur;

% Generate the envelope (guard against divide by zero error by adding
% a small number to denominator)
y=[];
for k=1:numv-1 
   ii=linspace(0,1,(v(k+1,1)-v(k,1))*fs);
   if v(k,3)==0
      y=[y linspace(v(k,2),v(k+1,2),size(ii,2))];
   else
      y=[y v(k,2)+(v(k+1,2)-v(k,2))*(1-exp(v(k,3)*ii))/(1-exp(v(k,3)+1e-12))];
   end
end

% Figure out how many samples are expected
nums=size(0:1/fs:dur,2);

% Figure out how many samples were generated
numg=size(y,2);

% Pad or trim the vector as needed
% (NOTE: This method is a bit of a kluge -- maybe someone can suggest a better
% way!)
if numg<nums
   y=[y zeros(1,nums-numg)];
elseif numg>nums
   y(nums+1:numg)=[];
end
   