load EN4_temp.mat tempcEN 
load EN4_salt.mat
load grid_EN4.mat
addpath /work/uo0122/u241272/seawater_ver3_3.1/

%Compute ILD

for k=1:42
aux(:,:,k,:)=tempcEN(:,:,1,:) - 0.5;
end

tem2=tempcEN-aux;

for l=1:792
tic
l

 for i=1:360
  for j=1:173
    %ind=find(squeeze(tem2(i,j,:,l))>-0.2 & squeeze(tem2(i,j,:,l))<0.2);
    ind=find(squeeze(tem2(i,j,:,l))<=0);
    if isempty(ind)
    ild05_en4(i,j,l)=NaN;
    else
    ild05_en4(i,j,l)=dep_EN(ind(1));
    %ild(i,j,l)=dep_EN(ind);
    end
    clear ind
  end %j
 end %i
 
toc
end %l


%Compute MLD

for l=1:792
for k=1:42

pden(:,:,k,l)=sw_dens(squeeze(saltEN(:,:,k,l)),squeeze(tempcEN(:,:,k,l)),0);

end %k
end %l


for l=1:792

corden(:,:,1,l)=sw_dens(squeeze(saltEN(:,:,1,l)),squeeze(tempcEN(:,:,1,l)-0.5),0);

end %l


for k=1:42
auxm(:,:,k,:)=corden(:,:,1,:);
end

sigma=pden-auxm;

for l=1:792
tic
l

 for i=1:360
  for j=1:173
    %ind=find(squeeze(tem2(i,j,:,l))>-0.2 & squeeze(tem2(i,j,:,l))<0.2);
    ind=find(squeeze(sigma(i,j,:,l))>=0);
    if isempty(ind)
    mld05_en4(i,j,l)=NaN;
    else
    mld05_en4(i,j,l)=dep_EN(ind(1));
    %ild(i,j,l)=dep_EN(ind);
    end
    clear ind
  end %j
 end %i
 
toc
end %l


%Compute BLT

blt05_en4 = ild05_en4 - mld05_en4; 

new_lon_EN=lon_EN;
new_lon_EN(new_lon_EN>180)=new_lon_EN(new_lon_EN>180)-360;
[y,x]=meshgrid(lat_EN,new_lon_EN);

blt05_en4_grid=blt05_en4;
blt05_en4_grid(361:360+50,:,:)=blt05_en4(1:50,:,:);
blt05_en4_grid(1:50,:,:)=[];

ild05_en4_grid=ild05_en4;
ild05_en4_grid(361:360+50,:,:)=ild05_en4(1:50,:,:);
ild05_en4_grid(1:50,:,:)=[];

mld05_en4_grid=mld05_en4;
mld05_en4_grid(361:360+50,:,:)=mld05_en4(1:50,:,:);
mld05_en4_grid(1:50,:,:)=[];

x_new=x;
x_new(361:360+50,:)=x(1:50,:);
x_new(1:50,:)=[];


%saving

save('trial_blt_ild05_mld_en4.mat','blt05_en4_grid'); 
save('trial_blt_ild05_mld_en4.mat','blt05_en4','-append');
save('trial_blt_ild05_mld_en4.mat','ild05_en4_grid','-append');
save('trial_blt_ild05_mld_en4.mat','ild05_en4','-append');
save('trial_blt_ild05_mld_en4.mat','mld05_en4_grid','-append');
save('trial_blt_ild05_mld_en4.mat','mld05_en4','-append');
