package com.twelvemonkeys.imageio.stream;

import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.ImageOutputStreamImpl;
import java.io.IOException;

/**
 * ImageInputStream that writes through a delegate, but keeps local position and bit offset.
 * Note: Flushing or closing this stream will *not* have an effect on the delegate.
 *
 * @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
 * @author last modified by $Author: harald.kuhr$
 * @version $Id: SubImageOutputStream.java,v 1.0 30/03/15 harald.kuhr Exp$
 */
public class SubImageOutputStream extends ImageOutputStreamImpl {
    private final ImageOutputStream stream;

    public SubImageOutputStream(final ImageOutputStream stream) {
        this.stream = stream;
    }

    @Override
    public void write(int b) throws IOException {
        stream.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        stream.write(b, off, len);
    }

    @Override
    public int read() throws IOException {
        return stream.read();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return stream.read(b, off, len);
    }

    @Override
    public boolean isCached() {
        return stream.isCached();
    }

    @Override
    public boolean isCachedMemory() {
        return stream.isCachedMemory();
    }

    @Override
    public boolean isCachedFile() {
        return stream.isCachedFile();
    }
}

@@ -163,16 +163,72 @@
 ption;%0A%0A
+import static com.twelvemonkeys.lang.Validate.notNull;%0A%0A
 /**%0A * I
@@ -707,16 +707,49 @@
  stream;
+%0A    private final long startPos;
 %0A%0A    pu
@@ -805,16 +805,35 @@
  stream)
+ throws IOException
  %7B%0A     
@@ -849,22 +849,223 @@
 tream = 
-stream
+notNull(stream, %22stream%22);%0A        startPos = stream.getStreamPosition();%0A    %7D%0A%0A    @Override%0A    public void seek(long pos) throws IOException %7B%0A        super.seek(pos);%0A        stream.seek(startPos + pos)
 ;%0A    %7D%0A
@@ -1121,32 +1121,54 @@
 s IOException %7B%0A
+        flushBits();%0A%0A
         stream.w
@@ -1176,16 +1176,37 @@
 ite(b);%0A
+        streamPos++;%0A
     %7D%0A%0A 
@@ -1281,32 +1281,53 @@
 s IOException %7B%0A
+        flushBits();%0A
         stream.w
@@ -1337,32 +1337,58 @@
 e(b, off, len);%0A
+        streamPos += len;%0A
     %7D%0A%0A    @Over
@@ -1427,32 +1427,76 @@
 s IOException %7B%0A
+        bitOffset = 0;%0A        streamPos++;%0A
         return s
@@ -1611,39 +1611,117 @@
     
-return stream.read(b, off, len)
+bitOffset = 0;%0A        int count = stream.read(b, off, len);%0A        streamPos += count;%0A        return count
 ;%0A  

Fix streamPos/bitPos issue in SubImageOutputStream.