           << nbest[nbestIndex - sentences2score.size() + j][3] << " ||| "
           << std::endl;
       }
-      index = boost::lexical_cast<size_t>(nbest[nbestIndex][0]);
+      if (nbestIndex < nbest.size()) {
+        index = boost::lexical_cast<size_t>(nbest[nbestIndex][0]);
+      }
+      else {
+        return 0;
+      }
     }
   }
   return 0;

  std::vector<std::vector<std::string>> nbest;
  ParseNBestFile(nbestPath, nbest);

  size_t index = 0;
  size_t nbestIndex = 0;
  for (auto& in: input) {
    Encoder encoder(weights);
    Decoder decoder(weights);

    auto words = Split(in);
    auto sIndexes = svcb.Encode(words);

    std::vector<std::vector<size_t> > sentences2score;
    while (nbestIndex < nbest.size()) {

      std::vector<std::vector<size_t>> batch;
      PrepareBatch(sentences2score, batch);

      auto scores = ScoreBatch(encoder, decoder, SourceContext, batch);

      for (size_t j = 0; j < batch[0].size(); ++j) {
        std::cout
          << nbest[nbestIndex - sentences2score.size() + j][0] << " ||| "
