%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%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=['040'];
diss='no';
direct='/Users/emmanuel.boss/Desktop/EXPORTS01/IOPPackage/Epoch1Day8/'


%reading data in and getting their sampling time
[time, P, T, S, C]=rd_SB37([direct,'run_24_CTD-ENGR.',fnam]);
time_ctd=time;
time_conductivity=time-3/(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));
time_salinity=(time_ctd(I));
T=T(I);
P=P(I);
time_ctd=time_salinity;
S=SS;
[SVAN,sigma]=swstate(S,T,P);

[time Vchl]=rd_analog([direct,'run_29_ANALOG.',fnam]);
time_chl=time-2.75/(24*3600); %assume a delay for fuorometer
%median filter for analogue 5 sample median  filter (1.25 sec):
Vchl_new=medfilt1(Vchl,5);

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

[time FDOM]=rd_Eco1ch([direct,'run_23_ECO.',fnam]);
time_FDOM=time;

%determine begining and end time for merging.
I=find(time_ctd>=time_chl(1) & time_ctd>=time_bb9(1)  & time_ctd>=time_FDOM(1));
I1=find(time_ctd<max(time_chl) & time_ctd<=max(time_bb9) & time_ctd<=max(time_FDOM));
I2=find(time_ctd>=time_ctd(min(I)) & time_ctd<=time_ctd(max(I1)));
time_merge=time_ctd(I2); 
clear dat 
%create interpolated data matrix
dat1(:,1)=(time_merge-min(time_merge))*24*3600; %time in secs'
dat1(:,[2:5])=[P(I2),T(I2),S(I2),sigma(I2)];
dat1(:,6)=interp1(time_chl,Vchl,time_merge,'linear');
dat1(:,7)=interp1(time_FDOM,FDOM,time_merge,'linear');
for j=1:9
    dat1(:,7+j)=interp1(time_bb9,BB9(:,j),time_merge,'linear');
end

figure(1)
plot(dat1(:,3),-dat1(:,2))
figure(2)
plot(dat1(:,4),-dat1(:,2))
figure(3)
plot(dat1(:,5),-dat1(:,2))
figure(4)
plot(dat1(:,6),-dat1(:,2))
figure(5)
plot(dat1(:,7),-dat1(:,2))
figure(6)
plot(dat1(:,8:16),-dat1(:,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 





