file=uipickfiles('FilterSpec','C:/Projects/DRI-BP/*.mat');
nfiles=length(file);
for j=1:nfiles
    [datapath, filename, ext, versn] = fileparts(char(file(j)));
    if ~exist([datapath,'/analysis'],'dir')
        mkdir([datapath,'/analysis'])
    end
     writedir(j)=cellstr([datapath,'/analysis']);
     files(j)=cellstr([filename,'.mat']);
end
SNR_thresh=1.02;
for jfiles=1:nfiles
%     fid=fopen(char(file(jfiles)));
%     lidar=read_Proc_profiles(fid,0.0);
%     fclose(fid);
    load(char(file(jfiles)));
    
    vad=lidar;
    vad.number_of_gates=lidar.number_of_gates-14;
    vad.ranges=lidar.ranges(15:end);
    vad.RWS=lidar.RWS(:,15:end);
    vad.SNR=lidar.SNR(:,15:end);
    vad.Beta=lidar.Beta(:,15:end);
    vad.xd=lidar.xd(:,15:end);
    vad.yd=lidar.yd(:,15:end);
    vad.zd=lidar.zd(:,15:end);
    vad.azimuth=lidar.azimuth(:,15:end);
    vad.elevation=lidar.elevation(:,15:end);
    [na nr]=size(vad.RWS);

    [inda,indb]=size(vad.SNR);
    numble=inda*indb;
    snr=reshape(vad.SNR,numble,1);
    rws=reshape(vad.RWS,numble,1);
    zd=reshape(vad.zd,numble,1);
    ele=reshape(vad.elevation,numble,1);
%    p=reshape(p,numble,1);
    ind=find(snr<SNR_thresh | abs(rws./cosd(ele+0.001))>15 );
    snr(ind)=NaN;
    rws(ind)=NaN;
    snr=reshape(snr,inda,indb);
    rws=reshape(rws,inda,indb);
    zd=reshape(zd,inda,indb);
    vad.SNR=snr;
    vad.RWS=rws;
  
    profile=vvp_regression(vad);
  

    profile_plot
     textfile=fullfile(char(writedir(jfiles)),[char(files(jfiles)),'_profile.png']);
     saveas(hfig,textfile)
     textfile=fullfile(char(writedir(jfiles)),[char(files(jfiles)),'_profile.dat']);
     prtid=print_file(textfile,profile,vad);
     textfile=fullfile(char(writedir(jfiles)),[char(files(jfiles)),'_profile.mat']);
     save(textfile,'profile');
     close(hfig)
     Vh(:,jfiles)=profile.Vh;
     w(:,jfiles)=profile.w;
     theta(:,jfiles)=profile.theta;
     height=profile.heights;
     shear(:,jfiles)=sqrt(profile.vel(:,3).^2+profile.vel(:,4).^2);
     turb(:,jfiles)=profile.turb;
    
     clear lidar vad profile

end