function autodetectPGA(~, ~, Empty_Button, Buttons, rbgautopga, AxesD, RegSlider, AutoPGAText, SensSlider,Recondition,DataText)
% function newautodetectPGA_temp(~, ~, Empty_Button, Buttons, rbgautopga, AxesD, RegSlider, AutoPGAText, SensSlider,Recondition,DataText)

%% read data and chosen (combined) Criteria
data = get(Empty_Button,'UserData');

Cr = zeros(1,5);
for i = 1:5
    Cr(i) = get(rbgautopga(i),'Value');
end

maxdet = str2num(get(AutoPGAText(3),'String')); 
maxdet = round(maxdet);
% check for missing/wrong inputs
if sum(Cr) == 0 || ~isfield(data,'D') || isempty(maxdet)
%     msgbox('Choose at least one criterion')
    return
end

if maxdet<1
    maxdet = 1;
end

data.isautodetect = 0;
k = size(data.D,1);
if isfield(data,'time') == 1
    t = data.time;
else
    t = 1:k;
end   

scal = get(SensSlider(1),'Value');
Dn = data.D/max(max(data.D));       

%% apply chosen criteria and combine the obtained values

% initialize needed Variables
Val = [];           %refined data searched for peaks
maxVal = [];        %used to normalize combined Values 

%detect local minima in the 2nd derivative by x as peaks
if Cr(1)
    mx = 4;
    crit = crit1(Dn,data.x,mx);
%     crit = diff(Dn,2)
    crit = opt(crit,mx);
    maxVal = [maxVal,max(crit)];
    Val = [Val;crit];
end

%detect local minima in local variance in x as peaks
if Cr(2) 
    mx = 5;
    crit = crit3(Dn,mx);  
    critb = max(crit1(Dn,data.x,mx));
    combine = zeros(1,size(crit,2));
    for i = 1:size(crit,1)
        combine = max(combine,ismaxbool(crit(i,:)));
    end
    crit = critb;
    for i = 1:size(critb,1)
        crit(i,:) = crit(i,:).*combine;
    end
    crit = max(crit,0);
    crit = [zeros(1,mx) , crit , zeros(1,mx)];
    maxVal = [maxVal,max(crit)];
    Val = [Val;crit];
end

%detect local minima in the 2nd derivatives of the first ns right singular vectors as peaks
if Cr(3)  
    ns = 3;
    mx = 4;
    crit = crit5(data.S,data.V,data.x,ns,mx);
    crit = opt(crit,mx);
    maxVal = [maxVal,max(crit)];
    Val = [Val;crit];
end

%detect local minima/maxima in the 1st derivative by t as peaks
if Cr(4)
    mt = 11;
    crit = crit2(Dn,t,mt);
    crit = opt(crit)+opt(-crit);
    maxVal = [maxVal,max(crit)];
    Val = [Val;crit];
end

%detect local maxima in local variance in t as peaks
if Cr(5)  
    mt = 5;
    crit = crit4(Dn,mt);
    crit = opt(crit);
    maxVal = [maxVal,max(crit)];
    Val = [Val;crit];
