public NashornProcessor(File documentRoot, String documentPath)
      throws ScriptException, IOException, SAXException {
    // The document root must be a valid directory
    assert (documentRoot.isDirectory());

    // The document root is needed for evaluating script files that are
    // marked with absolute path in the src attribute
    this.documentRoot = documentRoot;

    // Let's see if we could find the document that has been inferred
    File file = new File(documentRoot, documentPath);

    // Keep the parent of this file for relative path based file access
    basePath = file.getParentFile();
    document = HTMLDocument.parse(new FileInputStream(file));

    ScriptEngine e = new ScriptEngineManager().getEngineByName("nashorn");
    assert (e instanceof NashornScriptEngine);
    engine = (NashornScriptEngine) e;

    // TODO get base href and implement set basePath and use it accordingly
    // The basePath can also have full URL which makes it tricky
    // HTMLElement[] scriptElements = document.getElementsByTagName("base");

    HTMLElement[] parts = {document.getHead(), document.getBody()};
    CompiledScript[][] res = new CompiledScript[2][];

    for (int i = 0; i < parts.length; ++i) {

      HTMLElement[] scriptElements = parts[i].getElementsByTagName("script");
      res[i] = new CompiledScript[scriptElements.length];

      int idx = 0;
      for (HTMLElement scriptElement : scriptElements) {
        // if the element has a src tag then we work on a file otherwise, we
        // expect either a CDATA section or a TEXT section within the
        // script element
        String scriptFile = scriptElement.getAttribute("src");
        CompiledScript script;
        if (scriptFile == null) {
          script = loadTextScript(scriptElement);
        } else {
          script = loadFileScript(scriptFile);
        }
        res[i][idx++] = script;
      }
    }

    headScripts = res[0];
    bodyScripts = res[1];
  }
  /* Compile a script as a text element provided as a text node or a cdata section
    or a combination
  */
  private CompiledScript loadTextScript(HTMLElement scriptElement) throws ScriptException {
    StringBuilder scriptText = new StringBuilder();
    for (HTMLNode node : scriptElement.getChildNodes()) {
      // only allowed are text nodes or cdata section
      assert (node.isText() || node.isCdataSection());

      scriptText.append(node.getNodeValue());
    }

    return engine.compile(scriptText.toString());
  }