function out=play(fncname,notes,fs)
%PLAY Convert notelist to a waveform
%	waveform=PLAY('fncname',notelist,fs) plays the instrument defined by 'fncname'
%  using the notes in 'notelist'. It returns a waveform sampled at 'fs' Hz.
%
%  Each row of the matrix 'notelist' consists of note-on time, duration,
%  note number, and velocity.  Note numbers are converted to frequency in Hz
%  using note number 69 as concert A (440 Hz). Velocities are scaled to have
%  a max value of 1 before passing to the instrument function.
 
%  Created 1998 Feb 23
%  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.

% generate time vector for output waveform; end time is nearest integer
% above the last note event time (give some extra room)
tt=0:1/fs:ceil(max(notes(:,1))+max(notes(:,2)))-(1/fs);

% convert note numbers to frequencies in Hz
notes(:,3)=note2hz(notes(:,3));

% scale note velocities so max velocity is one
notes(:,4)=notes(:,4)/max(notes(:,4));


% convert each note to a waveform, and add the waveform to the output waveform
y=zeros(size(tt));
for i=1:size(notes,1),
   % convert note to waveform using the instrument defined by 'fncname'
   w=feval(fncname,notes(i,2:4),fs);
   % place waveform in the output file
   ttint=round(notes(i,1)*fs)+1:round(notes(i,1)*fs)+length(w);
   y(ttint)=y(ttint)+w;
end

% play the sound if no output arguments, otherwise return the sound
if nargout<1
   soundsc(y,fs)
else
   out=y;
end

return