%%%% computes the same state probabilities of a population of electrodes
%%%% input "PR_MAT" is a matrix of PR values where rows=> trials and columns => electrodes 

function [p_vals] = same_state_probability_dist(PR_MAT)

    [t_num, e_num] =  size(PR_MAT);

    %%% normalize all the Prs between 0 and 1   
    all_prs = zeros(t_num, e_num);
    for e = 1:e_num
        all_prs(:,e) = ( PR_MAT(:,e)  - min(PR_MAT(:,e)) ) / ( max(PR_MAT(:,e)) - min(PR_MAT(:,e)) );          
    end
  
    p_vals = zeros(1, e_num);

    for e = 1:e_num

        
        e_states = zeros(1, t_num);
        pop_states = zeros(1, t_num);          
       
        cur_pr_vec = all_prs(:,e);
        high_idx = find(cur_pr_vec >= median(cur_pr_vec));
        e_states(high_idx) = 1;
        
        all_prs2 = all_prs;
        all_prs2(:,e) = [];
        
        avg_vec = mean(all_prs2, 2);
        high_idx = find(avg_vec >= median(avg_vec));
        pop_states(high_idx) = 1; 
        
        count = length( find( (pop_states + e_states) == 1) );  %%%% number of times the states were different

        p_vals(e) = ( t_num - count ) / t_num;  %%% probability of having same states

    end


end