function makemaxdet(~,~,Empty_Button, Buttons, rbgautopga, AxesD, RegSlider, AutoPGAText, SensSlider)
data = get(Empty_Button,'UserData');

if data.isautodetect == 1
    scal = get(SensSlider(1),'Value');
    maxdet = str2num(get(AutoPGAText(3),'String')); 
    maxdet = round(maxdet);

    if ~isfield(data,'D') || isempty(maxdet)
        %     msgbox('Choose at least one criterion')
        return
    end

    if maxdet<1
        maxdet = 1;
    end

    Val = data.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) 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);
    data.isautodetect = 1;
    
    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.D','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');
    
    data.isautodetect = 1;
    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,[]);
            end
        else
            onoffButton(Buttons,17,[]);
        end
    end
end