function [H,sdh1p,sdh1mm] = frac_rmscor(p,per_cut)
% RMS-correlation for calculation of Hurst exponent and asperity measure 
% according to Stigsson & Mas Ivars (2019), Candela et al. (2009) and
% Renard et al. (2006)
%
%   [H,sdh1p,sdh1mm] = frac_rmscor(P,PER_CUT)
%
%   P: profile array (first column x, second column y)
%   PER_CUT: percent of profile length cutoff (e.g. 10%->0.1)
%   !!! profile must be de-trended
%   !!! profile must have constant intervals of x
%   !!! profile must be in millimetre to obtain sdh1mm
%
%
% Please cite: 
% Marsch K & Fernandez-Steeger (2021) 
% https://doi.org/10.1007/s00603-020-02348-0
%
%
% License:
% "This work is licensed under the Creative Commons Attribution 4.0
% International (CC BY 4.0) License. To view a copy of this license, visit:
% http://creativecommons.org/licenses/by/4.0/"


%% calculate H
x = p(:,1)-min(p(:,1)); %move to first quadrant
y = p(:,2)-min(p(:,2));
numcut = floor(per_cut*length(x));
steps = linspace(1,numcut,numcut);
count = 1;
resi = zeros(length(steps),2);
for i = steps
    dy = y(1:1:end-i)-y(i+1:1:end);
    resi(count,1:2) = [i,std(dy,1)];
    count = count+1;
end
X2 = [ones(length(log10(resi(:,1))),1) log10(resi(:,1))];
c = X2\log10(resi(:,2));
H = c(2);

%% calculate asperity measure for intervals of p
sdh1p = 10^c(1);

%% calculate asperity measure for 1mm
sampstep = p(2,1)-p(1,1);
sdh1mm = sdh1p/(sampstep/1)^H;
