public void writeBits(int value, int SampleBits) throws IOException
    {
        int sampleMask = (1 << SampleBits) - 1;
        value &= sampleMask;

        if (byteOrder == BYTE_ORDER_NETWORK) // MSB, so add to right
        {
            bitCache = (bitCache << SampleBits) | value;
        }
        else if (byteOrder == BYTE_ORDER_INTEL) // LSB, so add to left
        {
            bitCache = bitCache | (value << bitsInCache);
        }
        else
            throw new IOException("Unknown byte order: " + byteOrder);
        bitsInCache += SampleBits;

        while (bitsInCache >= 8)
        {
            if (byteOrder == BYTE_ORDER_NETWORK) // MSB, so write from left
            {
                int b = 0xff & (bitCache >> (bitsInCache - 8));
                actualWrite(b);

                bitsInCache -= 8;
            }
            else if (byteOrder == BYTE_ORDER_INTEL) // LSB, so write from right
            {
                int b = 0xff & bitCache;
                actualWrite(b);

                bitCache >>= 8;
                bitsInCache -= 8;
            }
            int remainderMask = (1 << bitsInCache) - 1; // unneccesary
            bitCache &= remainderMask; // unneccesary
        }

    }