function results = yamashita(OP,MV,options)
% function results = yamashita(OP,MV,options)
% 
% This file is a simple implementation 
% of the Yamashita stiction detection metod 
% in Matlab  
% 
% need: [diff.m], [std.m], [mean.m], 
%       primer.m, collect.m, 
%       skip.m, rho1.m, rho3.m
%
%       [fun.m] means fun.m is an internal
%       matlab function
%
% options: options.direct = 1  : direct action  (default)
%                         = -1 : reverse action  
%          options.report = 1  : make a small report 
%                         = 0  : no report      (default)
%
%
%                   Henrik Manum, 17 march 2006

% step 0. Check if there are some options set by user
if nargin == 2
    options.report = 0;
    options.direct = 1;
else
    if isfield(options,'report') == 0
        options.report = 0;
    end
    if isfield(options,'direct') == 0
        options.direct = 1;
    end
end


% The method strictly follows the steps of Yamashita
% step 1. Obtain a time series of the controller 
% output and valve position (given by input to file)
x = OP * 1000; y = options.direct*MV;

% step 2. Calculate the time difference for each 
% measurement variable
dxdt = diff(x); dydt = diff(y);

% step 3. Normalize the difference vaules using 
% the mean and standard deviation
X = (dxdt - mean(dxdt))/std(dxdt);
Y = (dydt - mean(dydt))/std(dydt);

% step 4. Quantize each variable in three symbols
X_sym = primer(X);
Y_sym = primer(Y);

% step 5. Describe qualitative movements in x-y 
% plots by combing symbolic values of each variable
symbols_raw = collect(X_sym,Y_sym);

% step 6. Skip SS patterns from the symbol sequence
symbols = skip(symbols_raw);

% step 7. Evaluate the index rho_1 by counting IS and
% DS periods in the pattern found
results.rho_1 = rho1(symbols);    

% step 8. Find specific patterns and count stuck
% periods. Then evaulate the index rho_3
results.rho_3 = rho3(symbols,options.direct);

% step 9. If wanted, make a small report
if options.report
    results.report = check_results(symbols,symbols_raw);
end

return
