import math
import sys

def calcular_entropia(bitstream):
    n = len(bitstream)
    if n == 0: return 0
    
    p0 = bitstream.count('0') / n
    p1 = bitstream.count('1') / n
    
    entropia = 0
    for p in [p0, p1]:
        if p > 0:
            entropia -= p * math.log2(p)
    return entropia

def calcular_entropia_condicional(bitstream):
    transicoes = {'00': 0, '01': 0, '10': 0, '11': 0}
    contagem_base = {'0': 0, '1': 0}
    
    for i in range(len(bitstream) - 1):
        par = bitstream[i:i+2]
        transicoes[par] += 1
        contagem_base[bitstream[i]] += 1
    
    h_condicional = 0
    for base in ['0', '1']:
        p_base = contagem_base[base] / (len(bitstream) - 1)
        if p_base > 0:
            h_local = 0
            for prox in ['0', '1']:
                p_transicao = transicoes[base + prox] / contagem_base[base]
                if p_transicao > 0:
                    h_local -= p_transicao * math.log2(p_transicao)
            h_condicional += p_base * h_local
            
    return h_condicional

def clean_image_data(image_data):
    
    clean_text = ""

    for line in image_data:
        line = line.strip()
        line = line.replace(" ", "")
        if not line or line.startswith('#'):
            continue
        clean_text += line

    return clean_text

with open(sys.argv[1], "r") as image:
        lines = image.readlines()
        image_data = clean_image_data(lines[2:])

        h_x = calcular_entropia(image_data)
        h_condicional = calcular_entropia_condicional(image_data)

        print(f"Entropia: {h_x:.4f} bits/pixel")
        print(f"Entropia Condicional: {h_condicional:.4f} bits/pixel")