% fileplay - Do plots for given file and play over MIDI channel 9
% Data is played on kick and snare (note numbers 36 and 38).
% Metrical grid can be played on hi-hat, cowbell etc.
function player=fileplay(MO,file,varargin)
	opts=prefs('vel',80,'dur',0.1,'shift',file{2},'metre',[],varargin{:});

	disp(file{1});
	BDT=shift_beat(opts.shift,read(file{1}));
	drumplot(BDT,'bar',4,'pause',0,varargin{:});
	player=playdrums(MO,[36,38,42,44,51,56,49,53],addmetre(opts.metre,BDT(:,[2,1,4])),opts);
end

function player=playdrums(MO,PercMap,Evs,opts)
	NN=map(PercMap,Evs(:,1));
	Times=(Evs(:,2)-Evs(1,2))/1000;
	player=rendermidi(MO,window(zipmidi_abs(Times,opts.dur,9,NN,opts.vel)'),nows(MO)+1);
end

function Evs=addmetre(metre,Evs)
	for i=1:size(metre,1)
		Evs=add_periodic(metre(i,1),metre(i,2),Evs);
	end
end

function X=add_periodic(m,type,Y)
	[UMetPos,K]=unique(Y(:,3));
	Bars=(0:m:max(UMetPos))';
	BarTimes=interp1(UMetPos,Y(K,2),Bars);
	Types=repmat(type,size(BarTimes));
	X=sort_by(2,vertcat(Y,[Types,BarTimes,Bars]));
end

function X=sort_by(col,Y)
	[dummy,K]=sort(Y(:,col));
	X=Y(K,:);
end
