% this file takes ADCP data from rdradcp process,
% file trims time sequence, depth, rotates to major/minor axis,
% 
% Justin Rogers, stanford efml, 9/2012

run presentation_plot
clc, clear all, close all;

files=dir('*.000');
bottom_trim = 2.5; % data to drop from bottom (m)
%%
for ii=1:size(files,1); % get order for files in increasing mab
filename=files(ii).name;
[adcp,cfg,ens,hdr]=rdradcp(filename);

if size(adcp.mtime,2)>10

%%  trim time extent
start_time=datenum(2012,9,19,15,0,0);
end_time=datenum(2012,9,25,17,0,0);

time_id=find(adcp.mtime>=start_time & adcp.mtime<=end_time);
mtime_proc=adcp.mtime(time_id);
depth_proc=adcp.depth(time_id);
temperature_proc=adcp.temperature(time_id);

%% trim vertical extent

%calculate bin height
bin_height = cfg.ranges+cfg.cell_size/2;

% calculate vertical data to drop
Rmax = mean(depth_proc)*cos(deg2rad(20));
bins_drop = size(find(bin_height>Rmax),1);
bins_drop_bottom = size(find(bottom_trim>bin_height),1);
bin_height_good = bin_height(1:end-bins_drop);

% trim data above Rmax
east_vel_proc=adcp.east_vel(1:end-bins_drop,time_id);
north_vel_proc=adcp.north_vel(1:end-bins_drop,time_id);
vert_vel_proc=adcp.north_vel(1:end-bins_drop,time_id);
error_vel_proc=adcp.error_vel(1:end-bins_drop,time_id);
corr_proc=adcp.corr(1:end-bins_drop,time_id);
perc_good_proc=adcp.perc_good(1:end-bins_drop,time_id);
intens_proc=adcp.intens(1:end-bins_drop,time_id);

%% low pass filter velocity data
t_window = 10/60/24; % averaging 10 min window
dt = mtime_proc(2)-mtime_proc(1); % data time step
window = round(t_window/dt);

tempu = 0*adcp.east_vel;
tempv = 0*adcp.east_vel;
tempw = 0*adcp.east_vel;

for i = window/2+1:size(tempu,2)-window/2-1;
    tempu(:,i) = mean(adcp.east_vel(:,i-window/2:i+window/2),2);
    tempv(:,i) = mean(adcp.north_vel(:,i-window/2:i+window/2),2);
    tempw(:,i) = mean(adcp.vert_vel(:,i-window/2:i+window/2),2);
end

east_vel_avg=tempu(1:end-bins_drop,time_id);
north_vel_avg=tempv(1:end-bins_drop,time_id);
vert_vel_avg=tempw(1:end-bins_drop,time_id);

clear tempu tempv tempw

%% depth average
U = nanmean(east_vel_avg,1); % depth averaged values
V=nanmean(north_vel_avg,1);

%% compute variance
[theta]=adcp_paa(U,V);

%% rotate coordinates

[maj_vel_avg_rot, min_vel_avg_rot]= adcp_rotation(east_vel_avg,north_vel_avg, theta);
[maj_vel_inst_rot, min_vel_inst_rot]= adcp_rotation(east_vel_proc,north_vel_proc, theta);

Urot=nanmean(maj_vel_avg_rot,1);
Vrot=nanmean(min_vel_avg_rot,1);

end
matname = ['ADCP_Processed_',filename,'.mat'];
save(matname);
end