Coverage -- attack bird after game closed
[open-adventure.git] / make_dungeon.py
1 #!/usr/bin/python3
2
3 # This is the new open-adventure dungeon generator. It'll eventually
4 # replace the existing dungeon.c It currently outputs a .h and .c pair
5 # for C code.
6 #
7 # The nontrivial part of this is the compilation of the YAML for
8 # movement rules to the travel array that's actually used by
9 # playermove().  This program first compiles the YAML to a form
10 # identical to the data in section 3 of the old adventure.text file,
11 # then a second stage unpacks that data into the travel array.
12 #
13 # Here are the rules of the intermediate form:
14 #
15 # Each row of data contains a location number (X), a second
16 # location number (Y), and a list of motion numbers (see section 4).
17 # each motion represents a verb which will go to Y if currently at X.
18 # Y, in turn, is interpreted as follows.  Let M=Y/1000, N=Y mod 1000.
19 #               If N<=300       it is the location to go to.
20 #               If 300<N<=500   N-300 is used in a computed goto to
21 #                                       a section of special code.
22 #               If N>500        message N-500 from section 6 is printed,
23 #                                       and he stays wherever he is.
24 # Meanwhile, M specifies the conditions on the motion.
25 #               If M=0          it's unconditional.
26 #               If 0<M<100      it is done with M% probability.
27 #               If M=100        unconditional, but forbidden to dwarves.
28 #               If 100<M<=200   he must be carrying object M-100.
29 #               If 200<M<=300   must be carrying or in same room as M-200.
30 #               If 300<M<=400   game.prop(M % 100) must *not* be 0.
31 #               If 400<M<=500   game.prop(M % 100) must *not* be 1.
32 #               If 500<M<=600   game.prop(M % 100) must *not* be 2, etc.
33 # If the condition (if any) is not met, then the next *different*
34 # "destination" value is used (unless it fails to meet *its* conditions,
35 # in which case the next is found, etc.).  Typically, the next dest will
36 # be for one of the same verbs, so that its only use is as the alternate
37 # destination for those verbs.  For instance:
38 #               15      110022  29      31      34      35      23      43
39 #               15      14      29
40 # This says that, from loc 15, any of the verbs 29, 31, etc., will take
41 # him to 22 if he's carrying object 10, and otherwise will go to 14.
42 #               11      303008  49
43 #               11      9       50
44 # This says that, from 11, 49 takes him to 8 unless game.prop(3)=0, in which
45 # case he goes to 9.  Verb 50 takes him to 9 regardless of game.prop(3).
46
47 import sys, yaml
48
49 yaml_name = "adventure.yaml"
50 h_name = "dungeon.h"
51 c_name = "dungeon.c"
52
53 statedefines = ""
54
55 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
56 #ifndef DUNGEON_H
57 #define DUNGEON_H
58
59 #include <stdio.h>
60 #include <stdbool.h>
61
62 #define SILENT  -1      /* no sound */
63
64 /* Symbols for cond bits */
65 #define COND_LIT        0       /* Light */
66 #define COND_OILY       1       /* If bit 2 is on: on for oil, off for water */
67 #define COND_FLUID      2       /* Liquid asset, see bit 1 */
68 #define COND_NOARRR     3       /* Pirate doesn't go here unless following */
69 #define COND_NOBACK     4       /* Cannot use "back" to move away */
70 #define COND_ABOVE      5
71 #define COND_DEEP       6       /* Deep - e.g where dwarves are active */
72 #define COND_FOREST     7       /* In the forest */
73 #define COND_FORCED     8       /* Only one way in or out of here */
74 /* Bits past 10 indicate areas of interest to "hint" routines */
75 #define COND_HBASE      10      /* Base for location hint bits */
76 #define COND_HCAVE      11      /* Trying to get into cave */
77 #define COND_HBIRD      12      /* Trying to catch bird */
78 #define COND_HSNAKE     13      /* Trying to deal with snake */
79 #define COND_HMAZE      14      /* Lost in maze */
80 #define COND_HDARK      15      /* Pondering dark room */
81 #define COND_HWITT      16      /* At Witt's End */
82 #define COND_HCLIFF     17      /* Cliff with urn */
83 #define COND_HWOODS     18      /* Lost in forest */
84 #define COND_HOGRE      19      /* Trying to deal with ogre */
85 #define COND_HJADE      20      /* Found all treasures except jade */
86
87 typedef struct {{
88   const char** strs;
89   const int n;
90 }} string_group_t;
91
92 typedef struct {{
93   const string_group_t words;
94   const char* inventory;
95   int plac, fixd;
96   bool is_treasure;
97   const char** descriptions;
98   const char** sounds;
99   const char** texts;
100   const char** changes;
101 }} object_t;
102
103 typedef struct {{
104   const char* small;
105   const char* big;
106 }} descriptions_t;
107
108 typedef struct {{
109   descriptions_t description;
110   const long sound;
111   const bool loud;
112 }} location_t;
113
114 typedef struct {{
115   const char* query;
116   const char* yes_response;
117 }} obituary_t;
118
119 typedef struct {{
120   const int threshold;
121   const int point_loss;
122   const char* message;
123 }} turn_threshold_t;
124
125 typedef struct {{
126   const int threshold;
127   const char* message;
128 }} class_t;
129
130 typedef struct {{
131   const int number;
132   const int turns;
133   const int penalty;
134   const char* question;
135   const char* hint;
136 }} hint_t;
137
138 typedef struct {{
139   const string_group_t words;
140 }} motion_t;
141
142 typedef struct {{
143   const string_group_t words;
144   const long message;
145 }} action_t;
146
147 typedef struct {{
148   const string_group_t words;
149   const char* message;
150 }} special_t;
151
152 typedef struct {{
153   const long motion;
154   const long cond;
155   const long dest;
156   const bool nodwarves;
157   const bool stop;
158 }} travelop_t;
159
160 /* Abstract out the encoding of words in the travel array.  Gives us
161  * some hope of getting to a less cryptic representation than we
162  * inherited from FORTRAN, someday. To understand these, read the
163  * encoding description for travel.
164  */
165 #define T_TERMINATE(entry)      ((entry).motion == 1)
166 #define L_SPEAK(loc)            ((loc) - 500)
167
168 extern const location_t locations[];
169 extern const object_t objects[];
170 extern const char* arbitrary_messages[];
171 extern const class_t classes[];
172 extern const turn_threshold_t turn_thresholds[];
173 extern const obituary_t obituaries[];
174 extern const hint_t hints[];
175 extern long conditions[];
176 extern const motion_t motions[];
177 extern const action_t actions[];
178 extern const special_t specials[];
179 extern const travelop_t travel[];
180 extern const long tkey[];
181 extern const char *ignore;
182
183 #define NLOCATIONS      {}
184 #define NOBJECTS        {}
185 #define NHINTS          {}
186 #define NCLASSES        {}
187 #define NDEATHS         {}
188 #define NTHRESHOLDS     {}
189 #define NMOTIONS        {}
190 #define NACTIONS        {}
191 #define NSPECIALS       {}
192 #define NTRAVEL         {}
193 #define NKEYS           {}
194
195 enum arbitrary_messages_refs {{
196 {}
197 }};
198
199 enum locations_refs {{
200 {}
201 }};
202
203 enum object_refs {{
204 {}
205 }};
206
207 enum motion_refs {{
208 {}
209 }};
210
211 enum action_refs {{
212 {}
213 }};
214
215 enum special_refs {{
216 {}
217 }};
218
219 /* State definitions */
220
221 {}
222 #endif /* end DUNGEON_H */
223 """
224
225 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
226
227 #include "{}"
228
229 const char* arbitrary_messages[] = {{
230 {}
231 }};
232
233 const class_t classes[] = {{
234 {}
235 }};
236
237 const turn_threshold_t turn_thresholds[] = {{
238 {}
239 }};
240
241 const location_t locations[] = {{
242 {}
243 }};
244
245 const object_t objects[] = {{
246 {}
247 }};
248
249 const obituary_t obituaries[] = {{
250 {}
251 }};
252
253 const hint_t hints[] = {{
254 {}
255 }};
256
257 long conditions[] = {{
258 {}
259 }};
260
261 const motion_t motions[] = {{
262 {}
263 }};
264
265 const action_t actions[] = {{
266 {}
267 }};
268
269 const special_t specials[] = {{
270 {}
271 }};
272
273 const long tkey[] = {{{}}};
274
275 const travelop_t travel[] = {{
276 {}
277 }};
278
279 const char *ignore = \"{}\";
280
281 /* end */
282 """
283
284 def make_c_string(string):
285     """Render a Python string into C string literal format."""
286     if string == None:
287         return "NULL"
288     string = string.replace("\n", "\\n")
289     string = string.replace("\t", "\\t")
290     string = string.replace('"', '\\"')
291     string = string.replace("'", "\\'")
292     string = '"' + string + '"'
293     return string
294
295 def get_refs(l):
296     reflist = [x[0] for x in l]
297     ref_str = ""
298     for ref in reflist:
299         ref_str += "    {},\n".format(ref)
300     ref_str = ref_str[:-1] # trim trailing newline
301     return ref_str
302
303 def get_string_group(strings):
304     template = """{{
305             .strs = {},
306             .n = {},
307         }}"""
308     if strings == []:
309         strs = "NULL"
310     else:
311         strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
312     n = len(strings)
313     sg_str = template.format(strs, n)
314     return sg_str
315
316 def get_arbitrary_messages(arb):
317     template = """    {},
318 """
319     arb_str = ""
320     for item in arb:
321         arb_str += template.format(make_c_string(item[1]))
322     arb_str = arb_str[:-1] # trim trailing newline
323     return arb_str
324
325 def get_class_messages(cls):
326     template = """    {{
327         .threshold = {},
328         .message = {},
329     }},
330 """
331     cls_str = ""
332     for item in cls:
333         threshold = item["threshold"]
334         message = make_c_string(item["message"])
335         cls_str += template.format(threshold, message)
336     cls_str = cls_str[:-1] # trim trailing newline
337     return cls_str
338
339 def get_turn_thresholds(trn):
340     template = """    {{
341         .threshold = {},
342         .point_loss = {},
343         .message = {},
344     }},
345 """
346     trn_str = ""
347     for item in trn:
348         threshold = item["threshold"]
349         point_loss = item["point_loss"]
350         message = make_c_string(item["message"])
351         trn_str += template.format(threshold, point_loss, message)
352     trn_str = trn_str[:-1] # trim trailing newline
353     return trn_str
354
355 def get_locations(loc):
356     template = """    {{ // {}
357         .description = {{
358             .small = {},
359             .big = {},
360         }},
361         .sound = {},
362         .loud = {},
363     }},
364 """
365     loc_str = ""
366     for (i, item) in enumerate(loc):
367         short_d = make_c_string(item[1]["description"]["short"])
368         long_d = make_c_string(item[1]["description"]["long"])
369         sound = item[1].get("sound", "SILENT")
370         loud = "true" if item[1].get("loud") else "false"
371         loc_str += template.format(i, short_d, long_d, sound, loud)
372     loc_str = loc_str[:-1] # trim trailing newline
373     return loc_str
374
375 def get_objects(obj):
376     template = """    {{ // {}
377         .words = {},
378         .inventory = {},
379         .plac = {},
380         .fixd = {},
381         .is_treasure = {},
382         .descriptions = (const char* []) {{
383 {}
384         }},
385         .sounds = (const char* []) {{
386 {}
387         }},
388         .texts = (const char* []) {{
389 {}
390         }},
391         .changes = (const char* []) {{
392 {}
393         }},
394     }},
395 """
396     obj_str = ""
397     for (i, item) in enumerate(obj):
398         attr = item[1]
399         try:
400             words_str = get_string_group(attr["words"])
401         except KeyError:
402             words_str = get_string_group([])
403         i_msg = make_c_string(attr["inventory"])
404         descriptions_str = ""
405         if attr["descriptions"] == None:
406             descriptions_str = " " * 12 + "NULL,"
407         else:
408             labels = []
409             for l_msg in attr["descriptions"]:
410                 if not isinstance(l_msg, str):
411                     labels.append(l_msg)
412                     l_msg = l_msg[1]
413                 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
414             descriptions_str = descriptions_str[:-1] # trim trailing newline
415             if labels:
416                 global statedefines
417                 statedefines += "/* States for %s */\n" % item[0]
418                 for (i, (label, message)) in enumerate(labels):
419                     if len(message) >= 45:
420                         message = message[:45] + "..."
421                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
422                 statedefines += "\n"
423         sounds_str = ""
424         if attr.get("sounds") == None:
425             sounds_str = " " * 12 + "NULL,"
426         else:
427              for l_msg in attr["sounds"]:
428                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
429              sounds_str = sounds_str[:-1] # trim trailing newline
430         texts_str = ""
431         if attr.get("texts") == None:
432             texts_str = " " * 12 + "NULL,"
433         else:
434              for l_msg in attr["texts"]:
435                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
436              texts_str = texts_str[:-1] # trim trailing newline
437         changes_str = ""
438         if attr.get("changes") == None:
439             changes_str = " " * 12 + "NULL,"
440         else:
441              for l_msg in attr["changes"]:
442                  changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
443              changes_str = changes_str[:-1] # trim trailing newline
444         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
445         immovable = attr.get("immovable", False)
446         try:
447             if type(locs) == str:
448                 locs = [locnames.index(locs), -1 if immovable else 0]
449             else:
450                 locs = [locnames.index(x) for x in locs]
451         except IndexError:
452             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
453             sys.exit(1)
454         treasure = "true" if attr.get("treasure") else "false"
455         obj_str += template.format(i, words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
456     obj_str = obj_str[:-1] # trim trailing newline
457     return obj_str
458
459 def get_obituaries(obit):
460     template = """    {{
461         .query = {},
462         .yes_response = {},
463     }},
464 """
465     obit_str = ""
466     for o in obit:
467         query = make_c_string(o["query"])
468         yes = make_c_string(o["yes_response"])
469         obit_str += template.format(query, yes)
470     obit_str = obit_str[:-1] # trim trailing newline
471     return obit_str
472
473 def get_hints(hnt, arb):
474     template = """    {{
475         .number = {},
476         .penalty = {},
477         .turns = {},
478         .question = {},
479         .hint = {},
480     }},
481 """
482     hnt_str = ""
483     md = dict(arb)
484     for member in hnt:
485         item = member["hint"]
486         number = item["number"]
487         penalty = item["penalty"]
488         turns = item["turns"]
489         question = make_c_string(item["question"])
490         hint = make_c_string(item["hint"])
491         hnt_str += template.format(number, penalty, turns, question, hint)
492     hnt_str = hnt_str[:-1] # trim trailing newline
493     return hnt_str
494
495 def get_condbits(locations):
496     cnd_str = ""
497     for (name, loc) in locations:
498         conditions = loc["conditions"]
499         hints = loc.get("hints") or []
500         flaglist = []
501         for flag in conditions:
502             if conditions[flag]:
503                 flaglist.append(flag)
504         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
505         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
506         if trail:
507             line += "|" + trail
508         if line.startswith("|"):
509             line = line[1:]
510         if not line:
511             line = "0"
512         cnd_str += "    " + line + ",\t// " + name + "\n"
513     return cnd_str
514
515 def get_motions(motions):
516     template = """    {{
517         .words = {},
518     }},
519 """
520     mot_str = ""
521     for motion in motions:
522         contents = motion[1]
523         if contents["words"] == None:
524             words_str = get_string_group([])
525         else:
526             words_str = get_string_group(contents["words"])
527         mot_str += template.format(words_str)
528         global ignore
529         if contents.get("oldstyle", True) == False:
530             for word in contents["words"]:
531                 if len(word) == 1:
532                     ignore += word.upper()
533     return mot_str
534
535 def get_actions(actions):
536     template = """    {{
537         .words = {},
538         .message = {},
539     }},
540 """
541     act_str = ""
542     for action in actions:
543         contents = action[1]
544         
545         if contents["words"] == None:
546             words_str = get_string_group([])
547         else:
548             words_str = get_string_group(contents["words"])
549
550         if contents["message"] == None:
551             message = "NO_MESSAGE"
552         else:
553             message = contents["message"]
554             
555         act_str += template.format(words_str, message)
556         global ignore
557         if contents.get("oldstyle", True) == False:
558             for word in contents["words"]:
559                 if len(word) == 1:
560                     ignore += word.upper()
561     act_str = act_str[:-1] # trim trailing newline
562     return act_str
563
564 def get_specials(specials):
565     template = """    {{
566         .words = {},
567         .message = {},
568     }},
569 """
570     spc_str = ""
571     for special in specials:
572         contents = special[1]
573
574         if contents["words"] == None:
575             words_str = get_string_group([])
576         else:
577             words_str = get_string_group(contents["words"])
578
579         if contents["message"] == None:
580             message = "NULL"
581         else:
582             message = make_c_string(contents["message"])
583
584         spc_str += template.format(words_str, message)
585         global ignore
586         if contents.get("oldstyle", True) == False:
587             for word in contents["words"]:
588                 if len(word) == 1:
589                     ignore += word.upper()
590     spc_str = spc_str[:-1] # trim trailing newline
591     return spc_str
592
593 def bigdump(arr):
594     out = ""
595     for (i, entry) in enumerate(arr):
596         if i % 10 == 0:
597             if out and out[-1] == ' ':
598                 out = out[:-1]
599             out += "\n    "
600         out += str(arr[i]).lower() + ", "
601     out = out[:-2] + "\n"
602     return out
603
604 def buildtravel(locs, objs):
605     ltravel = []
606     verbmap = {}
607     for i, motion in enumerate(db["motions"]):
608         try:
609             for word in motion[1]["words"]:
610                 verbmap[word.upper()] = i
611         except TypeError:
612             pass
613     def dencode(action, name):
614         "Decode a destination number"
615         if action[0] == "goto":
616             try:
617                 return locnames.index(action[1])
618             except ValueError:
619                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
620         elif action[0] == "special":
621             return 300 + action[1]
622         elif action[0] == "speak":
623             try:
624                 return 500 + msgnames.index(action[1])
625             except ValueError:
626                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
627         else:
628             print(cond)
629             raise ValueError
630     def cencode(cond, name):
631         if cond is None:
632             return 0
633         elif cond == ["nodwarves"]:
634             return 100
635         elif cond[0] == "pct":
636             return cond[1]
637         elif cond[0] == "carry":
638             try:
639                 return 100 + objnames.index(cond[1])
640             except ValueError:
641                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
642                 sys.exit(1)
643         elif cond[0] == "with":
644             try:
645                 return 200 + objnames.index(cond[1])
646             except IndexError:
647                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
648                 sys.exit(1)
649         elif cond[0] == "not":
650             try:
651                 obj = objnames.index(cond[1])
652                 if type(cond[2]) == int:
653                     state = cond[2]
654                 else:
655                     for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
656                         if type(stateclause) == list:
657                             if stateclause[0] == cond[2]:
658                                 state = i
659                                 break
660                     else:
661                         sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
662                         sys.exit(0);
663                 return 300 + obj + 100 * state
664             except ValueError:
665                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
666                 sys.exit(1)
667         else:
668             print(cond)
669             raise ValueError
670
671     for (i, (name, loc)) in enumerate(locs):
672         if "travel" in loc:
673             for rule in loc["travel"]:
674                 tt = [i]
675                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
676                 tt.append(dest)
677                 tt += [verbmap[e] for e in rule["verbs"]]
678                 if not rule["verbs"]:
679                     tt.append(1)
680                 ltravel.append(tuple(tt))
681
682     # At this point the ltravel data is in the Section 3
683     # representation from the FORTRAN version.  Next we perform the
684     # same mapping into the runtime format.  This was the C translation
685     # of the FORTRAN code:
686     # long loc;
687     # while ((loc = GETNUM(database)) != -1) {
688     #     long newloc = GETNUM(NULL);
689     #     long L;
690     #     if (TKEY[loc] == 0) {
691     #         TKEY[loc] = TRVS;
692     #     } else {
693     #         TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
694     #     }
695     #     while ((L = GETNUM(NULL)) != 0) {
696     #         TRAVEL[TRVS] = newloc * 1000 + L;
697     #         TRVS = TRVS + 1;
698     #         if (TRVS == TRVSIZ)
699     #             BUG(TOO_MANY_TRAVEL_OPTIONS);
700     #     }
701     #     TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
702     # }
703     #
704     # In order to de-crypticize the runtime code, we're going to break these
705     # magic numbers up into a struct.
706     travel = [[0, 0, 0, False, False]]
707     tkey = [0]
708     oldloc = 0
709     while ltravel:
710         rule = list(ltravel.pop(0))
711         loc = rule.pop(0)
712         newloc = rule.pop(0)
713         if loc != oldloc:
714             tkey.append(len(travel))
715             oldloc = loc 
716         elif travel:
717             travel[-1][-1] = not travel[-1][-1]
718         while rule:
719             cond = newloc // 1000
720             travel.append([rule.pop(0),
721                            cond,
722                            newloc % 1000,
723                            cond==100,
724                            False])
725         travel[-1][-1] = True
726     return (travel, tkey)
727
728 def get_travel(travel):
729     template = """    {{
730         .motion = {},
731         .cond = {},
732         .dest = {},
733         .nodwarves = {},
734         .stop = {},
735     }},
736 """
737     out = ""
738     for entry in travel:
739         out += template.format(*entry).lower()
740     out = out[:-1] # trim trailing newline
741     return out
742
743 if __name__ == "__main__":
744     with open(yaml_name, "r") as f:
745         db = yaml.load(f)
746
747     locnames = [x[0] for x in db["locations"]]
748     msgnames = [el[0] for el in db["arbitrary_messages"]]
749     objnames = [el[0] for el in db["objects"]]
750
751     (travel, tkey) = buildtravel(db["locations"],
752                                  db["objects"])
753     ignore = ""
754     c = c_template.format(
755         h_name,
756         get_arbitrary_messages(db["arbitrary_messages"]),
757         get_class_messages(db["classes"]),
758         get_turn_thresholds(db["turn_thresholds"]),
759         get_locations(db["locations"]),
760         get_objects(db["objects"]),
761         get_obituaries(db["obituaries"]),
762         get_hints(db["hints"], db["arbitrary_messages"]),
763         get_condbits(db["locations"]),
764         get_motions(db["motions"]),
765         get_actions(db["actions"]),
766         get_specials(db["specials"]),
767         bigdump(tkey),
768         get_travel(travel), 
769         ignore,
770     )
771
772     h = h_template.format(
773         len(db["locations"])-1,
774         len(db["objects"])-1,
775         len(db["hints"]),
776         len(db["classes"])-1,
777         len(db["obituaries"]),
778         len(db["turn_thresholds"]),
779         len(db["motions"]),
780         len(db["actions"]),
781         len(db["specials"]),
782         len(travel),
783         len(tkey),
784         get_refs(db["arbitrary_messages"]),
785         get_refs(db["locations"]),
786         get_refs(db["objects"]),
787         get_refs(db["motions"]),
788         get_refs(db["actions"]),
789         get_refs(db["specials"]),
790         statedefines,
791     )
792
793     with open(h_name, "w") as hf:
794         hf.write(h)
795
796     with open(c_name, "w") as cf:
797         cf.write(c)
798
799 # end