 middleware = (options) ->
 
   # Start the Python mobwrite daemon.
+  debug = options?.debug?
   logger = options?.logger
   daemonPort = options?.port or DEFAULT_DAEMON_PORT
   daemonHost = options?.host or DEFAULT_DAEMON_HOST
-  root = options?.root or "__mobwrite__"
+  root = options?.root or "mobwrite"
   serve({logger: logger, port: daemonPort, host: daemonHost})
 
   # Make a pattern that we can match inbound requests for mobwrite middleware.
-  rootPattern = new RegExp("#{root}/([^\/]+)")
+  rootPattern = new RegExp("#{root}/([^\\/\\?]+)")
+
+  # Set up default Javascript configs. These can always be overridden in the
+  # HTML anyway, but setting sane defaults helps.
+  clientOptions =
+    debug: debug
+    syncGateway: "/#{root}/sync"
+    syncInterval: options?.minSyncInterval or DEFAULT_MIN_SYNC_INTERVAL
+    minSyncInterval: options?.minSyncInterval or DEFAULT_MIN_SYNC_INTERVAL
+    maxSyncInterval: options?.maxSyncInterval or DEFAULT_MAX_SYNC_INTERVAL
+  clientJavascript = """
+    ;(function(){
+      #{if debug then MOBWRITE_DEBUG_JAVASCRIPT else MOBWRITE_MINIFIED_JAVASCRIPT}
+      var options = JSON.parse(#{JSON.stringify(JSON.stringify(clientOptions))})
+      for (var key in options) {
+        if (options.hasOwnProperty(key)) {
+          mobwrite[key] = options[key]
+        }
+      }
+    }).call(this);
+    """
 
   # Create a connect middleware (e.g. for use in ExpressJS).
   # TODO: verify that this works with plain http.createServer()

              font-family: sans-serif;
          }
      </style>
      <script>
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/diff_match_patch_uncompressed.js"))};
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/mobwrite_core.js"))};
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/mobwrite_form.js"))};
      </script>
      </head>
      <body>
          <form id="mobwrite-form" action="" method="post" accept-charset="utf-8">

DAEMON_TIMEOUT_IN_MILLISECONDS = 10*1000
DEFAULT_DAEMON_HOST = "localhost"
DEFAULT_DAEMON_PORT = 3017
DEFAULT_MIN_SYNC_INTERVAL = 250
DEFAULT_MAX_SYNC_INTERVAL = 1250

MOBWRITE_DEBUG_JAVASCRIPT = """
    ;(function(){
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/diff_match_patch_uncompressed.js"))};
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/mobwrite_core.js"))};
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/mobwrite_form.js"))};
    }).call(this);
    """

MOBWRITE_MINIFIED_JAVASCRIPT = """
    ;(function(){
      #{fs.readFileSync(path.resolve(MOBWRITE_PATH, "html/compressed_form.js"))};
    }).call(this);
    """

serve = (options) ->
  port = options?.port or DEFAULT_DAEMON_PORT
