@Override
	protected Object encode(ChannelHandlerContext ctx, Channel chan, Object msg) throws Exception {
		if(chan == null || !chan.isConnected()) {
			return null;
		}
		if(msg instanceof ChannelBuffer) {
			MessageBuilder bldr = new MessageBuilder();
			bldr.writeBytes(((ChannelBuffer) msg));
			msg = bldr;
		}
		Message packet = null;
		if(msg instanceof MessageBuilder) {
			packet = ((MessageBuilder) msg).toMessage();
		} else {
			packet = (Message) msg;
		}
		if(!packet.isRaw()) {
			int packetLength = 1 + packet.getLength() + packet.getType().getSize();
			ChannelBuffer response = ChannelBuffers.buffer(packetLength);
			response.writeByte((byte) packet.getOpcode());
			if(packet.getType() == PacketType.VAR_BYTE) {
				response.writeByte((byte) packet.getLength());
			} else if(packet.getType() == PacketType.VAR_SHORT) {
				response.writeShort((short) packet.getLength());
			}
			response.writeBytes(packet.getBuffer());
			return response;
		}
		return packet.getBuffer();
	}