function threshold = true_calibrate_scan(n, N, alpha, B, M, kappa)
%%%%%%% Input parameters 
%     n  %graph size 
%     N  %subset size
%     alpha %null parameter, edge density under alternative
%     B  % number of subsets
%     M % number of samples
%     kappa  %target level

    %%% membership matrix Pi
    Pi  = [ones(N, 1)', zeros(n- N,1)'; zeros(N, 1)', ones(n- N,1)']';
    
    %%% structure matrices P_null, Omega_null  
    P_null = alpha*ones(2,2);
    
    Omega_null = Pi*P_null*Pi';
    
    %%% scan test values
    scan_values = zeros(M, 1);
    
    %%% perform M repetitions to set the threshold
    for sample_idx = 1:M
        %%% generate A 
        A = binornd(ones(n,n), Omega_null ); 
        A = A - tril(A) ;
        A = A + A';
        
        %%% compute V, eta^*, \tilde A
        V = ones(1,n) * A * ones(n,1);
        eta = 1 / V^0.5 * A * ones(n,1);
        At = A - eta * eta';
    
        %%%compute scan statistic 
        scan_values(sample_idx) = true_scan(A, N); 
    end
    
    %%% set threshold = kappa empirical quantile
    sorted_max_values = sort(scan_values);
    threshold = sorted_max_values(round((1-kappa)*length(scan_values))); 

end 