disp('Pick data directory for processing')
disp('')
CWD=pwd;
Data_Dir=uigetdir;
%cd(Data_Dir)
datafiles=uipickfiles('filterspec',[Data_Dir,'/User*']);
cd(CWD)
numfiles=length(datafiles);

Max_Velocity=19.4;
SNR_cutoff=1.008;

for j=1:numfiles
  %FILENAME=fullfile(Data_Dir,datafiles(j));
  fid=fopen(char(datafiles(j)));
  temp=read_CSM(fid,0.0);
  fclose(fid)
  tt=datevec(temp.start_time);
  temp.timestamp(j)=datenum([tt(1) tt(2) tt(3) tt(4) tt(5) tt(6)]);

  temp.name=datafiles(j);
  temp.datet=datestr(temp.start_time,'mm/dd/yyyy');
  lidar=temp;
  [na,nr]=size(lidar.SNR);
  clear temp
 % meanSNR=mean(mean(lidar.SNR(:,nr-50:nr)));
%
% --- Filter --------------------------------------------------------
%disp('--------------------------------------------------------------------------------')
Max_Velocity=19.;
SNR_cutoff=1.008;
avg_ang=10;
avg_rad=20;
dang=floor(avg_ang/abs(lidar.azimuth(10,1)-lidar.azimuth(11,1)))+1;
dr=floor(avg_rad/abs(lidar.ranges(1)-lidar.ranges(2)))+1;
%  [rws_filt,snr_filt,beta_filt]=filterrws(lidar,dang,dr,SNR_cutoff,Max_Velocity);
  rws_filt=medfilt2(lidar.RWS,[1,60]);
  snr_filt=medfilt2(lidar.SNR,[1,60]);
  beta_filt=medfilt2(lidar.Beta,[1,60]);
  
  lidar.rws_filt=rws_filt;
  lidar.snr_filt=snr_filt;
  lidar.beta_filt=beta_filt;
  ind=find(abs(lidar.RWS)>Max_Velocity);
  lidar.rws_filt(ind)=NaN;
  lidar.snr_filt(ind)=NaN;
  lidar.beta_filt(ind)=NaN;
  ind=find(lidar.SNR<SNR_cutoff);
  lidar.rws_filt(ind)=NaN;
  lidar.snr_filt(ind)=NaN;
  lidar.beta_filt(ind)=NaN;
  
  disp('Filtering Complete.')
  vad=lidar;
  clear rws_filt snr_filt beta_filt

  prof=vvp_regression(vad);
  ind=find(prof.nind<9);
  prof.beta(ind)=NaN;
  prof.turb(ind)=NaN;
  prof.vels(ind,:)=NaN;
  prof.theta(ind)=NaN;
  prof.u(ind)=NaN;
  prof.v(ind)=NaN;
  prof.w(ind)=NaN;
  prof.Vh(ind)=NaN;
  ind=find(abs(prof.u)>60 | abs(prof.v)>60 | abs(prof.w)>60);
  prof.beta(ind)=NaN;
  prof.turb(ind)=NaN;
  prof.vels(ind,:)=NaN;
  prof.theta(ind)=NaN;
  prof.u(ind)=NaN;
  prof.v(ind)=NaN;
  prof.w(ind)=NaN;
  prof.Vh(ind)=NaN;
  prof.start_time=lidar.start_time;
  
  ind=find(prof.turb>1);
  ts(j)=prof.start_time;
  Vh(j,:)=prof.Vh;
  Vh(j,ind)=NaN;
  theta(j,:)=prof.theta;
  theta(j,ind)=NaN;
  w(j,:)=prof.w;
  w(j,ind)=NaN;
  
  [tdir,tfile,tx]=fileparts(char(datafiles(j)));
  filesave=[datestr(prof.start_time,'yyyymmdd_HHMMSS'),'_profile','.mat'];
  ttdir=datestr(prof.start_time,'yyyymmdd');
  if ~exist(['C:/lidar/Hampton_May2019/analysis/',ttdir],'dir')
      mkdir(['C:/lidar/Hampton_May2019/analysis/',ttdir])
  end
  save(fullfile(['C:/lidar/Hampton_May2019/analysis/',ttdir],filesave),'prof','lidar')
  
  hs=panel3(prof);
  saveas(hs,fullfile(['C:/lidar/Hampton_May2019/analysis/',ttdir],[datestr(prof.start_time,'yyyymmdd_HHMMSS'),'.png']))
  pause(2)
  close(hs)
  clear prof lidar
  
end