%% This shell aims to display the stacked RFs, grouped by event clusters, on profiles
%% Written by Yaoyao He, on 2026/2/3
clear; clc; close all

%% Profiles
profiles{1} = [125 115 105 95 75 66 55 46 35];
% N-E
% profiles{1} = 141:150;
% profiles{2} = 131:140;
% profiles{3} = 121:130;
% profiles{4} = 111:120;
% profiles{5} = 101:110;
% profiles{6} = [91:94, 96:100];
% profiles{7} = [83:84, 95, 86:90];
% profiles{8} = 71:80;
% profiles{9} = [61:63, 65:70];
% profiles{10} = 51:60;
% profiles{11} = [41:50];
% profiles{12} = [156, 31:40];
% profiles{13} = [157, 152, 21:30];
% profiles{14} = [159, 154, 11:13, 15:19];
% profiles{15} = [160, 155, 1:10];
% profiles{16} = [171:176 178:180];
% profiles{17} =  [141 132 122 113 104 94 84 75 67 57 48 38 29 20 10];
% N-S
% profiles{18} = [141:-10:91, 71:-10:1];
% profiles{19} = [132:-10:72, 62:-10:2, 170];
% profiles{20} = [142, 133:-10:83, 72, 63:-10:3, 168, 172];
% profiles{21} = [144:-10:54, 45, 34, 15, 14, 4, 172];
% profiles{22} = [143, 134:-10:74, 65, 55, 46, 35, 25, 16, 5, 173,];
% profiles{23} = [135:-10:95, 75, 66, 56, 47, 36, 27, 17, 6, 177, 165, 166, 175];
% profiles{24} = [146:-10:96, 85, 86, 76, 67, 57, 37, 27, 17, 7, 164, 176];
% profiles{25} = [147:-10:77, 68:-10:8, 162, 178];
% profiles{26} = [138:-10:88, 79:-10:9, 161, 163, 179, 180];
% profiles{27} = [148, 139:-10:89, 80:-10:10];
% profiles{28} = [150, 149, 140:-10:90];

%% I/O 
inputdir = "D:\YB\yunnan2\F0_6.0_waterlevel_0.01\3_selected_stationset_v2";
subdir = string(ls(fullfile(inputdir, 'NK*')));

 
%% Basic parameters
% Range of BAZ
min_baz = 200;
max_baz = 300;
outputdir = fullfile("D:\YB\yunnan2\F0_6.0_waterlevel_0.01\profiles", strcat('BAZ_', num2str(min_baz), '_', num2str(max_baz)));
 if ~exist(outputdir, 'dir')
     mkdir(outputdir);
 end
% Topography
[N25E099, R1] = readgeoraster("D:\YB\NASADEM_HGT_1arcsecond_YB\ASTGTMV003_N25E099_N27E101\ASTGTMV003_N25E099_dem.tif");
[N25E100, R2] = readgeoraster("D:\YB\NASADEM_HGT_1arcsecond_YB\ASTGTMV003_N25E099_N27E101\ASTGTMV003_N25E100_dem.tif");
elev_YB = double([N25E099 N25E100(:, 2:end)]);
lonlim = linspace(98.9999, 101.0001, size(elev_YB, 2));
latlim = linspace(26.0001, 24.9999 , size(elev_YB, 1));
[lonmig, latmig] = meshgrid(lonlim, latlim);
% stations' location
sta_info = textscan(fopen("D:\YB\yunnan2\station.txt", 'r'), '%f %f %s %s %s %s %f', 'Commentstyle', 'shell', 'Headerlines', 1);
lon = (sta_info{1})';
lat = (sta_info{2})';
scale = 1;
% filter
fl = 0.02;
fh = 1;
order = 2;
% figures
labelsize = 24;
ticklabelsize = 20;
textfontsize = 12;
fontsize = 20;
color = [0,0,0;0.7451,0.7451,0.7451];
color_stack = [1,0,0;0.7451,0.7451,0.7451];
fig_size = [-1454         483         743         463];
b_height = 0.15;
t_height = 0.07;
l_width = 0.14;
width = 0.8;
l_xlim = -5;
r_xlim = 20;
set(0,'DefaultAxesFontName','Calibri')
set(0,'DefaultTextFontName','Calibri') 

