       (setq ems-output-buffer (generate-new-buffer "*ems-output*"))
       )))
 
-(defun ems-load-mathjax ()
-  (comint-redirect-send-command-to-process
-   "var mjx = require('mathjax-node');" ems-output-buffer ems-node-buffer t))
+(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-load-sre ()
-  (comint-redirect-send-command-to-process
-   "var sre = require('speech-rule-engine');" ems-output-buffer ems-node-buffer t))
 
+(defun ems-next-counter ()
+  (incf ems-request-counter))
 
 ;; Input: LaTeX expression
 (defun ems-start-walker (expr)
-  (comint-redirect-send-command-to-process
-   (format "mjx.typeset({math: '%s', format: 'TeX', mml:true}, function(data) {sre.walk(data.mml)});" expr)
-   ems-output-buffer ems-node-buffer t))
+  (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)
-  (let* ((counter (incf ems-request-counter))
-         (command (format "console.log('BEGINOUTPUT%d:' + sre.move(%d) + 'ENDOUTPUT%d');"
-             counter key counter)))
-    (comint-redirect-send-command-to-process
-     command
-     ems-output-buffer ems-node-buffer t)
-    (ems-parse-output-buffer counter)))
+  (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-mathjax)
-  (ems-load-sre))
+  (ems-load-setup))
 
 (defun ems-teardown-bridge ()
   (kill-buffer ems-output-buffer)

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

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

        (add-to-list
         'comint-preoutput-filter-functions
         #'(lambda (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)
