summaryrefslogtreecommitdiff
path: root/userspace/fonts/binarize.py
blob: 1abb9d6a118084cebd4e23dba91d1b0785d83b35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import sys

def binarize(file_in, file_out):

    """ Create a binary file from an ASCII file. Everything 
        but '0' and '1' (alternatively '_' and 'X') is ignored 
        from the input file. """

    print ("binarizing " + file_in + " to "+ file_out + ".")
    
    try:

        f=open(file_in,'r')

        try:

            o=open(file_out,'wb')

            try:

                while True:

                    b=readnext(f)
                    if b==-1:
                        break

                    o.write(bytes([b]))

            except IOError:
                print("IOError happened during processing.");
                print("I am closing the input and ouput files and aborting.");
                print("Warning: The output file is very likely incomplete.");

            o.close()

        except IOError:
            print("IOError opening output file: " + file_out);

        f.close()

    except IOError:
        print("IOError opening input file: " + file_in);


def readnext(f):

    """ Read next 'byte' from the given ASCII file (BufferedWriter)
        everything but '_','X','0','1' is ignored. 
        Returns the byte as integer or -1 on EOF """

    l=0 
    b=""

    while l<8:

        c=f.read(1)

        if not c:
            return -1

        if c=="0" or c=='_':
            l+=1
            b+="0"

        if c=="1" or c=='X':
            l+=1
            b+="1"

    return  int(b,2)

def usage():

    """ Prints usage information to sdtout """

    print ("python3.x binarize.py [file_in] [file_out]")



""" direct use """

if __name__ == "__main__":

    if(len(sys.argv)==3):
        binarize(sys.argv[1],sys.argv[2])
    else:
        usage()