#!/usr/bin/env python
import collections
import math
import sys

def computeEntropy(byteCounter256):
    sumValues = sum(byteCounter256.values())
    entropy = 0.0
    i = 0
    j = 0
    ind = 0
    for iter in range(0x100):
        if byteCounter256[iter] > 0:
            byteCounter = float(byteCounter256[iter]) / float(sumValues)
            entropy += - byteCounter * math.log(byteCounter, 2)
    i = math.ceil(entropy)
    j = math.trunc(entropy)
    ind = j * 2 + (j != i)
    if j == 8:
        ind = 15
    return ind


def byteCounterAndEntropy(file):
    byteCounter = {iter: 0 for iter in range(0x100)}
    byteCounter256 = {iter: 0 for iter in range(0x100)}
    entropy = {iter: 0 for iter in range(0x10)}
    byte = {iter: 0 for iter in range(0x10)}
    featureVector = {iter: 0 for iter in range(0x100)}
    fIn = open(file, 'rb')
    cnt = 0
    for char in fIn.read():
        cnt = cnt + 1
        if cnt == 256:
            cnt = 0
            index = computeEntropy(byteCounter256)
            entropy[index] = entropy[index] + 1
            byteCounter256 = {iter: 0 for iter in range(0x100)}
        value = ord(char)
        byteCounter[value] += 1
        byteCounter256[value] += 1

    for i in range(0, 16, 1):
        for j in range(0, 16, 1):
            byte[i] = byte[i] + byteCounter[i*16 + j]

    for i in range(0, 16, 1):
        featureVector[i] = byte[i]

    for i in range(0, 16, 1):
        featureVector[16+i] = entropy[i]

    fIn.close()    
    print "hi byteStats"
    return featureVector
    
    '''
    for key, value in listCount:
        line = '0x%02x %9d' % (key,  value) #key = Byte value, value = count (listCount -> key,value)++animesh
        print(line)
    '''

