1 | #!/usr/bin/env python |
---|
2 | |
---|
3 | # |
---|
4 | # Copyright (c) 2012-2013 by Konstantin Dmitriev <ksee.zelgadis@gmail.com> |
---|
5 | # |
---|
6 | # This program is free software; you can redistribute it and/or modify |
---|
7 | # it under the terms of the GNU General Public License as published by |
---|
8 | # the Free Software Foundation; either version 2 of the License, or |
---|
9 | # (at your option) any later version. |
---|
10 | |
---|
11 | import os |
---|
12 | import sys |
---|
13 | import codecs |
---|
14 | |
---|
15 | def check_substring(data, substring): |
---|
16 | s = "\n".join(data); |
---|
17 | if substring in s: |
---|
18 | return True |
---|
19 | return False |
---|
20 | |
---|
21 | def process(filename): |
---|
22 | def merge_defs(): |
---|
23 | defs=False |
---|
24 | for l in template_contents: |
---|
25 | if defs: |
---|
26 | if not "</defs>" in l: |
---|
27 | inputfile_f.write(l) |
---|
28 | else: |
---|
29 | break |
---|
30 | elif "<defs>" in l: |
---|
31 | defs=True |
---|
32 | |
---|
33 | template_filename = os.path.join(os.path.dirname(sys.argv[0]), 'stickman.sif') |
---|
34 | |
---|
35 | template_f = codecs.open(template_filename, 'r', encoding='utf-8') |
---|
36 | template_contents = template_f.readlines() |
---|
37 | template_f.close() |
---|
38 | |
---|
39 | # Read the input file |
---|
40 | inputfile_f = codecs.open(filename, 'r', encoding='utf-8') |
---|
41 | inputfile_contents = inputfile_f.readlines() |
---|
42 | inputfile_f.close() |
---|
43 | |
---|
44 | # Now write results to the same file |
---|
45 | inputfile_f = open(filename, 'w', encoding='utf-8') |
---|
46 | |
---|
47 | num=1 |
---|
48 | while check_substring(inputfile_contents, '(stk%s' % num): |
---|
49 | num+=1 |
---|
50 | |
---|
51 | for i, line in enumerate(template_contents): |
---|
52 | template_contents[i] = line.replace('(stk','(stk%s' % num) |
---|
53 | |
---|
54 | defs_found=False |
---|
55 | for line in inputfile_contents: |
---|
56 | if "</defs>" in line: |
---|
57 | defs_found=True |
---|
58 | merge_defs() |
---|
59 | if line == "</canvas>\n": |
---|
60 | if not defs_found: |
---|
61 | inputfile_f.write("<defs>\n") |
---|
62 | merge_defs() |
---|
63 | inputfile_f.write("</defs>\n") |
---|
64 | canvas=False |
---|
65 | for l in template_contents: |
---|
66 | if canvas: |
---|
67 | if not l == "</canvas>\n": |
---|
68 | inputfile_f.write(l) |
---|
69 | else: |
---|
70 | break |
---|
71 | elif "</defs>" in l: |
---|
72 | canvas=True |
---|
73 | inputfile_f.write(line) |
---|
74 | |
---|
75 | inputfile_f.close() |
---|
76 | |
---|
77 | if len(sys.argv) < 2: |
---|
78 | sys.exit() |
---|
79 | else: |
---|
80 | process(sys.argv[1]) |
---|
81 | |
---|
82 | |
---|