package com.dpforge.droidgif.decoder2.lzw;

import java.io.IOException;
import java.io.InputStream;

class CodeStream {
	private final InputStream mStream;
	private int mCodeSize;

	private int mCurrentByte;
	private int mBitIndex;

	public CodeStream(final InputStream inputStream, final int codeSize) {
		mStream = inputStream;
		mCodeSize = codeSize;
	}

	void setCodeSize(int size) {
		mCodeSize = size;
	}

	int nextValue() throws IOException {
		int value = 0;
		for (int valueBitIndex = 0; valueBitIndex < mCodeSize; valueBitIndex++, mBitIndex = (mBitIndex + 1) % 8) {
			if (mBitIndex == 0) {
				mCurrentByte = mStream.read();
			}
			boolean bit = getBit(mCurrentByte, mBitIndex);
			value = setBit(value, valueBitIndex, bit);
		}
		return value;
	}

	private static boolean getBit(int value, int index) {
		int mask = (1 << index);
		return ((value & mask) == mask);
	}

	private static int setBit(int value, int index, boolean bit) {
		int mask = (1 << index);
		if (bit) {
			return value | mask;
		} else {
			return value & ~mask;
		}
	}
}

@@ -113,16 +113,125 @@
 tream %7B%0A
+%09private final static int%5B%5D BIT_MASKS = new int%5B%5D%7B0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095%7D;%0A%0A
 %09private
@@ -297,27 +297,22 @@
 te int m
-CurrentByte
+Buffer
 ;%0A%09priva
@@ -320,23 +320,25 @@
 e int mB
-itIndex
+ufferSize
 ;%0A%0A%09publ
@@ -555,578 +555,211 @@
 %7B%0A%09%09
-int value = 0;%0A%09%09for (int valueBitIndex = 0; valueBitIndex %3C mCodeSize; valueBitIndex++, mBitIndex = (mBitIndex + 1) %25 8) %7B%0A%09%09%09if (mBitIndex == 0) %7B%0A%09%09%09%09mCurrentByte = mStream.read();%0A%09%09%09%7D%0A%09%09%09boolean bit = getBit(mCurrentByte, mBitIndex);%0A%09%09%09value = setBit(value, valueBitIndex, bit);%0A%09%09%7D%0A%09%09return value;%0A%09%7D%0A%0A%09private static boolean getBit(int value, int index) %7B%0A%09%09int mask = (1 %3C%3C index);%0A%09%09return ((value & mask) == mask);%0A%09%7D%0A%0A%09private static int setBit(int value, int index, boolean bit) %7B%0A%09%09int mask = (1 %3C%3C index);%0A%09%09if (bit) %7B%0A%09%09%09return value %7C mask;%0A%09%09%7D else %7B%0A%09
+while (mBufferSize %3C mCodeSize) %7B%0A%09%09%09mBuffer %7C= mStream.read() %3C%3C mBufferSize;%0A%09%09%09mBufferSize += 8;%0A%09%09%7D%0A%09%09int value = mBuffer & BIT_MASKS%5BmCodeSize%5D;%0A%09%09mBuffer %3E%3E= mCodeSize;%0A%09%09mBufferSize -= mCodeSize;%0A
 %09%09re
@@ -772,21 +772,9 @@
 alue
- & ~mask;%0A%09%09%7D
+;
 %0A%09%7D%0A

improve code stream