private int writeToStream(OutputStream streamOut, int count)
            throws IOException {
        int oldVirtualSize = virtualSize;
        if (virtualSize > 0) { // If the buffer isn't empty
            int bytesToWrite;

            // If the virtual buffer wraps
            if (head + virtualSize >= physicalSize && count > 0) {
                bytesToWrite = Math.min(count, physicalSize - head);
                if (streamOut != null) {
                    streamOut.write(buffer, head, bytesToWrite);
                }
                count -= bytesToWrite;
                skip(bytesToWrite); // head may wrap to zero with this call
            }

            // If the virtual buffer doesn't wrap
            if (head + virtualSize < physicalSize && count > 0) {
                bytesToWrite = Math.min(count, getTail() - head);
                if (streamOut != null) {
                    streamOut.write(buffer, head, bytesToWrite);
                }
                skip(bytesToWrite);
            }
        }
        return oldVirtualSize - virtualSize;
    }