% close all;
clear all;clc;
datestr(now,'HH:MM')
addpath(genpath('/home/yckuo/MATLAB/m_map/'))
addpath('/data3/yiwen/matlab_coawst/particle_tracking/')
%-  set the initial drifter positions------------------------------
%==================================%
% loading spun_up :: U & V % 
pathi='/data3/yiwen/matlab_coawst/particle_tracking/0926_tracking/'
load([pathi,'spun_up_10days.mat'])
lon=lon(:,1);lat=lat(1,:);
%======================== particle domain =============================%
x1=linspace(121.9125,121.9130,30);y1=linspace(25.1242,25.1285,30);
[x11,y11]=meshgrid(x1,y1);
% 
x2=linspace(121.9130,121.9175,30);y2=linspace(25.1280,25.1285,30);
[x22,y22]=meshgrid(x2,y2);
%=========================================================================%
p=1; 
for i=1:size(x11,1)
    for j=1:size(x11,2)    
    xpos(p,1,1)=x11(i,j);ypos(p,1,1)=y11(i,j);
    xpos2(p,1,1)=x22(i,j);ypos2(p,1,1)=y22(i,j);  
    p=p+1;
    end
end
    mf=size(xpos,1);
    %Default:60*10 (time step [mins])
    %test for smaller dt  [W&N Bdy] 
    dtuv=1*60;                       
    testmon0=1;
for testmon=testmon0
    ditt=1; 
    xpos1(:)=xpos(:,1,1);ypos1(:)=ypos(:,1,1);
    TT=0;
    %(0hrs:1152 / 6hrs=1212 / 12hrs=1272 / 18hrs=1332) %
    dstart=1332; 
    m=2881;mon1=1;     
for  d=dstart:m      
  for i=1:mf   
      um2=u6(:,1:end-1,d);vm2=v6(1:end-1,:,d);  
      um2(isnan(um2))=0;vm2(isnan(vm2))=0;
       A=find((xpos1(i)-lon)>=0); B=find((ypos1(i)-lat)>=0);
%      A2=find((xpos2(i)-lon)>=0); B2=find((ypos2(i)-lat)>=0);
   if (isempty(A==1)|isempty(B==1)|length(A)==length(lon)|length(B)==length(lat) ) 
          xpos(i,d,mon1)=xpos1(i);ypos(i,d,mon1)=ypos1(i);
%   if (isempty(A2==1)|isempty(B2==1)|length(A2)==length(lon)|length(B2)==length(lat)) 
%         xpos2(i,d,mon1)=xpos2(i);ypos2(i,d,mon1)=ypos2(i);

else
   [C,ix]=min(abs(xpos1(i)-lon(A)));[C,iy]=min(abs(ypos1(i)-lat(B)));

% c--------update the drifter positions-------------- %
  [xpos1(i),ypos1(i)] = partical_B_new(xpos1(i),ypos1(i),um2,vm2,lon,lat',ix,iy,dtuv);

  end
     xx(i,ditt)=xpos1(i);yy(i,ditt)=ypos1(i);
     end
    ditt=ditt+1;     
end

end


%% save to mat
patho='/data3/yiwen/matlab_coawst/particle_tracking/1002_tracking/boundary_sp2/';
fn = [patho 'case2_18hr_A2.mat'];
save(fn,'xx2','yy2')

