         (add-to-list
          'comint-preoutput-filter-functions
          #'(lambda (output)
-           (string-match (format "BEGINOUTPUT" ems-request-counter) output))
-           (replace-regexp-in-string "[.]*BEGINOUTPUT[0-9]+" "" output)
-           (replace-regexp-in-string "ENDOUTPUT[.]*" "" output))))
+             (with-current-buffer (get-buffer "*ems-output*")
+               (let ((result (ems-parse-output output)))
+                 (when result 
+                   (insert result)
+                   (insert "\n"))
+                 output))))))
+
 
 (defun ems-load-node ()
   (run-js inferior-js-program-command t)

(defvar ems-node-process nil)
(defvar ems-output-buffer nil)
(defvar ems-request-counter 0)

(add-hook
 'inferior-js-mode-hook

      (setq ems-output-buffer (generate-new-buffer "*ems-output*"))
      )))

(defun ems-load-setup ()
  (process-send-string 
   ems-node-process
   (concat 
    "var mjx = require('mathjax-node');" 
    "var sre = require('speech-rule-engine');"
    "var runWithCounter = function(counter, callback, args) {"
    "  var result = callback.apply(sre, args);"
    "  console.log('BEGINOUTPUT' + counter + ': ' + result + ' :ENDOUTPUT');"
    "};\n"
    )))


(defun ems-next-counter ()
  (incf ems-request-counter))

;; Input: LaTeX expression
(defun ems-start-walker (expr)
  (process-send-string
   ems-node-process
   ;TODO: Here we can get LaTeX errors.
   (concat 
    (format "mjx.typeset({math: '%s', format: 'TeX', mml:true}, " expr)
    (format "function(data) {sre.walk(data.mml)});\n"))))


;; Input: A key value
(defun ems-move-walker (key)
  (process-send-string
   ems-node-process
   (format "runWithCounter(%d, sre.move, [%d]);\n" (incf ems-request-counter) key)))


;; TODO Error handling after each step.
(defun ems-setup-bridge ()
  (ems-load-node)
  (ems-load-setup))

(defun ems-teardown-bridge ()
  (kill-buffer ems-output-buffer)
