var sys = require('sys');
var EventEmitter = require('events').EventEmitter;
var framing = require('./framing');
var oldFraming = require('./oldFraming');

function Connection(socket, version, url, protocol) {
    var that = this;
    EventEmitter.call(this);
    this.socket = socket;
    // For user access:
    this.url = url;
    this.protocol = protocol;

    var ended = false;  // state
    socket.on('end', function() {
	socket.end();
    });

    var proxyEvent = function(type) {
	socket.on(type, function(e) {
	    var args = Array.prototype.slice(arguments);
	    that.emit.apply(that, [type].concat(args));
	});
    };
    proxyEvent('drain');
    proxyEvent('error');
    proxyEvent('close');

    var reader;
    if (version === 2) {
	reader = new framing.MessageReader();
	reader.on('message', function(op, payload) {
	    if (op === 'text') {
		that.emit('data', payload.toString('utf-8'));
	    } else if (op === 'binary') {
		that.emit('data', payload);
	    } else if (op === 'ping') {
		var w = that.makeWriter('pong');
		w.end(payload);
	    } else if (op === 'close') {
		that.emit('end');

		var w = that.makeWriter('close');
		w.end();
		socket.end();
	    }
        });

	// prototype.send already applies to draft version 2
    } else {
	reader = new oldFraming.MessageReader();
	reader.on('message', function(payload) {
	    that.emit('data', payload);
	});

	this.send = function(msg) {
	    oldFraming.writeMessage(socket, msg);
	};
    }

    socket.on('data', function(data) {
	reader.write(data);
    });
};
sys.inherits(Connection, EventEmitter);
module.exports = Connection;

Connection.prototype.makeWriter = function(op) {
    return new framing.MessageWriter(socket, op);
};

Connection.prototype.send = function(payload) {
    var w = new framing.MessageWriter(this.socket,
				      (payload.constructor === Buffer) ? 'binary' : 'text');
    w.end(payload);
};

Connection.prototype.end = function() {
    var w = this.makeWriter('close');
    w.end();
    this.socket.end();
};

@@ -362,70 +362,81 @@
     
-var ended = false;  // state%0A    socket.on('end', function() %7B
+socket.on('end', function() %7B%0A%09// end is only emitted for a 'close' frame
 %0A%09so
@@ -459,29 +459,30 @@
 %7D);%0A
-%0A
     
-var proxyEvent =
+socket.on('drain',
  fun
@@ -491,17 +491,45 @@
 ion(
-type
 ) %7B%0A%09
+that.emit('drain');%0A    %7D);%0A    
 sock
@@ -534,20 +534,23 @@
 cket.on(
-type
+'error'
 , functi
@@ -562,116 +562,36 @@
  %7B%0A%09
-    var args = Array.prototype.slice(arguments);%0A%09    that.emit.apply(that, %5Btype%5D.concat(args));%0A%09%7D
+that.emit('error', e
 );%0A    %7D
 ;%0A  
@@ -590,73 +590,56 @@
    %7D
+)
 ;%0A    
-proxyEvent('drain');%0A    proxyEvent('error');%0A    proxyEven
+socket.on('close', function() %7B%0A%09that.emi
 t('c
@@ -645,16 +645,24 @@
 close');
+%0A    %7D);
 %0A%0A    va

replace proxyEvent with manual event forwarding