package skadistats.clarity.util;

import com.google.protobuf.ByteString;
import org.xerial.snappy.Snappy;
import skadistats.clarity.decoder.bitstream.BitStream;

import java.io.IOException;

public class LZSS {

    private static int MAGIC = 'L' | 'Z' << 8 | 'S' << 16 | 'S' << 24;

    public static byte[] unpack(ByteString raw) throws IOException {
        return unpack(BitStream.createBitStream(raw));
    }

    public static byte[] unpack(BitStream bs) throws IOException {
        if (bs.readUBitInt(32) != MAGIC) {
            throw new IOException("wrong LZSS magic");
        }
        byte[] dst = new byte[bs.readUBitInt(32)];
        int di = 0;
        int cmd = 0;
        int bit = 0x100;
        while (true) {
            if (bit == 0x100) {
                cmd = bs.readUBitInt(8);
                bit = 1;
            }
            if ((cmd & bit) == 0) {
                dst[di++] = (byte) bs.readUBitInt(8);
            } else {
                int a = bs.readUBitInt(8);
                int b = bs.readUBitInt(8);
                int position = (a << 4) | (b >> 4);
                int count = (b & 0x0F) + 1;
                if (count == 1) {
                    break;
                }
                Snappy.arrayCopy(dst, di - position - 1, count, dst, di);
                di += count;
            }
            bit = bit << 1;
        }
        return dst;
    }

}

@@ -70,41 +70,8 @@
 ng;%0A
-import org.xerial.snappy.Snappy;%0A
 impo
@@ -1023,19 +1023,22 @@
 int 
-position = 
+offset = 1 + (
 (a %3C
@@ -1052,16 +1052,17 @@
 (b %3E%3E 4)
+)
 ;%0A      
@@ -1082,16 +1082,20 @@
  count =
+ 1 +
  (b & 0x
@@ -1101,12 +1101,8 @@
 x0F)
- + 1
 ;%0A  
@@ -1198,65 +1198,142 @@
     
-Snappy.arrayCopy(dst, di - position - 1, count, dst, di);
+int end = di + count;%0A                for (int i = di; i %3C end; i++) %7B%0A                    dst%5Bi%5D = dst%5Bi - offset%5D;%0A                %7D
 %0A   

Fix bug with Snappy.arrayCopy() not doing the job correctly.