function Fidelity_ES = Calculate_fidelity_ES_N_hop_M_pair(F_in,N,M)
%%%%%%%%%%%%%%% Calculate ES 
number_of_pairs_ES =N+2;
number_of_states_ES = pow2(number_of_pairs_ES);
order_ES=zeros(1,number_of_pairs_ES+1);% the order of fidelity, says order(4)=2, meaning 2*F^3, order ranging from 0-->7
for i =1:number_of_states_ES
    value = de2bi(i-1,number_of_pairs_ES,'left-msb');
    single_term = power(-1,value(1));
    for j=2:number_of_pairs_ES
        single_term=single_term*power(-1,value(j));
    end
    if (single_term==1)
        temp=number_of_pairs_ES;% for calculating the order of particular NO error pattern
        for j=1:number_of_pairs_ES
             temp = temp - value(j);
        end
        order_ES(temp+1)=1 + order_ES(temp+1); % add up
    end
end
F_ES=0;
for i =1:length(order_ES)
    F_ES = F_ES + order_ES(i)*F_in.^(i-1).*(1-F_in).^(number_of_pairs_ES+1-i);
end
%Calculate for different M
F_ES_in=F_ES;
index = log2(M);
while index > 0 % > 0 for ES
    F_ES_out = F_ES_in.*F_ES_in;
    F_ES_in = F_ES_out;
    index=index - 1;
end
Fidelity_ES=F_ES_out;
