function [p_n] = detrendint(p,samp_int)

%% 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/"

%% please cite 
% --> Kristofer Marsch (2020)
% --> DOI for this data available at https://orcid.org/0000-0002-1857-506X 


%% --parameters-- %%
% p: array of profile, first column horizontal values, second column heights
% samp_int: specify sampling interval, should be 1mm

%% detrend
angle = 5; %first guess
while abs(angle) > 0.01 
    XX = [ones(length(p(:,1)),1) p(:,1)];
    slope = XX\p(:,2);
    angle = atand(slope(2,1));
    matrix = [cosd(-angle), -sind(-angle) ; sind(-angle), cosd(-angle)]; 
    p = (matrix*p')'; 
end
p = unique([(p(:,1)-min(p(:,1))) (p(:,2)-min(p(:,2)))],'rows'); 

%% interpolate to samp_int
xi = (min(p(:,1)):samp_int:max(ceil(p(:,1)))); 
zi = interp1(p(:,1),p(:,2),xi,'linear');
p = [xi' zi'];
p(any(isnan(p),2),:) = []; %delete NaN
p_n=p;