function [averagelap,parameters,covarmatrix,statistics] = laptime_LS_adjustment(car,stintdistance)
%LAPTIME_LS_ADJUSTMENT Summary of this function goes here
%   Detailed explanation goes here
%% Setup the Import Options
opts = delimitedTextImportOptions("NumVariables", 2);

% Specify range and delimiter
opts.DataLines = [1, Inf];
opts.Delimiter = ",";

% Specify column names and types
opts.VariableTypes = ["string", "string"];
opts = setvaropts(opts, [1, 2], "WhitespaceRule", "preserve");
opts = setvaropts(opts, [1, 2], "EmptyFieldRule", "auto");
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";

% Import the data
metadata = readtable(car+"/"+"metadata.txt");
k=length(metadata.date);

for i=1:k
data = readtable(car+"/"+metadata.date(i)+".txt", opts);
[km, perc]=laptime_import(data.Var1(:),data.Var2(:),metadata.length(i),...
    metadata.pb(i));
pos=metadata.pos(i);
q=length(km);
if i==1
    L=[km,perc];
    pVec=ones(q,1);%*pos^1;
else
    L=[L(:,1),L(:,2);
        km,perc];
    pVec=[pVec;
        ones(q,1)];%*pos^1];
end
end
figure
plot(L(:,1),L(:,2),'o')
hold all

n=length(L);
%% Least-squares adjustment
A=[L(:,1).^2, L(:,1), ones(n,1)];
l=L(:,2);
NV=10;
itteration=0;
while max(NV)>2 && itteration<=50
n=length(l);
u=3;
f=n-u;
P=pVec.*eye(n);    
ATl=A'*P*l;
ATA=A'*P*A;
Qxx=inv(ATA);

xd=Qxx*ATl;

ld=A*xd;

%% "Data snooping"
v=ld-l;
vTv=v'*P*v;
sig0=sqrt(vTv/f);

NV=abs(v)/sig0;
log=NV<=2;

A=A(log>0,:);
pVec=pVec(log>0);
l=l(log>0,:);
itteration=itteration+1;
end
%% Test

Sigxx=Qxx*sig0^2;
sigx=sqrt(diag(Sigxx));

varPlotX=0:stintdistance;
varPlotY=xd(1)*varPlotX.^2+xd(2)*varPlotX+xd(3);
plot(A(:,2),l,'x')
plot(varPlotX,varPlotY)
title(car)
xlabel('race distance [km]')
ylabel('laptime [% of personal best]')
ylim([1 1.05])
hold off

averagelap=sum(varPlotY)/stintdistance;
parameters=xd;
covarmatrix=Sigxx;
statistics=[length(L); length(l)];
end