%     TEST = 1
%     figure
%     subplot(3,2,[1 2])
%     plot(Dn','k')
%     hold on
%     axis tight
%     crit6(data.S,data.V,4)
end

%% normalize combined values

maxVal = min(maxVal)./maxVal;
for i=1:length(maxVal)
    Val(i,:) = maxVal(i)*Val(i,:);
end
Val = max(Val,[],1);

%% remove/reduce noise
Val = Val-mean(Val);
Val = filt_SG(Val,data.x(2)-data.x(1),2,2);
% Val = smooth(Val,5,'sgolay',2)';

Val = max(Val,0);
Val = peak2(Val);

%% calculate number of returned peaks

Val = Val/max(Val);
data.Val = Val;

md = min(maxdet,length(find(Val>0)));
pts = (1:md)';
[srt,idall] = sort(Val,'descend');
srt = log(srt(pts));

% straight g with the parametric form ab(1)*x+ab(2)*y=1
% ab = [pts(1) srt(1);pts(end) scal]\[1;1];
ab = [pts(1) srt(1);pts(end) srt(end)]\[1;1];
% dd includes the distances of all points to g multiplied by norm(ab,2)
dd = zeros(1,md);
for i=1:md
    dd(i) = abs(ab(1)*i+ab(2)*srt(i)-1);
end

[~,id] = max(dd);

data.autodetectall = idall(1:length(find(Val>0)));
data.bestpeak = id;

id = max(1,min(round(scal*id),md));
tmp = idall(1:id);
data.autodetect = sort(tmp);
% sort(tmp)
data.isautodetect = 1;
data.isbd = 0;

% if Cr(1)
%     StimmtSoNicht = 1
%     data.autodetect = [86 125 184 887 1011 1112 1137 1172];
% end

% close(findobj('type','figure','number',2))
% figure
% hold on
% plot(pts,srt,'LineWidth',1)
% plot(pts,dd,'LineWidth',1)
% plot([pts(1) pts(end)],[srt(1) srt(end)])
% xlim([1,md])

set(Empty_Button,'UserData',data);

mid = min(0,min(min(data.D)));
mad = max(max(data.D))*1.1;
lgntxt = {};
for i=1:length(data.autodetect)
    plot(AxesD,data.x(data.autodetect(i))*[1 1],[mid mad],'linewidth',1.5)
    hold(AxesD, 'on');
    lgntxt{end+1} = num2str(round(10*data.x(data.autodetect(i)))/10);
end
plot(AxesD,data.x(data.id),data.D(:,data.id)','k');
axis(AxesD,'tight');
set(AxesD,'ylim',[mid mad]);
xlabel(AxesD,'channel');
lgn = legend(AxesD,lgntxt);
set(lgn,'fontsize',12,'location','best');
hold(AxesD, 'off');

set(Empty_Button,'UserData',data);


if (isfield(data,'issvd')*isfield(data,'isnovctrs') == 1) && (data.issvd*data.isnovctrs == 1)
    if get(RegSlider(8), 'Value') > 0
        if (isfield(data,'isgivenspec') == 1) && (data.isgivenspec == 1)
            onoffButton(Buttons,17,[4]);
            set(Buttons(4),'BackgroundColor',0.94*[1 1 1]);
            set(Buttons(17),'BackgroundColor',[0.8500 0.3250 0.0980]);
        end
    else
        onoffButton(Buttons,17,[4]);
        set(Buttons(4),'BackgroundColor',0.94*[1 1 1]);
        set(Buttons(17),'BackgroundColor',[0.8500 0.3250 0.0980]);
    end
end

set(Recondition(4),'String','automatic','ForegroundColor','k');
set(DataText(9),'String',[])
set(DataText(8),'String',[])

% basic functions

function crit = crit1(Dn,x,mx)
    crit = -vand2(Dn,x(2)-x(1),mx);

function crit = crit2(Dn,t,mt)
    crit = vand1(Dn',t(2)-t(1),mt);
    crit= crit';

function crit = crit3(Dn,mx)
    crit = localvar(Dn,1,mx);

function crit = crit4(Dn,mt)
    crit = localvar(Dn,2,mt);

function crit = crit5(S,V,x,ns,mx)
    V = abs(V(:,1:ns));
    S = S(1:ns,1:ns);
    crit = -vand2(S*V',x(2)-x(1),mx);

function crit = crit6(S,V,nr)
    colors = [0.8 0 0; 0 0.8 0.8; 0 0 0.8; 0.8 0.8 0];
    V = V(:,1:nr);
    S = S(1:nr,1:nr);
    h = ones(nr,1);
    t = zeros(nr,1);
    for  i = 1:nr
        g = diff(V(:,i),4);
        h(i) = sum(g);
        X = h(i)/h(1)-log(S(i,i)/S(1,1))/log(10);
%         p = ismaxbool(V(:,i))+ismaxbool(-V(:,i));
        p = ismaxbool(abs(V(:,i)));
        P = nonzeros(p.*(1:length(p))')
        k = p.*V(:,i);
        m = 1/sum(p)*sum(abs(p.*V(:,i)));
        t(i) = X*m;
        subplot(3,2,2+i)
        plot(V(:,i))
        axis tight
        hold on 
        plot(xlim(),t(i)*[1 1],'g','LineWidth',1.25)
        plot(xlim(),-t(i)*[1 1],'g','LineWidth',1.25)
        for j = 1:length(P)
            if abs(V(P(j),i))>abs(t(i))
                subplot(3,2,2+i)
                plot(P(j)*[1 1],ylim(),'Color',colors(i,:),'LineWidth',1.25)
                subplot(3,2,[1 2])
                plot(P(j)*[1 1],ylim(),'Color',colors(i,:),'LineWidth',1.25)
            end
        end

    end
%     t

% reduce Values to local maxima
function Val = opt(temp,m)
    for i = 1:size(temp,1)
        temp(i,:) = temp(i,:).*ismaxbool(temp(i,:));
    end
%     for i = 1:size(temp,2)
%         temp(:,i) = temp(:,i).*ismaxbool(temp(:,i));
%     end
    Val = max(max(temp,0));
    if exist('m','var')
        Val = [zeros(1,m) , Val , zeros(1,m)];
    end
%     Val = Val/max(Val);

% return 1 peak per non zero interval
function Val = peak2(temp)
    n = length(temp);
    Val=zeros(size(temp));
    i0 = 1;
    while i0 < n
        while i0<n && temp(i0) == 0
            i0 = i0+1;
        end
        j = i0;
        while j<n && temp(j+1)>0
            j = j+1;
        end
        [~,id] = max(temp(i0:j));
        Val(i0+id-1) = temp(i0+id-1);
        i0 = j+1;
    end

% approximate 2nd derivative
    % find polynomial ax²+bx+c to approximate D on [x-mx,x+mx]
    % a/2 approximates 2nd derivative in x
function deriv2 = vand2(D,h,mx)
    n = size(D,2);
    if ~exist('mx','var')
        mx = 9;
    end
    np = 2*mx+1;             
    M = zeros(np,3);
    
    for i=1:mx      % get M so that M*(a b c) = D(x-mx:x+mx)
        M(i,:) = [(mx+1-i)^2*h^2 -(mx+1-i)*h 1];
        M(np+1-i,:) = [(mx+1-i)^2*h^2 (mx+1-i)*h 1];
    end
    M(mx+1,:) = [0 0 1];
    
    pM = pinv(M);           %pseudoinverse  -> (a b c) = pM * D(x-mx:x+mx)
    sM = sparse(n-2*mx,n);
    for i=1:n-2*mx
        sM(i,i+[1:np]-1) = pM(1,:); %reduce pM to first column
    end
    deriv2 = D*sM';                 %calculate a


% approximate 1st derivative
    % find polynomial bx+c to approximate D on [x-mx,x+mx]
    % b approximates 1st derivative in x
function deriv1 = vand1(D,h,mh)
    n = size(D,2);
    if ~exist('mh','var')
        mh = 9;
    end
    np = 2*mh+1;
    M = zeros(np,2);
    
   for i=1:mh          % get M so that M*(b c) = D(x-mx:x+mx)
        M(i,:) = [-(mh+1-i)*h 1];
        M(np+1-i,:) = [(mh+1-i)*h 1];
    end
    M(mh+1,:) = [0 1];
    
    pM = pinv(M);           %pseudoinverse  -> (b c) = pM * D(x-mx:x+mx)
    sM = sparse(n-2*mh,n);
    for i=1:n-2*mh
        sM(i,i+[1:np]-1) = pM(1,:); %reduce pM to first column
    end
    deriv1 = D*sM';                 %calculate b

% calculate variance on moving window along chosen dimension dim
    % (dim=1 für x / dim=2 für t)
function lv = localvar(D,dim,mp)
    if ~exist('mh','var') 
        mp = 5;
    end
    if ~exist('dim','var')
        dim = 1;
    end
    if dim == 2    
        D = D';                 %transpose to move along time axis 
    end
    lv = zeros(size(D,1),size(D,2)-2*mp);
    for j=1:size(lv,2)
        for i=1:size(lv,1)
            sig = mean(D(i,j:j+2*mp));
            lv(i,j) = sum((D(i,j:j+2*mp) -sig).^2)/(2*mp);
        end
    end
    if dim == 2 
        lv = lv';
    end

function filtD = filt_SG(D,h,mx,ord)
n = size(D,2);
np = 2*mx+1;

M = zeros(np,ord+1);
% for i=1:mx      % get M so that M*(a b c) = D(x-mx:x+mx)
%     for j = 1:ord+1
%         M(i,j) = ((mx+1-i)*h)^(ord+1-j);
%         M(np+1-i,j) = ((mx+1-i)*h)^(ord+1-j);
%     end
% end
% M(mx+1,ord+1) = 1;

for i=-mx:mx
       for j=0:ord
              M(i+mx+1, j+1) = (i)^j;
       end
end

% F = M' * M;
pM = M * (M' * M)^(-1) * M';
filtD = D;
for n = mx+2:n-mx-1
    filtD(n) = D(n-mx:n+mx)*pM(:,mx+1);
end
for i = 1:mx+1
    filtD(i) = D(1:np)*pM(:,i);
end
for i = 0:mx
    filtD(n-mx+i) = D(n-np+1:n)*pM(:,mx+1+i);
end

function m = ismaxbool(t)
m = zeros(size(t));
    for i = 2:length(t)-1
        if t(i)>t(i-1) && t(i)>t(i+1)
            m(i) = 1;
        end
    end