public byte[] decompress(byte bytes[], int expected)
            throws ImageReadException, IOException
    {
        int total = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        //    Loop until you get the number of unpacked bytes you are expecting:
        int i = 0;
        while (total < expected)

        {
            //        Read the next source byte into n.
            if (i >= bytes.length)
                throw new ImageReadException(
                        "Tiff: Unpack bits source exhausted: " + i
                                + ", done + " + total + ", expected + "
                                + expected);

            int n = bytes[i++];
            //                If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
            if ((n >= 0) && (n <= 127))
            {

                int count = n + 1;

                total += count;
                for (int j = 0; j < count; j++)
                    baos.write(bytes[i++]);
            }
            //                Else if n is between -127 and -1 inclusive, copy the next byte -n+1
            //                times.
            else if ((n >= -127) && (n <= -1))
            {
                int b = bytes[i++];
                int count = -n + 1;

                total += count;
                for (int j = 0; j < count; j++)
                    baos.write(b);
            }
            else if (n == -128)
                throw new ImageReadException("Packbits: " + n);
            //                Else if n is between -127 and -1 inclusive, copy the next byte -n+1
            //                times.
            //        else
            //                Else if n is -128, noop.
        }
        byte result[] = baos.toByteArray();

        return result;

    }