text: /*
   * This file reads a markov chain model from a file generated by trainMarkov.js
   * It then choose a beginning and follows the model to create a new title
   */
  const fs = require('fs');
  
  const CONF = require('./config.json');
  const ORDER = CONF["ORDER"];
  const MODEL_FILE = CONF["MODEL_FILE"];
  
  const DEVIATION_TARGET = CONF["DEVIATION_TARGET"];
  const MAX_TRIES = CONF["MAX_TRIES"];
  
  var markovMap = JSON.parse(fs.readFileSync(MODEL_FILE));
  
  function selectBeginning() {
      var index = markovMap.size;
      var randomThreshold = Math.floor(Math.random() * index);
  
      for (var beginning in markovMap.beginnings) {
          index -= markovMap.beginnings[beginning];
          if (index <= randomThreshold) {
              return beginning;
          }
      }
  }
  
  function generateMarkovChain(deviationTarget) {
      var beginning = selectBeginning();
      var words = beginning.split(" ");
  
      var endFound = false;
      var deviationFactor = 0;
      while (!endFound) {
          // Get the last ORDER words in the result
          var lastNgramList = []
          for (var j=ORDER; j > 0; j--) {
              lastNgramList.push(words[words.length - j]);
          }
          lastNgram = lastNgramList.join(' ').trim();
  
          //console.log("\n", words.join(" "), "\t|" + lastNgram + "|");
  
          if (markovMap.words[lastNgram]) {
              var markovWords = Object.keys(markovMap.words[lastNgram]);
              var randomWord = markovWords[Math.floor(Math.random()* markovWords.length)]
  
              if (markovWords.length > 1) {
                  deviationFactor += 1;
                  //console.log(Object.keys(markovMap.words[lastNgram]).join(', ') , '->', randomWord);
              }
  
              words.push(randomWord);
          } else {
              //console.log("no propositions found");
              endFound = true;
          }
      }
  
      return {result: words.join(" "), deviationFactor: deviationFactor};
      //console.log("\n\ndeviation factor:", deviationFactor, "\n", words.join(" "));
  }
  
  function generateMarkovChainWithTarget(deviationTarget, maxTries) {
  
      var found = false;
      while (!found) {
          var res = generateMarkovChain()
  
          if (res.deviationFactor >= deviationTarget || maxTries === 0) {
              if (maxTries !== 0) {
                  console.log("deviation: " , res.deviationFactor, "\ttries:", MAX_TRIES - maxTries);
                  console.log(res.result);
              } else {
                  console.log("no result found");
              }
              found = true;
          }
  
          maxTries -= 1;
      }
  }
  
  console.log(DEVIATION_TARGET, MAX_TRIES);
  generateMarkovChainWithTarget(DEVIATION_TARGET, MAX_TRIES);
  