%% aquadop data processing

close all, clear all;clc

filename = 'PS2MHz02_5447';

%%
a = importdata(strcat(filename,'.hdr'),'');
cells = cell2mat(textscan(char(a(11)),'%*s %*s %*s %f %*s'));
cell_size = cell2mat(textscan(char(a(12)),'%*s %*s %f %*s'))/100;
blanking_dist= cell2mat(textscan(char(a(16)),'%*s %*s %f %*s'));
sample_time = cell2mat(textscan(char(a(10)),'%*s %*s %f %*s'));

z = blanking_dist+cell_size+cell_size*[0:1:cells-1];

E_vel = dlmread(strcat(filename,'.v1'));
N_vel = dlmread(strcat(filename,'.v2'));
z_vel = dlmread(strcat(filename,'.v3'));
sen =  dlmread(strcat(filename,'.sen'));
Press = sen(:,14);
depth  = Press*1E4/9.81/1025; %depth in m

Temp = sen(:,15);
bins_keep = find(z<mean(depth), 1, 'last' );
E_avg = mean(E_vel(:,1:bins_keep),2);
N_avg = mean(N_vel(:,1:bins_keep),2);
Vel_mag = sqrt(E_vel.^2+N_vel.^2);
Vel_mag_avg = mean(Vel_mag(:,1:bins_keep));
datenumber = datenum(sen(:,3),sen(:,1),sen(:,2),sen(:,4),sen(:,5),sen(:,6));

%% filter data
t_window = 10/60/24; % averaging 10 min window
dt = sample_time/3600/24; % data time step
window = round(t_window/dt);

E_vel_filt = 0*E_vel;
N_vel_filt = 0*E_vel;
z_vel_filt = 0*E_vel;

for i = window/2+1:size(E_vel_filt,1)-window/2-1;
    E_vel_filt(i,:) = mean(E_vel(i-window/2:i+window/2,:),1);
    N_vel_filt(i,:) = mean(N_vel(i-window/2:i+window/2,:),1);
    z_vel_filt(i,:) = mean(z_vel(i-window/2:i+window/2,:),1);
end

east_vel_avg=mean(E_vel_filt,2);
north_vel_avg=mean(N_vel_filt,2);
vert_vel_avg=mean(z_vel_filt,2);

%%

save(strcat(filename))