function x = detunex(df,dt,n,f0,t,m,sr)
% x = detunex(DF,DT,N,F0,T,M,SR)  Construct an example detuning stimulus
%	Create a harmonic complex with one mistuned (and possibly mistimed)
%	partial.  The partial is detuned by a factor of DF (e.g. 0.01) and 
%	its onset is advanced by DT (e.g. 0.020, -ve for delay).  The 
%	detuned harmonic is at N x the fundamental F0 (defaults: 4 & 250 Hz).
%	The overall stimulus duration is T sec (default 0.2) and has a 
%	total of M harmonics (default 6).  The output data is a playable
%	soundfile at sampling rate SR (default 22050).
% 1998jul11 dpwe@icsi.berkeley.edu ASI demo.

if nargin < 3; n = 4; end
if nargin < 4; f0 = 250; end
if nargin < 5; t = 0.2; end
if nargin < 6; m = 6; end
if nargin < 7; sr = 22050; end

% Figure the total duration, including any skew
ttot = t + abs(dt);

% How long to ramp tones up/down (linear)
ramptime = 0.010;

% Precalculate the ramp
nramppts = floor(ramptime*sr);
ramp = [1:nramppts]/nramppts;
rmask = [ramp, ones(1, ceil(t*sr)-2*nramppts), (1 - ramp)];
rmlen = size(rmask, 2);

% Empty output
nout = ceil(ttot*sr);
x = zeros(1, nout);

% Base time
tbase = 0;
if (dt > 0);  tbase = dt; end;

% Add in each harmonic

for h = 1:m
  if h == n
     % detuned and time-skewed harmonic
     tn = tbase - dt;
     fn = (1+df)*h*f0;
  else
     % regular harmonic
     tn = tbase;
     fn = h*f0;
  end
%  disp(['Harmonic ', int2str(h), ' freq ', num2str(fn), ' time ', num2str(tn)]);
  % How many leading zeros?
  leadz = floor(tn*sr);
  % Calculate the ramped sine tone
  dn = [zeros(1,leadz),rmask,zeros(1,nout-leadz-rmlen)].*sin(2*pi*fn*[0:(nout-1)]/sr);
  % Add into the output
  x = x + dn;
end

% Scale down for constant sum
x = x / m;
