 
   ignore = new Object
 
-  default_options = {}
   define_parameters = true
 
-  $document = null
   $file_picker = null
 
   notebook_content_type = 'application/x-lead-notebook'
 
   graphite.load_docs()
-
-  input_number = 1
 
   init_codemirror = ->
     CodeMirror.keyMap.lead = ed.key_map
     $.extend CodeMirror.commands, ed.commands
 
-  notebook = []
-
-  nb =
-    get_input_cell_by_number: (notebook, number) ->
-      for cell in notebook
-        return cell if cell.input_number == number
+  create_notebook = ->
+    notebook = []
+    notebook.input_number = 1
+    notebook.default_options = {}
+    notebook.$document = $ '<div class="document"/>'
+    notebook
 
   export_notebook = (current_cell) ->
     lead_js_version: 0
-    cells: notebook.filter((cell) -> cell != current_cell).map (cell) ->
+    cells: current_cell.notebook.filter((cell) -> cell != current_cell).map (cell) ->
       type: 'input'
       value: cell.editor.getValue()
 
-  import_notebook = (notebook, options) ->
-    for cell in notebook.cells
+  import_notebook = (notebook, imported, options) ->
+    for cell in imported.cells
       if cell.type is 'input'
         if options.run
           run_in_available_context cell.value
         else
-          add_context cell.value
-
-  clear_notebook = ->
-    $document.empty()
-    notebook = []
+          add_context notebook, cell.value
+
+  clear_notebook = (notebook) ->
+    notebook.$document.empty()
+    notebook.length = 0
 
   input_cell_at_offset = (cell, offset) ->
-    index = notebook.indexOf cell
-    notebook[index + offset]
-
-  get_available_input_cell = ->
+    index = cell.notebook.indexOf cell
+    cell.notebook[index + offset]
+
+  get_available_input_cell = (notebook) ->
     last = notebook[notebook.length - 1]
     if last?.is_clean()
       return last


      reader.readAsText file

  nb =
    init_editor: ->
      init_codemirror()
      $document = $ '#document'
      $file_picker = $ '#file'

      $file_picker.on 'change', (e) ->
        for file in e.target.files
          load_file opening_run_context, file

      return null

  remove_cell = (cell) ->
    index = cell.notebook.indexOf cell
    cell.$el.remove()
    cell.notebook.splice index, 1

  add_context = (notebook, code='') ->
    cell = get_available_input_cell notebook
    if cell?
      cell.editor.setValue code
    else
      cell = create_input_cell notebook, code
      notebook.$document.append cell.$el
      cell.rendered()
      notebook.push cell

