<?php

function gmp_rand($min, $max) {
    $max -= $min;
    $bit_length = strlen(gmp_strval($max, 2));

    do {
        $rand = gmp_init(0);
        for ($i = $bit_length - 1; $i >= 0; $i--) {
            gmp_setbit($rand, $i, rand(0, 1));
            if ($rand > $max) break;
        }
    } while ($rand > $max);

    return $rand + $min;
}

function array_weighted_rand ($list) {
    $total_weight = gmp_init(0);
    foreach ($list as $weight) {
        $total_weight += $weight;
    }

    $rand = gmp_rand(1, $total_weight);
    foreach ($list as $key => $weight) {
        $rand -= $weight;
        if ($rand <= 0) return $key;
    }
}

function fill_word ($word, $length, $trigrams) {
    while (strlen($word) < $length) {
        $word .= array_weighted_rand($trigrams[substr($word, -2)]);
    }
    return $word;
}

$lengths  = json_decode(file_get_contents('phpdict/distinct_word_lengths.json'), true);
$bigrams  = json_decode(file_get_contents('phpdict/word_start_bigrams.json'), true);
$trigrams = json_decode(file_get_contents('phpdict/trigrams.json'), true);


$length = array_weighted_rand($lengths);
$start  = array_weighted_rand($bigrams);
$word   = fill_word($start, $length, $trigrams);

//$word = strtolower($word);
$word = "SampleP592";

// Set the content-type
header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(296, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey  = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 296, 29, $white);

// The text to draw
$text = $word;
// Replace path by your own font path
$font = 'phpfont/arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 26, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 25, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);

?> 