% This function calculates a 2-channel stereo matrix S for a given mono wave
% file and the desired parameters for the difference of time and amplitude
% the 2 resulting channels shall have.
% The intention is to place a (mono) sound at a virtual position between to
% loudspeakers so that it appears as a "phanton sound source"
%
% it is recommended to use loudspeakers instead of headphones
%
% usage: [S, FS] = stereo(amp_diff, time_diff);
%        e.g. [S, FS] = stereo(3,200);  
%
%        use sound(S, FS) to play the matrix S
%        or wavwrite(S, FS, 'stereo.wav');
%
% PARAMETERS:
%
% amp_diff : difference between signal amplitude in dB ref. to left channel
%            pos. values -> the right speaker is louder
%            neg. values -> the left speaker is louder
%            amp_diff = 0 -> no difference between left and right speaker
%
% time_diff : desired time in microseconds difference between L and R
%             only the right channel is shifted              
%             use positive values to play the sound earlier(!) on the
%             right speaker
%
% OUTPUT:
%
% S : [Nx2]matrix where N is the number of sound samples
%
% authors: Frithjof Hummes, Hendrik Buschmeier 
% date   : 2005-10-03


function [S,FS] = stereo(amp_diff, time_diff)

wavname = 'leftside';
              
% load the mono wave file 
[Y, FS, NBITS] = wavread(wavname);

% initialization of the stereo matrix
S = zeros(length(Y),2);

% calculate the factors for the channels amplitudes 
% for a given difference between R and L in dB 

   ratio = 10^(amp_diff/10);
   rf = ratio / (ratio + 1);
   lf = 1 / (ratio + 1); 


% calculate the number of samples to shift the channel
% FS/1,000,000 samples per mirco second

   shft = round(time_diff * (FS / 1000000));

   
   
% calculate the final stereo matrix

   L = lf * Y;
   R = zeros(length(Y),1);             % initialization of the right channel  
   T = Y;                              % just a temporary vector

   if (shft < 0) 
        T = T(1:length(T)+shft);       % take the first samples 
        R(1-shft:length(R)) = T;       % place it at the desired position               

   elseif (shft > 0) 
        T = T(shft+1:length(T));       % take the last samples 
        R(1:length(T)) = T;            % place it at the desired position                    

   else R = T;                         % no shifting
   end 
 
   S(:,1) = L;                         % copy into the stereo matrix
   S(:,2) = rf * R;                    

return % stereo