clc;
clf;
clear all;
warning('OFF', 'MATLAB:table:ModifiedAndSavedVarnames')

set(figure(1), 'Renderer', 'painters');

[file,path] = uigetfile('*.csv','MultiSelect','on'); %gets directory

for F = 1:length(file)
myFiles = dir(fullfile(path,file{F}));
N(F') = natsortfiles({myFiles.name});   % sort the filenames!
D(F') = natsortfiles({myFiles.date});
end

%preallocate
peaklocin = zeros(F,1);
peaklocout = zeros(F,1);
locsin = zeros(F,1);
OutVolt = zeros(1,F);
ToFarray = zeros(1,F);

for F = 1:length(file)
fullFileName = fullfile(path,file{F});
fprintf(1, 'Now reading %s\n', fullFileName);

  num = readtable(fullfile(path,file{F}));   %or readtable
 
  % all of your actions for filtering and plotting go here
  A = table2array(num);
  A(1,:) = [];

Time = A(:,1);
Input = A(:,2);
Output = A(:,3);

timeplot = Time*1e6;
 
filterbw = [0.6e6 3e6];
filterlength = 2000;
  
%d= distance between wedges + distance to beam (centre of wedge)
df = finddelay(Input, Output);
Fs = 1/((Time(2,1))-(Time(1,1)));
St = 1/Fs;
dftimeToF = df*St;

%low pass filter
bpinput = bandpass(Input, filterbw, Fs,'ImpulseResponse','iir');

%low pass filter
bpoutput = bandpass(Output, filterbw, Fs,'ImpulseResponse','iir');

%normalise data to -1 - 1
factorin = max([max(bpinput) abs(min(bpinput))]);
normin = bpinput/factorin;
factorout = max([max(bpoutput) abs(min(bpoutput))]);
normout = bpoutput/factorout;

%create envelope of Input
[upin,loin] = envelope(normin,filterlength,'analytic');

%find peak of envelope Input
[pkkin,locsin] = findpeaks(upin,Fs,'MinPeakHeight',0.5);
peaklocin = locsin(1,1)+min(Time);

%create envelope of Output
[upout,loout] = envelope(normout,filterlength,'analytic');

%find peak of envelope Output
[pkkout,locsout] = findpeaks(upout,Fs,'MinPeakHeight',0.5);
peaklocout = locsout+min(Time);

%calc ToF
ToF = (peaklocout(1,1)-peaklocin);

%build array of results
format longG
ToFarray(F') = ToF;

end

combined = transpose([N; D;num2cell(ToFarray);num2cell(OutVolt)]);

msize = 10;

figure(1)
hold on
grid on
ylabel('Time of Flight (s)')
plot(ToFarray, 'x','MarkerSize',msize)
hold off

x0=10;
y0=10;
width=1600;
height=1000;
set(gcf,'position',[x0,y0,width,height])

set(gcf, 'Color', 'w');
%export_fig simpulse20c.eps -nocrop -transparent