function [a_out, b_out]=tt(x)
% TT   Mean trapping time and its distribution.
%    A=TT(X) computes the mean of the length of the vertical 
%    line structures in a recurrence plot, so called trapping 
%    time TT.
%
%    [A B]=TT(X) computes the TT and the lengths of the
%    found vertical lines, stored in B. In order to get the 
%    histogramme of the line lengths, simply call 
%    HIST(B,[1 MAX(B)]).
%
%    Examples: X = crp(rand(200,1),1,1,.3,'fan','silent');
%              [v v_dist] = tt(X);
%              hist(v_dist,200)
%
%    See also CRQA, DL.

% Copyright (c) 2001-2003 by AMRON
% Norbert Marwan, Potsdam University, Germany
% http://www.agnld.uni-potsdam.de
%
% $Date$
% $Revision$
%
% $Log$
% Revision 3.2  2005/03/16 11:19:02  marwan
% help text modified
%
% Revision 3.1  2004/11/10 07:07:35  marwan
% initial import
%
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.

error(nargchk(1,1,nargin));
if nargout>2, error('Too many output arguments'), end

warning off
if any(x(:))

  if min(size(x))>1000       % this should speed up the routine; the value
                             % depends on the available memory
    x2=uint8(x);
    x2(end+1,:)=0;
    x=reshape(x2,size(x2,1)*size(x2,2),1);
    x2=x(2:end);x(end)=[];
    z0=find(x==0&x2==1);
    z1=find(x2==0&x==1);
  
  else
  
    x(end+1,:)=0;x=double(x);
    z=diff(reshape(x,size(x,1)*size(x,2),1));
    z0=find(~(z-1));
    z1=find(~(z+1));
  
  end
  
  
  if z0(1)>z1(1)
    z0(2:end+1)=z0(1:end);z0(1)=0; 
    if length(z0)>length(z1) 
       z0(end)=[];
    end
  end
  
  t=sort(z1-z0);
  t1=t(find(t-1));
  
  if nargout==2
     b_out=zeros(length(t),1);
     b_out=t;
  end
  
  if nargout>0
     if isempty(t1), a_out=0;
     else, a_out=mean(t1); 
     end
  else
     mean(t1)
  end
    
else

  if nargout==2
     b_out=NaN;
  end

  if nargout>0
     a_out=NaN;
  else
     NaN
  end

end

warning on
