"""Reach the weight-four byte decision using only a block residue and length bit count."""
from math import ceil
from plages25 import count
from pathlib import Path
import json

def delta(block_residue,length_bits):
    pad=(-1-5*block_residue)%8
    return (2*length_bits-1-pad+7)//8-(length_bits+6)//7

def study():
    old=json.loads(Path(__file__).with_name('plages25.json').read_bytes())[1]
    table=[[delta(k,b) for k in range(8)] for b in range(1,18)]
    checked=0
    for a,b,sgn in old['intervals']:
        for n in range(a,b+1):
            z=table[n.bit_length()-1][((n+63)//64)%8]
            g,s=count(n,1)
            assert z==g-s and (z>0)-(z<0)==sgn;checked+=1
    return dict(table=table,checked=checked,intervals=len(old['intervals']))
if __name__=='__main__':print(json.dumps(study()))
