 function yy = qtize(xx, lev, mx, ulaw)
%function yy = qtize(xx, lev, mx, ulaw)
% Uniform scalar quantization
% in
%	xx	vector of input samples
%	lev	# of desired quantization levels
%	mx	(optional) maximum value of entire input signal
%	ulaw	(optional) u-law value (0 = no companding)
% out
%	yy	quantized vector of output samples

% defaults
if nargin < 2; lev = 2^8; end
if nargin < 3; mx = max(abs(xx)); end
if nargin < 4; ulaw = 0; end

% infinity case
if isinf(lev); yy=xx; return; end

% compress if desired
if ulaw>0; xx=lin2mul(xx,ulaw,mx); end

% distinguish even/odd-case
if fix(lev/2) == lev/2;
	% compute quantization levels in even case
	yy = (2*mx/lev) * (round((0.5*lev/mx)*xx+0.5)-0.5);
else
	% compute quantization levels in odd case
	yy = (2*mx/lev) * round((0.5*lev/mx)*xx);
end

% deal with extremes
yy(yy >= +mx) = +mx * (lev-1)/lev;
yy(yy <= -mx) = -mx * (lev-1)/lev;

% expand if desired
if ulaw>0; yy=mul2lin(yy,ulaw,mx); end

return	% end of main function


function x=mul2lin(y,u,xm)
% PURPOSE	: Linear to u-Law Conversion
% PARAMETERS	: y = u-law compressed version of x
%	u = u-law factor (e.g. = 255)
%	xm = maximum absolute value in entire signal x
%	x = u-law expanded version of y
x=(xm/u)*(sign(y).*((((1+u)*ones(1,length(y))).^(abs(y)/xm))-1));

function y=lin2mul(x,u,xm)
% PURPOSE	: Linear to u-Law Conversion
% PARAMETERS	: x = input sequence
%	u = u-law factor (e.g. = 255)
%	xm = maximum absolute value in entire signal
%	y = u-law compressed version of x
y=(xm/log(1+u))*(sign(x).*log(1+(u/xm)*abs(x)));