%% main progress
for i_prof = [1 2 10 16]%1:length(profiles)
    i_profile = profiles{i_prof};
    Ps_arrivaltimes_of_prof = zeros(length(i_profile), 1);
    stacked_RFs_on_prof = zeros(901, length(i_profile));
    for i_sta = 1:length(i_profile)
        no_sta = i_profile(i_sta);
        fid = fopen(fullfile(inputdir, subdir(no_sta), 'list_r_Decon_PF.txt'), 'r');
        saclist_info = textscan(fid, '%s %f %f %f %f %s %s %f %f %f %f %f %f %f %f %f %f %f %f \n', 'CommentStyle', 'shell', 'HeaderLines', 1);
        fclose(fid);
        if isempty(saclist_info{1,1})
            continue
        end
        filename = string(saclist_info{1});  
        file_num = length(filename);
        rayp = saclist_info{1,8};
        stla = saclist_info{1,9}(1);
        stlo = saclist_info{1,10}(1);
        evla = saclist_info{1,12};
        evlo = saclist_info{1,13};
        dist = saclist_info{15};
        baz  = saclist_info{17};

        clus_data = zeros(901, file_num);
        clus_dist = zeros(file_num, 1);
        clus_baz  = zeros(file_num, 1);
        clus_rayp = zeros(file_num, 1);
        for i_file = 1:length(filename)
            [hdr, data] = irdsac(fullfile(inputdir, subdir(no_sta), filename(i_file)));
            tshift = hdr.a - hdr.b;
            time = (0:hdr.npts-1)'*hdr.delta - tshift;
            % filtering and normalization
            data = filtering(data, hdr.delta, fl, fh, order);
            data = data./max(abs(data));
            % assign data to cluster
            if baz(i_file) > min_baz && baz(i_file) < max_baz
                clus_data(:, i_file) = data;
                clus_dist(i_file) = dist(i_file);
                clus_baz(i_file) = baz(i_file);
                clus_rayp(i_file) = rayp(i_file);
            end    
        end
        % delete zero column
        clus_data = clus_data(:, any(clus_data ~= 0, 1));
        clus_dist = clus_dist(clus_dist ~= 0);
        clus_baz  = clus_baz(clus_baz ~= 0);
        clus_rayp = clus_rayp(clus_rayp ~= 0);
        % sort by BAZ 
        [clus_baz, ind1] = sort(clus_baz);
        clus_data = clus_data(:, ind1);
        clus_dist = clus_dist(ind1);
        clus_rayp = clus_rayp(ind1);
        % stacking RFs
        stacked_data = mean(clus_data, 2);
        stacked_RFs_on_prof(:, i_sta) = stacked_data;
        if isempty(find(stacked_data,1))
            flag1 = 0;
        else
            flag1 = 1; 
        end
        Ps_timewin_ind = find(roundn(time, -1)==5):find(roundn(time, -1)==7);
        [~, Ps_arrivaltime] = max(stacked_data(Ps_timewin_ind)); Ps_arrivaltime = 5+(Ps_arrivaltime-1)/10;
        Ps_arrivaltimes_of_prof(no_sta, 1) = Ps_arrivaltime;  
    end
    % plot profiles
    figure
    axes('Position', [0.17, 0.85, 0.75, 0.1])
    profile_lon = lon(i_profile);
    profile_lat = lat(i_profile);
    distances = [0 distance(profile_lat(1:end-1),profile_lon(1:end-1), profile_lat(2:end),profile_lon(2:end))*pi*6371/180];
    profile_len = sum(distances);
    cumsum_dist = cumsum(distances)/scale;
    % topography on stations
    lo_idx = zeros(1, length(profile_lon));
    la_idx = zeros(1, length(profile_lon));
    for i_point = 1:length(profile_lon)
        [~, lo_idx(i_point)] = min(abs(lonlim - profile_lon(i_point)));
        [~, la_idx(i_point)] = min(abs(latlim - profile_lat(i_point)));
    end
    % splicing segments
    diff_lo = diff(lo_idx);
    diff_la = diff(la_idx);
    profile_ele_interp = [];
    cumsum_dist_interp = [];
    for i_seg = 1:length(diff_lo)
        interp_points = abs(max(diff_lo(i_seg), diff_la(i_seg)))+1;
        lon_temp = linspace(lonlim(lo_idx(i_seg)), lonlim(lo_idx(i_seg+1)), interp_points);
        lat_temp = linspace(latlim(la_idx(i_seg)), latlim(la_idx(i_seg+1)), interp_points);
        profile_ele_temp = interp2(lonmig, latmig, elev_YB, lon_temp, lat_temp, 'linear');
        profile_ele_interp = [profile_ele_interp profile_ele_temp];
        cumsum_dist_interp = [cumsum_dist_interp linspace(cumsum_dist(i_seg), cumsum_dist(i_seg+1), interp_points)];
    end
    show_minelve = (round(min(profile_ele_interp)/100)-1)*100;
    show_maxelve = (round(max(profile_ele_interp)/100)+1)*100;
    fill([0 cumsum_dist_interp cumsum_dist_interp(end)], [show_minelve profile_ele_interp show_minelve], [.7 .7 .7], 'LineStyle', 'none')
    hold on
    plot(cumsum_dist_interp, profile_ele_interp, 'k-',  'LineWidth', 0.1)
    set(gca, 'FontSize', 14)
    xticks([])
    xticklabels([])
    ylabel('Elevation (m)', 'FontSize', 16)
    xlim([-1 (profile_len+2)/scale])
    ylim([show_minelve show_maxelve]) 
    ytick1 = show_minelve:400:show_maxelve;
    set(gca, 'YTick', ytick1)
    set(gca, 'YTickLabel', string(ytick1))
    titlestr = strcat('p', num2str(i_prof));
    title(titlestr, 'FontSize', fontsize);

    axes('Position', [0.17, 0.15, 0.75, 0.7])
    for i_trace = 1:length(i_profile)
        if ~any(stacked_RFs_on_prof(:,i_trace))
            plot([-10 30], [cumsum_dist(i_trace) cumsum_dist(i_trace)], 'k--', 'LineWidth', 1.5);
            hold on
        end
        single_wig7(time, stacked_RFs_on_prof(:, i_trace), cumsum_dist(i_trace), color(1,:), color(2,:), 'yes', 'yes');
        hold on
    end      
    % P phase
    plot([0 0], [-0.5 (profile_len+1)/scale], 'r', 'LineWidth', 1.5)
    hold on
    text(-1, (profile_len+0.5)/scale, 'P', 'Color', 'r', 'FontSize', 20)
    box on 
    grid on
    set(gca, 'YGrid', 'off');
    xlim([-2 r_xlim])
    ylim([-1 (profile_len+2)/scale])
    set(gca, 'FontSize', 16)
    xlabel('Time(sec)', 'FontSize', fontsize);
    ylabel('Distance (km)', 'FontSize', fontsize);
    xtick = 0:2:20;
    xticklabel = string(xtick);
    set(gca, 'XTick', xtick);
    set(gca, 'XTickLabel',xticklabel);
    ytick = cumsum_dist(1):5:cumsum_dist(end);
    yticklabel = string(ytick);
    set(gca, 'YTick', ytick);
    set(gca, 'YTickLabel',yticklabel);
    ytickangle(-60);
    view(90,90)
    fig_size2 = [-1921         178         475         767];
    set(gcf, 'OuterPosition', fig_size2)
    fig_name = strcat('BAZ_', num2str(min_baz), '_', num2str(max_baz), '_profile_', num2str(i_prof), '.png');
    exportgraphics(gcf, fullfile(outputdir, fig_name), 'BackgroundColor', 'white',  'Resolution', 2000); % 设置分辨率
%     close all
end