function res = playmusic(filename,tonefun, sf,unitdur,basenote)
% playmusic(filename, tonefun, sf, unitdur, basenote) - DTK
% plays a music file stored in the CS20 Excel format
% Examples:
% playmusic('scale.xls')-- play a scale using single pure tones
% playmusic('scale.xls', 'pipetone') --- similar, but with a pipe organ sound
% sf --- desired sampling frequence (48000 default)
% dur --- duration of a quarter note in seconds
% basenote --- the frequency of the note middle C

if nargin < 2 | isempty(tonefun)
    tonefun = @puretone;
end
if nargin < 3 | isemtpy(sf)
    sf = 48000;
end
if nargin < 4 | isempty(unitdur)
    unitdur = 0.4;
end
if nargin < 5 | isempty(basenote)
    basenote = 300*(2^(3/12)); %Hz
end
% read from the file
a = xlsread(filename);

freqs = basenote.*(2.^((a(:,1)-1)/12));
durs = a(:,2);
starts = a(:,3);
amps = a(:,4)./4;
totaldur = max(durs+starts)*unitdur;
s = zeros(ceil(totaldur*sf) + 100, 1);

for k=1:length(freqs)
    % no slurr for now
    snd = feval(tonefun, sf, freqs(k), durs(k)*unitdur, amps(k),0);
    b = 1+round(starts(k)*unitdur*sf);
    e = b+length(snd) - 1;
    if e <= length(s) % make sure that <snd> fits into <s>
        s(b:e) = s(b:e) + snd(:);
    else
        s(b:end) = s(b:end) + snd(1:(length(s)-b+1));
    end
end
res = s;

