% TUBE SIMULATION SCRIPT 
%NICHOLAS LYNAR - SID: 420 171 012
%DIGITAL AUDIO SYSTEMS SEMESTER 1, 2013

function y=tube(x, gain, Q, dist, rh, rl, mix)


q=x*gain/max(abs(x));			%This normalizes the input signal
if Q==0
  z=q./(1-exp(-dist*q));
  for i=1:length(q)			
    if q(i)==Q				
      z(i)=1/dist;			%0/0 value in Q
    end;
  end;
else
  z=(q-Q)./(1-exp(-dist*(q-Q)))+Q/(1-exp(dist*Q));
  for i=1:length(q)				
    if q(i)==Q					%transfer function's
      z(i)=1/dist+Q/(1-exp(dist*Q));	
    end;
  end;
end;
y=mix*z*max(abs(x))/max(abs(z))+(1-mix)*x;
y=y*max(abs(x))/max(abs(y));			
y=filter([1 -2 1],[1 -2*rh rh^2],y);	%This is the High Pass Filter section of the function
y=filter([1-rl],[1 -rl],y);			    %This is the Low Pass Filter section of the function

% function y=tube(x, gain, Q, dist, rh, rl, mix)
% Original Author: Bendiksen, Dutilleux, Zölzer, 
% Modified for Educational Purposes 

% x  = input mono wav file , to be loaded in as x before running the function 
%
% gain = just as a tube amp would have on it's face plate, the gain control is 
%         the amount of distortion, >0->
%
%  Q  =  The Q controls the linearity of the transfer function,
%        the more negative the value = the more linear the signal 
%
%  dist - this dist setting controls the timbre and character of the distortion,
%        as expected the higher the number the harder the distortion, ( >0  )
%
%  rh   - Input values <1, but close to 1, this controls the High Pass Filter, 
%        this control is quite sensitive and isn't ideal for creating rich processed tones 
%
%  rl   - 0<rl<1, values input control the Low Pass Filter, which simulates the capacitance 
%        within the tube amplifier 
%
%  mix  = the mix value is as found on any amplifier to control the output mix between 
%         the original and processed signals 