# -*- Mode: Python; tab-width: 4 -*-

# from Nagendra Mishr

import array

class bitField :
   
    def __init__(self, len=65536):
        bytes = (len / 8) + 1

        self._d = array.array("B")
        self._d.fromlist([0]*bytes)

    def __getitem__(self, index):
        byte = index / 8
        ind  = index % 8
        return (self._d[byte] >> ind) & 1

    def __setitem__(self, index, val):
        byte = index / 8
        ind = index % 8
        bit = 1<<ind
       
        if (val):
            # add the bit
            self._d[byte] = self._d[byte] | bit

        else:
            # remove the bit
            self._d[byte] = ((self._d[byte] ^ bit) | bit) ^ bit

    def findEmpty(self):

        ind = 0
        for i in range(self._d.itemsize + 1):
            v = self._d[i]
           
            if (v==255):
                ind += 8
                continue
            else:
                return self.table[v] + ind

        return -1

    def build_bit_table (self):
        self.table = [None] * 256
        for v in range (256):
            if ((v >> 0) & 1) == 0: z = 0
            elif ((v >> 1) & 1) == 0: z = 1
            elif ((v >> 2) & 1) == 0: z = 2
            elif ((v >> 3) & 1) == 0: z = 3
            elif ((v >> 4) & 1) == 0: z = 4
            elif ((v >> 5) & 1) == 0: z = 5
            elif ((v >> 6) & 1) == 0: z = 6
            elif ((v >> 7) & 1) == 0: z = 7
            self.table[v] = z

    # returns data to
    def getData(self):

        return self._d.tolist()

    # Load the data into memory
    def loadData(self, list):

        self._d = array.array("B")
        self._d.fromList(list)
       
