%% Script 2: Importing and processing potassium data from short/long cores
% 
% 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

% Create directories.

    warning('off','MATLAB:MKDIR:DirectoryExists');

    mkdir DirFiguresMergingshortlongcores
    mkdir DirResultsMergingshortlongcores

% Clear workspace, clear command window and close figure windows.

  clear, clc, close all

% Define all base ages.

   allbaseages = 550:10:570;

% Loop.

   for loopi = 1 : length(allbaseages)

% Clear workspace, clear command window and close figure windows.

   clearvars -except allbaseages loopi
   clc, close all
    
% Define tuned age model to be used.

   agemodeltune = allbaseages(loopi);
    
% Create character string for all age models.
    agemodeltunemergestr = [...
        'RRMarch2021_MHT',num2str(agemodeltune(1))];

% Load data.

    % Load long core data.
    data_cbh14 = load(['DirResultsLongcores/data_chb14_2_age_orig_',...
        agemodeltunemergestr(1,:),'.txt']);

    % Normalize data.
    data_cbh14(:,1) = data_cbh14(:,1);
    data_cbh14(:,2) = data_cbh14(:,2) - mean(data_cbh14(:,2),'omitnan');
    data_cbh14(:,2) = data_cbh14(:,2) / std(data_cbh14(:,2),'omitnan');
    
    % Load short core data, now with IntCal20 calibrated 14C ages.
    data_cb01 = load('DirDataOther/data_cb01_cb03_InCal20.txt');
    data_cb01(:,1) = data_cb01(:,1)/1000;
    data_cb01(:,2) = data_cb01(:,2) - mean(data_cb01(:,2),'omitnan');
    data_cb01(:,2) = data_cb01(:,2) / std(data_cb01(:,2),'omitnan');

% Merge data.

    data_merged = vertcat(data_cb01(data_cb01(:,1)<20,:), ...
        data_cbh14(data_cbh14(:,1)>20,:));
    data_merged(data_merged(:,1)<20,2) = ...
        data_cb01(data_cb01(:,1)<20,2) + 0.85;   % Offset

% Display the result.
    
    script_display_merging

% Save merged data.

    savename = strcat("DirResultsMergingshortlongcores/",...
        "data_chb14_2_cb01_cb03_age_rrmarch2021_mht",...
        num2str(agemodeltune(1)),".txt");

    save(savename,'data_merged','-ascii')

    end

    close all


