Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-examples / python / digital / run_length.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2007 Free Software Foundation, Inc.
4
5 # This file is part of GNU Radio
6
7 # GNU Radio is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3, or (at your option)
10 # any later version.
11
12 # GNU Radio is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with GNU Radio; see the file COPYING.  If not, write to
19 # the Free Software Foundation, Inc., 51 Franklin Street,
20 # Boston, MA 02110-1301, USA.
21
22
23 from optparse import OptionParser
24 import sys
25
26 def main():
27     parser = OptionParser()
28     parser.add_option("-f", "--file", default=None,
29                       help="Choose file to read data from.")
30     (options, args) = parser.parse_args()
31
32     if options.file == None:
33         print "Must specify file to read from using '-f'."
34         sys.exit(1)
35     print "Using", options.file, "for data."
36
37     f = open(options.file, 'r')
38     runs = []
39     count = 0
40     current = 0
41     bytes = 0
42     bits = 0
43     
44     for ch in f.read():
45         x = ord(ch)
46         bytes = bytes + 1
47         for i in range(7,-1,-1):
48             bits = bits + 1
49             t = (x >> i) & 0x1
50             if t == current:
51                 count = count + 1
52             else:
53                 if count > 0:
54                     if len(runs) < count:
55                         for j in range(count - len(runs)):
56                             runs.append(0);
57                     runs[count-1] = runs[count-1] + 1
58
59                 current = 1-current;
60                 count = 1
61
62     # Deal with last run at EOF
63     if len(runs) < count and count > 0:
64         for j in range(count - len(runs)):
65             runs.append(0);
66     runs[count-1] = runs[count-1] + 1
67
68     chk = 0
69     print "Bytes read: ", bytes
70     print "Bits read:  ", bits
71     print
72     for i in range(len(runs)):
73         chk = chk + runs[i]*(i+1)
74         print "Runs of length", i+1, ":", runs[i]
75     print
76     print "Sum of runs:", chk, "bits"
77     print
78     print "Maximum run length is", len(runs), "bits"
79
80 if __name__ == "__main__":
81     main()
82
83