# bindecode.py - lrb - 1/29/2011

import sys
import getopt

def usage():
    print "usage: python bindecode.py [options] [d | e filein fileout]"
    print "Options and arguments"
    print "-h               : print this help message and exit (also --help)"
    print "d filein fileout : decodes filein into fileout"
    print "e filein fileout : encodes filein into fileout"

def binToChar(part):
    d = 0
    for j in range (7,0,-1):
        d += (part[j] == '1') * pow(2,7-j)
    return chr(d)

def charToBin(c):
    d = ord(c)
    bStr = ''
    while d > 0:
        bStr = str(d % 2) + bStr
        d /= 2
    while len(bStr) < 8:
        bStr = '0' + bStr
    return bStr + ' '

def doit(li):
    my_filei = open(li[2],'r')
    my_fileo = open(li[3],'w')
    if li[1] == 'd':
        line = my_filei.readline()
        line = line.strip(' ')
        parts = line.split(' ')
        for part in parts:
            my_fileo.write(binToChar(part))
    elif li[1] == 'e':
        lines = my_filei.readlines()
        for line in lines:
            for j in range (0,len(line),1):
                my_fileo.write(charToBin(line[j]))
    my_fileo.close()

def main(argv):
    try:
        opts, args = getopt.getopt(argv, "h", ["help"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
    if len(sys.argv) == 1:
        usage()
        sys.exit()
    else:
        doit(sys.argv)

if __name__ == "__main__":
    main(sys.argv[1:])