function [RFM,RFM1,res] = dtp2rfm(x,varargin)

%DTP2RFM  calculate rainflow matrix from discrete turning points.
%
% CALL: RFM = dtp2rfm(x,n)
%       [RFM,RFM1,res] = dtp2rfm(x,n,def)
%       [RFM,RFM1,res] = dtp2rfm(x,RFM0,res0)
%       [RFM,RFM1,res] = dtp2rfm(x,def,RFM0,res0)
%
% Output:
%   RFM   = Rainflow Matrix (residual included).    [n,n]
%   RFM1  = Rainflow matrix (without resudual).     [n,n]
%   res   = Residual.                               [nres,1]/[nres,2]
%
% Input:
%   dtp   = Turning points (taking values 1,...,n). [T,1]/[T,2]
%   n     = Number of levels.
%   def   = Treatment of residual.
%           'up':   Count min-to-Max cycles,    (default)
%                   gives correct number of upcrossings.
%           'down': Count Max-to-min cycles, 
%                   gives correct number of downcrossings.
%           'CS':   Cloormann/Seeger method, 
%                   gives all closed hysterisis loops.
%                   This method is identical to the French ANFOR standard, 
%                   and the ASTM standard (variant called simplified version).
%   RFM0  = Rainflow matrix (without resudual).     [n,n]
%   res0  = Residual (taking values 1,...,n).       [nres0,1]/[nres0,2]
% 
% See also: dtp2arfm, dcc2cmat, tp2rfc, dat2tp

% Tested  on Matlab  5.3
%
% History:
% Revised by PJ 26-Jul-2000
%   New input 'def'. 
%   Now supports ANFOR and ASTM standards for rainflow counting.
% Revised by PJ (Pär Johannesson) 12-Jan-2000
%   updated for WAFO
% Created by PJ (Pär Johannesson) 1999

% Check input arguments
ni = nargin;
no = nargout;
error(nargchk(2,4,ni));

% Calculate asymetric RFM
if no < 2
  RFM = dtp2arfm(x,varargin{:});
else
  [RFM,RFM1,res] = dtp2arfm(x,varargin{:});
end

% Convert to symetric rainflow
RFM = RFM+RFM';
RFM = triu(RFM);
if no >= 2
  RFM1 = RFM1+RFM1';
  RFM1 = triu(RFM1);
end


