function [w x]=sidp3(sidp_parameters, compare_parameters,system,apriori)
kresli=0;
if (kresli); q=0; a=0; b=0; col(1)='b';col(2)='r' ;col(3)='c' ;col(4)='m' ;col(5)='y';end
eps=10^-4;
mode=0;
compare_parameters.student=quantile(trnd((sidp_parameters.num_of_candidates-1)*ones(1,100000)),(1-compare_parameters.alpha)^(1/(sidp_parameters.num_of_candidates-1)));
compare_parameters.rinott=4;

apriori.eta0=abs(apriori.y0)/system.sigma;
%apriori.eta0=0;

apriori.beta0=abs(apriori.b0)/sqrt(apriori.P0);
apriori.beta0_range=2*apriori.P0/sqrt(apriori.P0);    
if apriori.beta0-apriori.beta0_range<eps
    apriori.beta0=(abs(apriori.b0)+2*apriori.P0)/2/sqrt(apriori.P0);
    apriori.beta0_range=apriori.beta0-eps;
end

[H C]=init_hyperstate(sidp_parameters.n_grid,apriori,mode);  %vytvori H a mi, nastavi H0 a mi*

min_distance_C=0.5*sidp_parameters.search_region_init;
min_distance_H=(H(1,end)-H(1,1))/50;

if (kresli); [los1 los2]=mc_study(system,apriori,1000); q=q+1; w(q)=los1(1)/los1(3); x(q)=los2(1)/los2(3); end



    for j=1:sidp_parameters.n_iter
        j
        %search_region=sidp_parameters.gama^(j-1)*sidp_parameters.lambda^(i-1)*sidp_parameters.search_region_init;      
        search_region=sidp_parameters.gama^(j-1)*sidp_parameters.search_region_init;      
        %prolez mrizku a iteruj rizeni
        for k=1:sidp_parameters.n_grid
            candidates=generate_candidates(C(k), search_region, sidp_parameters.num_of_candidates);
            [C(k) mean_values]=choose_best_control(H,C,k,apriori,sidp_parameters.horizont,candidates,compare_parameters);
        end
        
if (kresli); [los1 los2]=mc_study(system,apriori,1000); q=q+1; w(q)=los1(2)/los1(3); x(q)=los2(2)/los2(3); end
        
        vypis=H;
        save 'Beta.txt' vypis -ASCII;
        save 'C.txt' C -ASCII;
        
        %pokud je mrizka prilis hruba, zjemni ji tamkde je treba
        for k=1:sidp_parameters.n_grid-1
            if (abs(C(k)-C(k+1))>min_distance_C && sidp_parameters.n_grid<sidp_parameters.n_grid_max && H(k+1)-H(k)>min_distance_H)
        %       [H C]=update(H,C,k); sidp_parameters.n_grid=sidp_parameters.n_grid+1;
            end
        end
        
        if (kresli); subplot(2,1,1); plot(H,C,['',col(j)]); hold on; a=max(a,max(C(:))); b=min(b,min(C(:)));end
    end
    
    if (kresli);
        xlabel('\fontsize{18} \beta'); ylabel('\fontsize{18} \nu^{ (2)}_0'); 
        set(gca,'ylim',[b a]);
        set(gca,'xlim',[0 H(end)]); 
        legend('\pi_1','\pi_2','\pi_3','\pi_4');
        subplot(2,1,2);
        plot(0:sidp_parameters.n_iter,[w' x' ones(size(x,2),1)]); xlabel('\fontsize{18} iterace'); ylabel('\fontsize{18} relativní ztráta'); legend('mean','median');set(gca,'ylim',[0.99 max(w(1),x(1))]); set(gca,'xtick',0:sidp_parameters.n_iter); set( get(gcf, 'Children'), 'FontSize', 18); 
    end
        %[w;x]
end

