clc;clear all;close all
pathi='/data3/yiwen/matlab_coawst/particle_tracking/Offline_output/2025/0113_tracking/3hrs/Aug_6days/Check_UV/'
% pathi='/data3/yiwen/matlab_coawst/particle_tracking/Offline_output/2025/0113_tracking/3hrs/Jul_6days/Check_UV/'

% fileNames = {'POS_0804_6D.mat', 'POS_0809_6D.mat', 'POS_0814_6D.mat', ...
%              'POS_0819_6D.mat', 'POS_0824_6D.mat','POS_0829_6D.mat','POS_0903_6D.mat'};

fileNames = {'POS_0712_6D.mat', 'POS_0717_6D.mat', 'POS_0722_5D_T.mat', ...
             'POS_0727_6D.mat', 'POS_0801_6D.mat'};

allCount = {};  % Count
allLonLat = {}; % lon_lat
for i = 1:length(fileNames)
    file_path = fullfile(pathi, fileNames);
    
    data = load(file_path{i});
    countData = data.Count;
    lonLatData = data.lon_lat;

    % 0804 ~ 0819，delete last varibles
%     if contains(fileNames{i}, {'0804', '0809', '0814', '0819'})
        countData = countData(1:end-1);
        lonLatData = lonLatData(1:end-1);
%     end
    
    % save to cell
    allCount = [allCount, countData];
    allLonLat = [allLonLat, lonLatData];
end

batchSize = 8; %for one day
numBatches = floor(length(allLonLat) / batchSize); 

mergedallLonLat = cell(1, numBatches);
for i = 1:numBatches
    batchData = allLonLat((i-1)*batchSize + (1:batchSize)); 
    mergedallLonLat{i} = cell2mat(batchData'); 
end

%======= Count the repeat(i,j) numbers =======%
all_lon_lat = {};
unique_lon_lat={};
idx={};Count={};

for IDX = 1:size(mergedallLonLat,2)
%--------------------------------------%
all_lon_lat{IDX} = mergedallLonLat{IDX}(:,1:2);
% Determine unique latitude and longitude points and their number of occurrences
[unique_lon_lat{IDX}, ~, idx{IDX}] = unique(all_lon_lat{IDX}, 'rows', 'stable');
counts{IDX} = accumarray(idx{IDX}, 1);

% Result: Count(i, j, number)
Count{IDX} = [unique_lon_lat{IDX}, counts{IDX}]; 
end

% return;
patho=pathi;
% fn = [patho 'POS_0804_0907_6D.mat'];
fn = [patho 'POS_0712_0805_6D.mat'];
save(fn,'Count','all_lon_lat','allCount')


%%
% date_list = 804:5:824; 
% num_days = numel(date_list);
% 
% Count = cell(1, num_days);
% for i = 1:num_days
%     date_num = date_list(i);
%     filename = sprintf('POS_0%d_6D.mat', date_num);
%     file_path = fullfile(pathi, filename);
% 
%     if exist(file_path, 'file')
%         load(file_path, 'lon_lat'); 
%         all_lon_lat = [];
% 
%         for IDX = 1:numel(lon_lat) 
%             all_lon_lat = [all_lon_lat; lon_lat{IDX}]; 
%         end
% 
%         [unique_lon_lat, ~, idx] = unique(all_lon_lat, 'rows', 'stable');
%         counts = accumarray(idx, 1);
% 
%         Count{i} = [unique_lon_lat, counts];
% 
%         fprintf('finish %s\n', filename);
%     else
%         fprintf('file %s does not exist \n', filename);
%         Count{i} = []; 
%     end
% end










