#!/usr/bin/php -f
<?php

function topicky($s) {
    return strlen($s)>5 && strlen($s) < 20;
}

function enough($s) {
    return count(array_filter(explode(" ",$s),"topicky"));
}

$lines = file($_SERVER['argv'][1]);
$lines = preg_replace("/^\w+:\s+/","",$lines);
$lines = array_map("trim",$lines);
$lines = array_filter($lines, "enough");
$lines = array_unique($lines);
shuffle($lines);

print("Inspired by ".count($lines)." lines...\n\n");

$words = array();
foreach($lines as $line) {
    array_push($words,explode(" ",$line));
}

$indices = array_keys($words);
$current = array_rand($indices);
$used = array();
$used[$current] = 1;


global $scores;
function score_cached($s,$t,&$source) {
    global $scores;
    if(!defined($scores[$s][$t])) {
        $d = count(array_filter(array_intersect($source[$s],$source[$t]),"topicky"));
        $scores[$s][$t] = $d;
        $scores[$t][$s] = $d;
        //print("d=$d for ".implode(" ",$source[$s])."|".implode(" ",$source[$t])."\n");
        return $d;
    } else {
        return $scores[$s][$t];
    }
}

print($lines[$current]."\n");

while(true) {

    $best_index = -1;
    $best_score = 0;
    for($i=0;$i<count($lines); $i++) {
        if($i != $current && !$used[$i]) {
            $score = score_cached($current,$i,$words);
            if($score >  $best_score) {
             $best_index = $i;
             $best_score = $score;
            }
        }
    }

    if($best_score <= 0) {
        break;
    }
    
    print($lines[$best_index]."\n");
    
    $used[$best_index] = 1;
    $current = $best_index; 
}

?>
