throws IOException
{
//log.debug("encode( )");
PushbackInputStream input = new PushbackInputStream( rawData, 4096 );
LZWDictionary dic = new LZWDictionary();
NBitOutputStream out = new NBitOutputStream( result );
out.setBitsInChunk( 9 ); //initially nine
out.write( CLEAR_TABLE );
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int byteRead = 0;
for( int i=0; (byteRead = input.read()) != -1; i++ )
{
//log.debug( "byteRead = '" + (char)byteRead + "' (0x" + Integer.toHexString(byteRead) + "), i=" + i);
buffer.write( byteRead );
dic.visit( (byte)byteRead );
out.setBitsInChunk( dic.getCodeSize() );
//log.debug( "Getting node '" + new String( buffer.toByteArray() ) + "', buffer.size = " + buffer.size() );
LZWNode node = dic.getNode( buffer.toByteArray() );
int nextByte = input.read();
if( nextByte != -1 )
{
//log.debug( "nextByte = '" + (char)nextByte + "' (0x" + Integer.toHexString(nextByte) + ")");
LZWNode next = node.getNode( (byte)nextByte );
if( next == null )
{
//log.debug("encode - No next node, writing node and resetting buffer (" +
// " node.getCode: " + node.getCode() + ")" +
// " bitsInChunk: " + out.getBitsInChunk() +
// ")");
out.write( node.getCode() );
buffer.reset();
}
input.unread( nextByte );
}
else
{
//log.debug("encode - EOF on lookahead: writing node, resetting buffer, and terminating read loop (" +
// " node.getCode: " + node.getCode() + ")" +
// " bitsInChunk: " + out.getBitsInChunk() +
// ")");
out.write( node.getCode() );
buffer.reset();
break;
}
if( dic.getNextCode() == 4096 )
{
//log.debug("encode - Clearing dictionary and unreading pending buffer data (" +
// " bitsInChunk: " + out.getBitsInChunk() +
// ")");
out.write( CLEAR_TABLE );
dic = new LZWDictionary();
input.unread( buffer.toByteArray() );
buffer.reset();
}
}
// Fix the code size based on the fact that we are writing the EOD
//
if( dic.getNextCode() >= 2047 )
{
out.setBitsInChunk( 12 );
}
else if( dic.getNextCode() >= 1023 )
{
out.setBitsInChunk( 11 );
}
else if( dic.getNextCode() >= 511 )
{
out.setBitsInChunk( 10 );
}
else
{
out.setBitsInChunk( 9 );
}
//log.debug("encode - Writing EOD (" +
// " bitsInChunk: " + out.getBitsInChunk() +
// ")");
out.write( EOD );
out.close();
result.flush();
}