         dirname = path.dirname(@tempfile)
         mkdirp.sync(dirname)
         @fd = fs.openSync(@tempfile, 'w')
+
+    write: (str) ->
+        fs.writeSync(@fd, str)
+
+    open_in_atom: ->
+        fs.closeSync @fd
+        console.log "[ratom] opening #{@tempfile}"
+        # register events
+        atom.workspace.open(@tempfile, activatePane:true).then (editor) =>
+            @handle_connection(editor)
+
+    handle_connection: (editor) ->
+        atom.focus()
+        buffer = editor.getBuffer()
+        @subscriptions = new CompositeDisposable
+        @subscriptions.add buffer.onDidSave(@save)
+        @subscriptions.add buffer.onDidDestroy(@close)
+
+    save: =>
+        if not @session.alive
+            console.log "[ratom] Error saving #{path.basename @tempfile} to #{@remoteAddress}"
+            status-message.display "Error saving #{path.basename @tempfile} to #{@remoteAddress}", 2000
+            return
+        console.log "[ratom] saving #{path.basename @tempfile} to #{@remoteAddress}"
+        status-message.display "Saving #{path.basename @tempfile} to #{@remoteAddress}", 2000
+        @session.send "save"
+        @session.send "token: #{@token}"
+        data = fs.readFileSync(@tempfile)
+        @session.send "data: " + Buffer.byteLength(data)
+        @session.send data
+
+    close: =>
+        console.log "[ratom] closing #{path.basename @tempfile}"
+        @session.close()
+        @subscriptions.dispose()
+
+class Session
+    should_parse_data: false
+    nconn: 0
+
+    constructor: (socket) ->
+        @socket = socket
+        @alive = true
+        socket.on "data", (chunk) =>
+            @parse_chunk(chunk)
+        socket.on "close", =>
+            @alive = false
+            console.log "[ratom] connection lost!"
+            status-message.display "Connection lost!", 5000
 
     parse_chunk: (chunk) ->
         if chunk

randomstring = require './randomstring'
status-message = require './status-message'

class Session
    should_parse_data: false
    readbytes: 0
    settings: {}

    constructor: (socket) ->
        @socket = socket
        @online = true
        socket.on "data", (chunk) =>
            @parse_chunk(chunk)
        socket.on "close", =>
            @online = false

    make_tempfile: ()->
        @tempfile = path.join(os.tmpdir(), randomstring(10), @basename)


        port = atom.config.get "remote-atom.port"
        @server.on 'listening', (e) =>
            @server_is_running = true
            console.log "[ratom] listening on port #{port}"
        @server.on 'error', (e) =>
            if not quiet
