import numpy as np
from PIL import Image

def get_G():
    img = Image.open("output2g.png").convert("L")
    P = (np.array(img) < 128).astype(np.uint8)
    return P

def test_bf(P, num_errors):
    N_data = 16384
    N_parity = 2048
    
    # 1. Create a valid codeword
    # Correct codeword was found to be codeword.bin. 
    # Let's just use 5 random error rows XORed into the syndrome.
    error_idx = np.random.choice(N_data, num_errors, replace=False)
    synd = np.zeros(N_parity, dtype=np.uint8)
    for i in error_idx:
        synd ^= P[i]
    
    current_w = np.sum(synd)
    print(f"Initial syndrome weight with {num_errors} errors: {current_w}")
    
    # 2. Try bit flipping
    found = []
    for i in range(N_data):
        new_synd = synd ^ P[i]
        new_w = np.sum(new_synd)
        if new_w < current_w:
            found.append(i)
            print(f"  Flipping bit {i} reduces weight from {current_w} to {new_w}!")
            
    print(f"Total bits that reduce weight: {len(found)}")
    print(f"True errors in found set: {set(found).intersection(set(error_idx))}")

if __name__ == "__main__":
    P = get_G()
    print("Testing Bit-Flipping (Weight Reduction) for t=1:")
    test_bf(P, 1)
    print("\nTesting Bit-Flipping (Weight Reduction) for t=5:")
    test_bf(P, 5)
