package skadistats.clarity.decoder;

import java.util.ArrayList;
import java.util.List;

import skadistats.clarity.model.PVS;

public class EntityBitStream extends BitStream {

    public EntityBitStream(byte[] data) {
        super(data);
    }

    public int readEntityIndex(int baseIndex) {
        int encodedIndex = readNumericBits(6);
        if ((encodedIndex & 0x30) != 0) {
            int a = (encodedIndex >> 4) & 3;
            int b = a == 3 ? 16 : 0;
            int i = readNumericBits(4 * a + b) << 4;
            encodedIndex = i | (encodedIndex & 0x0f);
        }
        return baseIndex + encodedIndex + 1;
    }

    public PVS readEntityPVS() {
        return PVS.values()[(readNumericBits(1) << 1) | readNumericBits(1)];
    }

    public List<Integer> readEntityPropList() {
        List<Integer> propList = new ArrayList<Integer>();
        int cursor = -1;

        while (true) {
            if (readBit()) {
                cursor += 1;
            } else {
                int offset = readVarInt();
                if (offset == 0x3fff) {
                    return propList;
                } else {
                    cursor += offset + 1;
                }
            }
            propList.add(cursor);
        }
    }

}

@@ -314,281 +314,809 @@
     
-int encodedIndex = readNumericBits(6);%0D%0A        if ((encodedIndex & 0x30) != 0) %7B%0D%0A            int a = (encodedIndex %3E%3E 4) & 3;%0D%0A            int b = a == 3 ? 16 : 0;%0D%0A            int i = readNumericBits(4 * a + b) %3C%3C 4;%0D%0A            encodedIndex = i %7C (encodedIndex & 0x0f)
+// Thanks to Robin Dietrich for providing a clean version of this code :-)%0D%0A%0D%0A        // The header looks like this: %5BXY00001111222233333333333333333333%5D where everything %3E 0 is optional.%0D%0A        // The first 2 bits (X and Y) tell us how much (if any) to read other than the 6 initial bits:%0D%0A        // Y set -%3E read 4%0D%0A        // X set -%3E read 8%0D%0A        // X + Y set -%3E read 28%0D%0A%0D%0A        int offset = readNumericBits(6);%0D%0A        switch (offset & 48) %7B%0D%0A            case 16:%0D%0A                offset = (offset & 15) %7C (readNumericBits(4) %3C%3C 4);%0D%0A                break;%0D%0A            case 32:%0D%0A                offset = (offset & 15) %7C (readNumericBits(8) %3C%3C 4);%0D%0A                break;%0D%0A            case 48:%0D%0A                offset = (offset & 15) %7C (readNumericBits(28) %3C%3C 4);%0D%0A                break
 ;%0D%0A 
@@ -1156,20 +1156,14 @@
 x + 
-encodedIndex
+offset
  + 1

add blues code for decoding the entity index