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    data = f.read()
19    f.close()
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    sys.stderr.write('Processing %s ...\n' % filename)
29    magic = 'Py_'
30    for c in filename:
31        if ord(c)<=0x80 and c.isalnum():
32            magic = magic + c.upper()
33        else: magic = magic + '_'
34    sys.stdout = f
35    print('#ifndef', magic)
36    print('#define', magic)
37    print('#ifdef __cplusplus')
38    print('extern "C" {')
39    print('#endif')
40    print()
41    f.write(data)
42    print()
43    print('#ifdef __cplusplus')
44    print('}')
45    print('#endif')
46    print('#endif /*', '!'+magic, '*/')
47
48if __name__ == '__main__':
49    main()
50