<?php
// middle_word_game.php
// RJM Programming
// February, 2017
// Help out middle_word_game.htm

if (isset($_GET['len']) && isset($_GET['at']) && isset($_GET['fitswith'])) {
  $suffix="";
  $whattoput="";
  $delim="";
  $xlen=$_GET['len'];
  $parid="def" . $xlen;
  $ipos=$_GET['at'];
  $vword=strtolower(urldecode($_GET['fitswith']));
  $ylen=strlen($vword);
  if (str_replace(' ','',str_replace('?','',$vword)) == '') {
    $suffix=" if (parent.document.getElementById('blurb')) { parent.document.getElementById('blurb').innerHTML=''; } ";
    $bits=explode(" ", $vword);
    $vword="";
    $vdelim="";
    for ($j=1; $j<=sizeof($bits); $j++) {
      if ($j == sizeof($bits)) {
        $nextword="OUCH";
        while (strtolower($nextword) != $nextword) {
          echo "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . "/PHP/surprise.php?min=" . (strlen($bits[-1 + $j]) + 1) . "&max=" . (strlen($bits[-1 + $j]) + 1) . "&needclue=y";
          $nextwords = file_get_contents("http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . "/PHP/surprise.php?min=" . (strlen($bits[-1 + $j]) + 1) . "&max=" . (strlen($bits[-1 + $j]) + 1) . "&needclue=y");
          $wbits = explode(" ", $nextwords);
          $nextword = $wbits[0];
        }
        $vword.=($vdelim . $nextword);
        $suffix=str_replace("''", "'" . str_replace("'","`",substr($nextwords,strlen($nextword) + 1)) . "'", $suffix);
      } else {
        $nextword="OUCH";
        while (strtolower($nextword) != $nextword) {
          $nextword = file_get_contents("http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . "/PHP/surprise.php?min=" . (strlen($bits[-1 + $j]) + 1) . "&max=" . (strlen($bits[-1 + $j]) + 1));
        }
        $vword.=($vdelim . $nextword);
      }
      $vdelim=" ";
    }
  }
  $hastobe="";
  for ($i=1; $i<=$xlen; $i++) {
    if ($i != $ipos) {
      $hastobe.="0";
    } else {
      $hastobe.=" ";
    }
  }
  for ($i=1; $i<=$ylen; $i++) {
    $achar=substr($vword,($i - 1),1);
    if ($achar == " ") {
      $whattoput.=($delim . '""');
    } else {
      $nextword="OUCH";
      while (strtolower($nextword) != $nextword) {
        $nextword = file_get_contents("http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . "/PHP/surprise.php?min=" . ($xlen + 1) . "&max=" . ($xlen + 1) . "&hastobe=" . str_replace(" ", $achar, $hastobe));
      }
      $whattoput.=($delim . '"' . strtoupper($nextword) . '"');
    }
    $delim=",";
  }
  echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('" . $parid . "')) { parent.document.getElementById('" . $parid . "').value='" . str_replace('"','~',$whattoput) . "'.replace(/~/g,String.fromCharCode(34)); } else { alert('" . str_replace('"','~',$whattoput) . "'); } " . $suffix . " \"></body></html>";
} else if (strlen($_SERVER['QUERY_STRING']) == 0) {
  echo "here";
}
?>
