clc;clear all;close all
addpath('/data3/yiwen/matlab_toolbox/t_tide/')
file1='/data3/yiwen/matlab_coawst/particle_tracking/ROMS_log_files/Bitou_WIND/TS_const/Check_UV/20240704_0731/Bitou_ocean_his.nc'
lon=ncread(file1,'lon_rho');
lat=ncread(file1,'lat_rho');

SSH=ncread(file1,'zeta'); %JUL
% SSH=ncread(file2,'zeta'); %AUG

i= 108:115;j= 80;
for k=1:length(i)
SSH_M{k}=squeeze(SSH(i(k),j,:));
end

%%
%======[Sec1.] Choose High & Low Tide ======%
min_peak_distance = 240; %設定最小峰距離 [12 hrs] 20*12 

% 找滿潮（高點）
[highTideVals, highTideIdx] = findpeaks(SSH_M{1}, ...
    'MinPeakProminence', 0.05, ...           % 可依實際波動幅度調整
    'MinPeakDistance', min_peak_distance);

% 找乾潮（低點）
[lowTideVals, lowTideIdx] = findpeaks(-SSH_M{1}, ...
    'MinPeakProminence', 0.05, ...
    'MinPeakDistance', min_peak_distance);
lowTideVals = -lowTideVals;


%---- Manual choose points [x]-----%
HT_idx=lowTideIdx;  HT_idx(HT_idx<3842)=[];
LT_idx=highTideIdx; LT_idx(LT_idx<3842)=[];
lowTideVals(lowTideIdx<3842)=[];
highTideVals(highTideIdx<3842)=[];
%------ time shift [+16hrs]-------%
startTime = datetime(2024, 7, 04, 0, 0, 0);
endTime = datetime(2024, 7, 31, 23, 57, 0);  
timeStep = minutes(3); 
timeSeries = startTime:timeStep:endTime;

set(0,'defaultfigurecolor','w')
figure;
plot(timeSeries, SSH_M{1},'color','b','Linewidth',2); hold on;
plot(timeSeries(LT_idx), highTideVals, 'r^', 'MarkerFaceColor', 'r');
plot(timeSeries(HT_idx), lowTideVals, 'gv', 'MarkerFaceColor', 'g');
xlabel('time'); ylabel('SSH (m)');
legend('SSH', 'High Water[LT]', 'Low Water[HT]');
set(gca,'XMinorTick','on','YMinorTick','on','TickDir','out');ytickformat('%.2f')
set(gca,'fontsize',14,'linewidth',2);grid on;
xlim([datetime(2024, 7, 12, 0, 0, 0), datetime(2024, 8, 01 ,0, 0, 0)])


return;
%---- save to mat -----%
patho='/data3/yiwen/matlab_coawst/particle_tracking/Offline_output/2025/0519_tracking/Jul_5days/Tide/'
fn = [patho 'Tide_0712_0731.mat'];
save(fn,'LT_idx','HT_idx')
%%
%======[Sec2.] Choose Spring & Neap Tide ======%
uniqueDays = unique(dateshift(timeSeries, 'start', 'day'));
dailyLabel = strings(length(uniqueDays), 1);  % 儲存每一天是大潮、小潮或一般


for i = 1:length(uniqueDays)
    % 當天時間範圍
    dayStart = uniqueDays(i);
    dayEnd = dayStart + days(1);

    % 擷取當天資料
    idx = timeSeries >= dayStart & timeSeries < dayEnd;
    ssh_day = SSH_M{1}(idx);

    if isempty(ssh_day)
        dailyLabel(i) = "NoData";
        continue;
    end

    % 計算潮差
    tideRange = max(ssh_day) - min(ssh_day);

    
    if tideRange >= TOP_13
        dailyLabel(i) = "大潮";
    elseif tideRange <= BOT_13
        dailyLabel(i) = "小潮";
    else
        dailyLabel(i) = "一般";
    end
end


T = table(uniqueDays', dailyLabel,...
    'VariableNames', {'Date', 'TideType'});

%---- save to mat -----%
% patho=''
% fn = [patho 'Tide_0804_0823.mat'];
% save(fn,'LT_idx','HT_idx')










