home · contact · privacy
Clean up memory allocated for Win structs.
[plomrogue] / src / rexit.c
1 /* rexit.c */
2
3 #include "rexit.h"
4 #include <stdlib.h> /* for exit(), free(), defines EXIT_SUCESS, EXIT_FAILURE */
5 #include <stdio.h> /* for printf(), perror() */
6 #include <stdint.h> /* for uint8_t */
7 #include <ncurses.h> /* for endwin() */
8 #include <errno.h> /* for errno */
9 #include "main.h" /* for World struct */
10 #include "map.h" /* for Map struct */
11 #include "keybindings.h" /* for KeysWinData, KeyBinding structs */
12 #include "command_db.h" /* for free_command_db() */
13 #include "windows.h" /* for Win struct */
14
15
16
17 /* The clean-up routine and the flag resource by which it decides what to do. */
18 static uint32_t cleanup_flags = 0x0000;
19 static void cleanup(struct World * world);
20
21
22
23 static void cleanup(struct World * world)
24 {
25     if (cleanup_flags & CLEANUP_NCURSES)
26     {
27         endwin();
28     }
29     if (cleanup_flags & CLEANUP_MAP)
30     {
31         free(world->map->cells);
32     }
33     if (cleanup_flags & CLEANUP_KEYBINDINGS)
34     {
35         uint16_t key;
36         for (key = 0; key <= world->keyswindata->max; key++)
37         {
38             free(world->keybindings[key].name);
39         }
40         free(world->keybindings);
41         free(world->keyswindata);
42     }
43     if (cleanup_flags & CLEANUP_LOG)
44     {
45         free(world->log);
46     }
47     if (cleanup_flags & CLEANUP_COMMAND_DB)
48     {
49         free_command_db(world);
50     }
51     if (cleanup_flags & CLEANUP_WIN_INFO)
52     {
53         free(world->wins.info->_title);
54     }
55     if (cleanup_flags & CLEANUP_WIN_MAP)
56     {
57         free(world->wins.map->_title);
58     }
59     if (cleanup_flags & CLEANUP_WIN_LOG)
60     {
61         free(world->wins.log->_title);
62     }
63     if (cleanup_flags & CLEANUP_WIN_KEYS)
64     {
65         free(world->wins.keys->_title);
66     }
67 }
68
69
70
71 extern void set_cleanup_flag(enum cleanup_flag flag)
72 {
73     cleanup_flags = cleanup_flags | flag;
74 }
75
76
77
78 extern void exit_game(struct World * world)
79 {
80     cleanup(world);
81     exit(EXIT_SUCCESS);
82 }
83
84
85
86 extern void exit_err(uint8_t err, struct World * world, char * msg)
87 {
88     if (0 == err)
89     {
90         return;
91     }
92     cleanup(world);
93     if (NULL == msg)
94     {
95         msg = "Details unknown.";
96     }
97     printf("Aborted PlomRogue due to error. %s\nInternal error code: %d\n",
98            msg, err);
99     if (0 != errno)
100     {
101         perror("errno states");
102     }
103     exit(EXIT_FAILURE);
104 }