pom=pom;
Remove["Global`*"];
SetDirectory[NotebookDirectory[]];
$HistoryLength=3;

fnom=50.;
Tnom=(1/fnom);
sr=Round[(96000/50)];



kperSampl=1.6;
sigmaSum=.4;
(*kPerSampl nam rika cca kolik period mam nasamplovano, vztazeno k Tnom*)
amplSampl=5.0489;
fiSampl=0.564;
kω=1.014897;
ω=kω*2.*Pi*fnom;
fcepom1[t_]:=amplSampl*Sin[ω*t+fiSampl]+0.3*(0.5*Sin[7*ω*t+0.125]+0.5*Sin[5*ω*t+0.125]+0.25*Sin[11*ω*t-0.125]);
fcepom[t_]:=amplSampl*Sin[0.7fcepom1[t]]
Δtnom=(Tnom/sr)//N;

SeedRandom[3];
sums=Table[RandomReal[NormalDistribution[0.5,sigmaSum]],{t,0,kperSampl*Tnom,Δtnom}];
datsignal=Table[fcepom[t],{t,0,kperSampl*Tnom,Δtnom}];
dSpom=sums+datsignal;

plSamples=ListPlot[dSpom,Joined->False,PlotStyle->{PointSize[0.005],Hue[0.666]},AxesLabel->{"i [-]","uSample [V]"},GridLines->Automatic];
plsigsamps=ListPlot[datsignal,Joined->False,PlotStyle->{PointSize[0.005],Black},AxesLabel->{"i [-]","uSample [V]"},GridLines->Automatic];
plobe=Show[plSamples,plsigsamps]

ClearAll[vydejNx5];
vydejNx5[listDat_]:=Module[{k1=0.8,aclist,x1,y1,x2,y2,x3,y3,Δmozne=0.1,mozne,start,zkrot,krok,fce,nx,f,sd2,nSampl},
sd2[list_]:=Module[{mean,mean2},mean=Mean[list];mean2=Mean[list*list];mean2-(mean^2)];
aclist=Accumulate[listDat];
nSampl=Length[aclist];
fce[nOkno_]:=Module[{rn,soucty,sigma,ns},
rn=Range[nSampl-nOkno];
soucty=Prepend[(aclist[[#+nOkno]]-aclist[[#]]&/@rn),aclist[[nOkno]]];
ns=Length[soucty];
sigma=(1./(nOkno^2))sd2[soucty];
{nOkno,sigma}
];
mozne=Range[Round[(1-Δmozne)*sr],Round[(1+Δmozne)*sr]];
start=fce/@{mozne[[1]],Round[0.5*(mozne[[1]]+mozne[[-1]])],mozne[[-1]]};

zkrot[n_]:=If[n<mozne[[1]],mozne[[1]],If[n>mozne[[-1]],mozne[[-1]],Round[n]]];

krok[body:{{x1_,y1_},{x2_,y2_},{x3_,y3_}}]:=Module[{nb,yka,miny},
yka=body/.{a_,b_}:>b;
miny=Min[yka];
nb=Which[miny==y2,{fce[Round[0.5*(x1+x2)]],fce[Round[0.5*(x3+x2)]]},
miny==y3,{fce[zkrot[x3+k1*(x3-x2)]]},miny==y1,{fce[zkrot[x1-k1*(x2-x1)]]}];
Sort[Take[Sort[Union[nb,body],#1[[2]]<#2[[2]]&],3],#1[[1]]<#2[[1]]&]
];

{{x1,y1},{x2,y2},{x3,y3}}=FixedPoint[krok,start];
nx=((y1+2 x2 y1-4 x2 y2-y3+2 x2 y3)/(2 (y1-2 y2+y3)));
{f=((fnom*sr)/nx),100*(kω-(f/fnom))}
];
vydejNx5[dSpom]//Timing