public static Message decode(final InputStream input)
			throws IOException {
		
		DataInputStream dataInput = new DataInputStream(input);

		int length = dataInput.readInt();


		if (length == 0) {
			return KEEP_ALIVE;
		}

		byte id = dataInput.readByte();

		switch (id) {
		case (chokeID):
			return CHOKE;
		case (unchokeID):
			return UNCHOKE;
		case (interestedID):
			return INTERESTED;
		case (uninterestedID):			
			return UNINTERESTED;
		case (haveID):
			int index = dataInput.readInt();
			return new Have(index);
		case (bitfieldID):
			byte[] bitfield = new byte[length - 1];
			dataInput.readFully(bitfield);
			return new Bitfield(bitfield);
		case (pieceID):
			int ind = dataInput.readInt();
			int start = dataInput.readInt();
			byte[] block = new byte[length - 9];
			dataInput.readFully(block);
			return new Piece(ind, start, block);
		case (requestID):
			int in = dataInput.readInt();
			int begin = dataInput.readInt();
			length = dataInput.readInt();
			return new Request(in, begin, length);
		}

		return null;
	}