function clippedsignal=centreclip(varargin)
%CENTRECLIP performs centre clipping of a speech signal.
%
%  CLIPPEDSIGNAL=CENTRECLIP(SIGNAL,RATIO,MODE)
%  The clipping level (CL) is equal to a fixed RATIO of the maximum amplitude.
%  RATIO can be given as either a percentage or a decimal ratio (0 to 1).
%  MODE == 'normal' outputs: 
%    For samples above CL, the output is equal to the input sample minus the clipping level.
%    For samples below CL, the output is zero.
%  MODE == '3level' outputs:                 J.J.Dubnowski et al. (1976)
%    SIGNAL(n)>CL  +1;
%    SIGNAL(n)<-CL -1;     Otherwise 0
% 
%  You can tell CENTRECLIP to use the default for any parameter by leaving it 
%  off or using [] for that parameter, e.g. CENTRECLIP(A,[],'3level')
%
%  Default clipping RATIO is 30% as used by M.M.Sondhi (1968).
%  Default MODE is 'normal'.
%
%  Author: Stuart N Wrigley
%  Release Date: 9 July 1998
%  Revision 0.00

error(nargchk(1,3,nargin));
[signal,level,mode]=clipcheck(varargin);

Amax=max(abs(signal));
CL=level*Amax;
switch mode
case 'normal'
   clippedsignal=(abs(signal)>CL).*(signal-(sgn(signal)*CL));
case '3level'
   clippedsignal=(abs(signal)>CL).*(sgn(signal));
otherwise
   error('Incorrect clipping mode! Use ''normal'' or ''3level''.');
end
clippedsignal=clippedsignal(:);

function [signal,level,mode]=clipcheck(P)
%CLIPCHECK  Helper function for CENTRECLIP
%   CLIPCHECK(P) takes the cell array P and uses each cell as 
%   an input argument.  Assumes P has between 1 and 3 elements.

signal=P{1};

if (length(P) > 1) & ~isempty(P{2})
   level = P{2};
   if level>=1              % given as percent therefore convert to ratio
      level=level/100;
   end   
else
   level = 0.3;
end

if (length(P) > 2) & ~isempty(P{3})
   mode = P{3};
else
   mode = 'normal';
end

