#!/usr/bin/env python

import sys, random, string

class Node:
    def __init__(self, prob, left, right, sym):
        self.prob, self.left, self.right, self.sym = prob, left, right, sym

    def __repr__(self):
        return `(self.prob, self.left, self.right, self.sym)`


def toss_coin(n):
    x = random.random()
    if x > f:
        return '0'
    else:
        return '1'

def huffman_code(symbols, probabilities):
    # Find smallest two elements in probs, and group them
    # Repeat to build up tree

    active_nodes = []
    for i in range(len(probabilities)):
        active_nodes.append(Node(probabilities[i], None, None, symbols[i]))

    while len(active_nodes) > 1:
        min1 = active_nodes[0]
        for node in active_nodes:
            if node.prob < min1.prob:
                min1 = node
        active_nodes.remove(min1)

        min2 = active_nodes[0]
        for node in active_nodes:
            if node.prob < min2.prob:
                min2 = node
        active_nodes.remove(min2)

        active_nodes.append(Node(min1.prob+min2.prob, min1, min2, None))

    # Traverse tree backwards to assign symbol codes
    codewords = {}
    
    def recurse_tree(node, code):
        if node.sym != None:
            codewords[node.sym] = code
        else:
            recurse_tree(node.left, code + '1')
            recurse_tree(node.right, code + '0')

    recurse_tree(active_nodes[0], '')
    return codewords

def generate_block_code(block_length):
    # Generate symbols as binary strings of length block_length
    # from 0000...0 to 1111...1, and calcualte associated
    # probabilities for bent coin with prob f of giving output 1

    binarystr = lambda n: n>0 and binarystr(n>>1)+str(n&1) or ''
    
    b = 0
    symbols = []
    probabilities = []
    i = 0
    while i < 2**block_length:
        bstr = string.zfill(binarystr(b), block_length)
        symbols.append(bstr)
        ones = string.count(bstr, '1')
        prob = (1-f)**(block_length-ones) * f**ones
        probabilities.append(prob)
        b += 1
        i += 1

    return huffman_code(symbols, probabilities)


def block_encode(code, input, block_length):
    output = ''
    for i in range(0, len(input), block_length):
        word = input[i:i+block_length]
        output += code[word]
    return output

def block_decode(code, input):
    rev_code = {}
    for key in code.keys():
        rev_code[code[key]] = key

    output = ''
    i = 0
    while i < len(input):
        s = ''
        while not rev_code.has_key(s):
            s += input[i]
            i += 1
        output += rev_code[s]
    return output


def generate_rle_code(max_run_length):
    symbols = range(0, max_run_length+1)
    probabilities = map(lambda n: ( (1-f)**n * f ), symbols)
    symbols.append('TRAIL_1')
    probabilities.append(1.0/N) # Prob(EOF) ~ 1/N

    code = huffman_code(symbols, probabilities)
    return code


def run_length_encode(input):
    run_lengths = map(len, string.split(input, '1'))
    max_rl = max(run_lengths)
    code = generate_rle_code(max_rl)
    output = string.join(map(code.__getitem__, run_lengths), '')

    if run_lengths[-1] == '0':
        output += code['TRAIL_1'] # marker symbol to say we do end in 1
    return output, max_rl


def run_length_decode(input, max_run_length):
    code = generate_rle_code(max_run_length)

    rev_code = {}
    for key in code.keys():
        rev_code[code[key]] = key
        
    output = ''
    terminate_one = input[-len(code['TRAIL_1']):] == code['TRAIL_1']
    if terminate_one:
        input = input[:-len(code['TRAIL_1'])]
    i = 0
    while i < len(input):
        s = ''
        while not rev_code.has_key(s):
            s += input[i]
            i += 1
        output += '0' * rev_code[s] + '1'

    if not terminate_one:
        output = output[:-1] # throw away the trailing 1

    return output


def test_block_huffman(block_length):
    input = string.join(map(toss_coin, range(N)), '')

    # Throw away the last few bits to make length of input
    # an exact  multiple of block_length
    if len(input) % block_length != 0:
        input = input[:-(len(input) % block_length)]

    code = generate_block_code(block_length)
    encoded = block_encode(code, input, block_length)
    decoded = block_decode(code, encoded)
    assert(input == decoded) # fall over if it breaks!

    print 'BLOCK CODE:', 'Block length', block_length, 'Compressed size', \
          len(encoded), 'Compression ratio', len(input)*1.0/len(encoded)

    return len(encoded)
    

def test_run_length():
    input = string.join(map(toss_coin, range(N)), '')
    encoded, max_rl = run_length_encode(input)
    decoded = run_length_decode(encoded, max_rl)

    assert(decoded == input)
    print 'RLE CODE:', 'Max run length', max_rl, 'Compressed size', \
          len(encoded), 'Compression ratio', len(input)*1.0/len(encoded)

    return len(encoded)



N = 10000 # number of coin tosses
f = 0.01  # fraction of which are 1

random.seed()

input = string.join(map(string.strip, open(sys.argv[1]).readlines()), '')
encoded, max_rl = run_length_encode(input)
decoded = run_length_decode(encoded, max_rl)
assert(decoded == input)
print 'RLE CODE:', 'Max run length', max_rl, 'Compressed size', \
      len(encoded), 'Compression ratio', len(input)*1.0/len(encoded)
