%% Script S2: Script to read the Chew Bahir XRF Data
% 
% Trauth, M.H., Asrat, A., Fischer, M., Foerster, V., Kaboth-Bahr, S.,
% Lamb, H.F., Marwan, N., Roberts, H.M., Schaebitz, F., 2024, Combining
% orbital tuning and direct dating approaches to age-depth model
% development for Chew Bahir, Ethiopia. Quaternary Science Advances
% 
% Martin H Trauth 7 June 2024

% Reading data from LacCore File.
dataall = ...
      datastore('DirDataOther/data_HSPDP_CHB14_XRF_Aug2019_20190827.txt');
dataall.SelectedVariableNames = {'SpliceDepth','Al','Ba','Ca','Cl',...
          'Fe','K','Mn','Rb','S','Si','Sr','Ti','Zr','qualityflag'};
dataxrftable = readall(dataall);

% Creating labels.
for i = 1 : 14
   lbs(:,i) = ["CHB ";string(dataall.SelectedVariableNames(:,i))];
end
lbs = lbs';
dataxrfstring = strcat(lbs(:,1),lbs(:,2));
dataxrfstring(1,:) = [];

% Converting table |dataxrftable| to double |dataxrf|.
dataxrf = table2array(dataxrftable);

% Removing bad points according to Verena's quality flags 0 and 1.
dataxrf(dataxrf(:,15) == 0 | dataxrf(:,15) ==1,:) = [];

% Removing duplicate data points.
dataxrf2 = dataxrf;
for i = 1:size(dataxrf2,1)-1
    if dataxrf2(i,1) == dataxrf2(i+1,1)
        dataxrf2(i,1) = NaN;
    end
end
dataxrf2(isnan(dataxrf2(:,1))==1,:) = [];
dataxrf = dataxrf2;
clear dataxrf2

% Removing gaps to create |dataxrf|.
dataxrf(isnan(dataxrf(:,2))==1,:) = [];

% Suppress warning concerning the ignorance of NaNs during interpolation.
warning('off','MATLAB:interp1:NaNstrip')

% Interpolating data to age model to create |dataxrfage|.
dataxrfage = dataxrf;
dataxrfage(:,1) = interp1(agemodeltiepoints(:,1),agemodeltiepoints(:,2),...
    dataxrf(:,1),inttype,exttype);

% Interpolating data to evenly spaced time axis to create |dataxrfageintp|.
dataxrfageintp(:,1) = agemodelmin : agemodelres : agemodelmax;
for i = 2:14
    dataxrfageintp(:,i) = interp1(dataxrf(:,1),...
        dataxrf(:,i),dataxrfageintp(:,1),inttype,exttype);
end
dataxrfageintp(:,15) = 1;






