function ElG_KeyGen($lambda, $r)
{
    //Generate the proper parameter q, with |q| >= lambda
    //The idea is to take the minimum q just above 2^lambda
    $powlambda = pow(2, $lambda);
    $max_retries = 5;
    $i = 0;
    do {
        $safe_primes = get_safe_primes($powlambda * pow(2, 1 + $i) * $r, $r);
        $nb_safe_primes = count($safe_primes);
        if ($nb_safe_primes == 0 || $safe_primes[$nb_safe_primes - 1][1] < $powlambda) {
            $q = 0;
        } else {
            if ($nb_safe_primes == 1) {
                $q = $safe_primes[0][1];
            } else {
                $candidate_q = $safe_primes[$nb_safe_primes - 1][1];
                $j = 1;
                while ($candidate_q > $powlambda) {
                    $candidate_q = $safe_primes[$nb_safe_primes - $j - 1][1];
                    $j++;
                }
                $q = $safe_primes[$nb_safe_primes - $j + 1][1];
            }
        }
        $i++;
    } while ($q < $powlambda && $i < $max_retries);
    //If no possible q was found, return false
    if ($i == $max_retries) {
        if (_DEBUG >= 1) {
            echo "KeyGen : impossible to find a suitable q for lambda = {$lambda} and r = {$r}. Aborting key generation.\n";
        }
        return false;
    }
    return ElG_KeyGen_alt($r, $q);
}
    }
    if ($INIT_ROUTE) {
        echo "Route initialization";
    }
    echo " on {$limit} sets of parameters. All is OK !\n";
    echo "Mean time for route proposition : ", 1000 * $total_time_prop_route / $limit, "ms, mean time for route initialization: ", 1000 * $total_time_init_route / $limit, "ms \n\n";
}
if ($TIMINGS_ELGAMAL) {
    echo "Measuring running times of ElGamal primitives and homomorphic operations...\n";
    $limit = 1000;
    $cumul = array("keygen" => 0, "enc" => 0, "dec" => 0, "mult" => 0, "plainmult" => 0, "scexp" => 0, "rerand" => 0);
    $keys = ElG_KeyGen($lambda, $r);
    $q = $keys["pk"]["group"]["order"];
    for ($i = 0; $i < $limit; $i++) {
        $begin_time = microtime(true);
        $keys = ElG_KeyGen_alt($r, $q);
        if ($keys == false) {
            echo "Error at key generation...";
            exit;
        }
        $end_time = microtime(true);
        $cumul["keygen"] += 1000 * ($end_time - $begin_time);
        list($pk, $sk) = array_values($keys);
        $group = $pk["group"];
        $a = $group["G"][array_rand($group["G"])];
        $b = $group["G"][array_rand($group["G"])];
        $begin_time = microtime(true);
        $ca = ElG_Enc($a, $pk);
        $end_time = microtime(true);
        $cumul["enc"] += 1000 * ($end_time - $begin_time);
        $begin_time = microtime(true);