%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%This program is designed to merge data collected by multiple instruments with the DH-4
%All data is merged to CTD data, the slowest sampling instrument.
%applies lags to instrument data
clear all
close all

%instrument specific information
Tcal=17.8;

fnam=['034'];
diss='no';
direct='/Users/emmanuel.boss/Desktop/EXPORTS01/IOPPackage/Epoch2Day7/'


%reading data in and getting their sampling time
[time, P, T, S, C]=rd_SB37([direct,'run_24_CTD-ENGR.',fnam]);
figure(1)
plot(time,-P)
[X ,Y]=ginput(2)

%insures profile start at highest point.
%II=find(P==min(P));
%if (time(II)>X(1))
%    X(1)=time(II);
%end
%tar pressure to 1db at surface
dp=min(P)-1; 
I=find(time>=X(1) & time <=X(2));
time_ctd=time(I);
P=P(I)+dp;
T=T(I);
C=C(I);

%compute average salinity for salinity correction of a_g:
time_conductivity=time_ctd+16/(24*3600); %delay between pumped conductivity and temperature
CC=interp1(time_conductivity,C,time_ctd,'linear');
I=find(isfinite(CC));
SS=sw_salt(CC(I)/4.2914,T(I),P(I));
mean_Salinity=nanmean(SS);

[time wl BB9]=rd_BB9counts([direct,'run_22_ECO.',fnam]);
time_bb9=time;

%determine begining and end time for merging.
I=find(time_ctd>=time_bb9(1) & time_ctd<=max(time_bb9));
time_merge=time_ctd(I); 
clear dat 

%create interpolated data matrix
dat1(:,1)=(time_merge-min(time_merge))*24*3600; %time in secs'
dat1(:,[2:3])=[P(I),T(I)];
for j=1:9
    dat1(:,3+j)=interp1(time_bb9,BB9(:,j),time_merge,'linear');
end
%bin data to 3m bins
[dat2,prr]=binpre(dat1',dat1(:,2),ceil(min(dat1(:,2))),floor(max(dat1(:,2))),3,1);
dat2=dat2';

wl=[412,440,488,510,532,595,650,715,880];
darks_fac=[49 51 51 59 56 52 55 56 53];
darks_field=[48.79	50.94	50.76	61.66	54.26	51.39	55.38	56.65 53];
slopes=[1.29e-5 1.415e-5 1.247e-5 1.008e-5 8.666e-6 5.333e-6 4.054e-6 3.24e-6 2.525e-6]; 
%apply calibrations
[betasw,beta90sw,bsw]= betasw_ZHH2009(wl,8,124,mean_Salinity);
dat2(:,6:14)=((dat2(:,6:14)-darks_field).*slopes-betasw)*2*pi*1.1;


figure(1)
plot(dat2(:,3),-dat2(:,2))
figure(2)
plot(dat2(:,4),-dat2(:,2))
figure(3)
plot(dat2(:,5),-dat2(:,2))
figure(4)
plot(dat2(:,6),-dat2(:,2))
figure(5)
plot(dat2(:,7),-dat2(:,2))
figure(6)
plot(dat2(:,6:14),-dat2(:,2))

% %bin data to 1m bins
% [dat2,prr]=binpre(dat1',dat1(:,2),ceil(min(dat1(:,2))),floor(max(dat1(:,2))),1,1);
% dat2=dat2';
% 
% 
% darks_fac=[49 51 51 59 56 52 55 56 53];
% darks_field=[48.79	50.94	50.76	61.66	54.26	51.39	55.38	56.65 53];
% slopes=[1.29e-5 1.415e-5 1.247e-5 1.008e-5 8.666e-6 5.333e-6 4.054e-6 3.24e-6 2.525e-6]; 
% %apply calibrations
% dat2(8:16)=(dat2(8:16)-darks_field)*slopes;

clear dat1 dat 





