function Final_XYZ = Save_valid_data(varargin)

%%

if isempty(varargin)
    %%% Run not from gui
    XYZ = Read_Cache;
    event = read_eventfile;
else
    %%% Run from GUI
    XYZ = varargin{1}.dataXYZ;
    event = read_eventfile;
end


%%
Final_XYZ = [];

%define day
day = datestr(XYZ.Matlabtime(1),'yymmdd');

for i = 1:length(event)

    %find start and endtimes
    [dum begin_ind] = min(abs(XYZ.Matlabtime-...
        datenum([day event(i).begintime],'yymmddHH:MM:SS')));
    [dum end_ind] = min(abs(XYZ.Matlabtime-...
        datenum([day event(i).endtime],'yymmddHH:MM:SS')));

    % Extract from dataset
    Final_XYZ = [Final_XYZ ; XYZ.X_RD(begin_ind:end_ind)'...
        XYZ.Y_RD(begin_ind:end_ind)'...
        XYZ.Z_RD(begin_ind:end_ind)'- str2double(event(i).surveyorheight)]; 

end
 %plot outcome
figure
scatter(Final_XYZ(:,1),Final_XYZ(:,2),3,Final_XYZ(:,3));

% save outcome
fid = fopen('../Products/XYZ_RDNAP.txt','wt');
fprintf(fid,['This file is automatically generated by the slidergui.\n'...
    'It contains the surface elevation of the measured path \n' ...
    'The values are extracted from the total survey and corrected for walker heigth \n\n'...
    'Survey of \t' datestr(XYZ.Matlabtime(1),'mm/dd/yyyy') '\n' ...   %%% Edit MA. 22/09 format voor de surveydate veranderd voor 't transect2netCDF script  
    'Processed on\t' datestr(now) '\n' ...
    'Use for monthly NetCDF = 1 \n\n' ...
    'X_rd [m]\t Y_rd [m]\t Z_NAP [m]\n']);

fprintf(fid, '%.3f\t %.3f\t %.3f\n', Final_XYZ');

fclose(fid);

