class ChunkReader implements Closeable {

    public int readChunk(Writable str, int maxBytesToConsume) throws IOException
           {
        ChunkWritable cw = (ChunkWritable) str;
        List<Node> list = new LinkedList<Node>();

        long bytesConsumed = 0;

        do {
            if (bufferLength > 0) {
                int remaining = bufferLength - bufferPosn;
                Node nd = new Node();
                nd.slice = new byte[remaining];
                nd.len = remaining;
                System.arraycopy(buffer, bufferPosn, nd.slice, 0, nd.len);
                list.add(nd);
                bytesConsumed += nd.len;
            } else {
                Node nd = new Node();
                nd.slice = new byte[buffer.length];
                nd.len = in.read(nd.slice);
                if (nd.len <= 0) {
                    break; // EOF
                }
                bytesConsumed += nd.len;
                list.add(nd);
            }

            bufferLength = bufferPosn = 0;

        } while (bytesConsumed < maxBytesToConsume);

        if (list.size() > 0) {
            cw.box = new byte[(int) bytesConsumed];
            int pos = 0;
            for (int i = 0; i < list.size(); i++) {
                Node n = list.get(i);
                System.arraycopy(n.slice, 0, cw.box, pos, n.len);
                pos += n.len;
            }
        }

        return (int) bytesConsumed;
    }

    public  ChunkReader(InputStream in);

}