1#! /usr/bin/env python3
2
3# Add some standard cpp magic to a header file
4
5import sys
6
7def main():
8    args = sys.argv[1:]
9    for filename in args:
10        process(filename)
11
12def process(filename):
13    try:
14        f = open(filename, 'r')
15    except IOError as msg:
16        sys.stderr.write('%s: can\'t open: %s\n' % (filename, str(msg)))
17        return
18    with f:
19        data = f.read()
20    if data[:2] != '/*':
21        sys.stderr.write('%s does not begin with C comment\n' % filename)
22        return
23    try:
24        f = open(filename, 'w')
25    except IOError as msg:
26        sys.stderr.write('%s: can\'t write: %s\n' % (filename, str(msg)))
27        return
28    with f:
29        sys.stderr.write('Processing %s ...\n' % filename)
30        magic = 'Py_'
31        for c in filename:
32            if ord(c)<=0x80 and c.isalnum():
33                magic = magic + c.upper()
34            else: magic = magic + '_'
35        print('#ifndef', magic, file=f)
36        print('#define', magic, file=f)
37        print('#ifdef __cplusplus', file=f)
38        print('extern "C" {', file=f)
39        print('#endif', file=f)
40        print(file=f)
41        f.write(data)
42        print(file=f)
43        print('#ifdef __cplusplus', file=f)
44        print('}', file=f)
45        print('#endif', file=f)
46        print('#endif /*', '!'+magic, '*/', file=f)
47
48if __name__ == '__main__':
49    main()
50