3 #include "command_db.h"
4 #include <stdlib.h> /* for free() */
5 #include <stdio.h> /* for FILE typedef, fgets() */
6 #include <stdint.h> /* for uint8_t */
7 #include <string.h> /* for strlen(), strtok() */
8 #include "main.h" /* for World struct */
9 #include "rexit.h" /* for exit_err() */
10 #include "readwrite.h" /* for textfile_sizes(), try_fopen(), try_fclose() */
11 #include "misc.h" /* for try_malloc() */
15 /* Build string pointed to by "ch_ptr" from next token delimited by "delim". */
16 static void copy_tokenized_string(struct World * world, char ** ch_ptr,
19 char * f_name = "copy_tokenized_string()";
20 char * dsc_ptr = strtok(NULL, delim);
21 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, world, f_name);
22 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
27 extern uint8_t is_command_id_shortdsc(struct World * world,
28 uint8_t id, char * shortdsc)
30 struct Command * cmd_ptr = world->cmd_db->cmds;
33 if (id == cmd_ptr->id)
35 if (strcmp(shortdsc, cmd_ptr->dsc_short))
41 cmd_ptr = &cmd_ptr[1];
47 extern uint8_t get_command_id(struct World * world, char * dsc_short)
49 struct Command * cmd_ptr = world->cmd_db->cmds;
52 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
56 cmd_ptr = &cmd_ptr[1];
62 extern char * get_command_longdsc(struct World * world, char * dsc_short)
64 struct Command * cmd_ptr = world->cmd_db->cmds;
67 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
69 return cmd_ptr->dsc_long;
71 cmd_ptr = &cmd_ptr[1];
77 extern void init_command_db(struct World * world)
79 char * f_name = "init_command_db()";
80 char * err_s = "Trouble in init_cmds() with textfile_sizes().";
82 char * path = "config/commands";
83 FILE * file = try_fopen(path, "r", world, f_name);
84 uint16_t lines, linemax;
85 exit_err(textfile_sizes(file, &linemax, &lines), world, err_s);
86 char line[linemax + 1];
88 struct Command * cmds = try_malloc(lines * sizeof(struct Command),
91 while (fgets(line, linemax + 1, file))
93 cmds[i].id = atoi(strtok(line, " "));
94 copy_tokenized_string(world, &cmds[i].dsc_short, " ");
95 copy_tokenized_string(world, &cmds[i].dsc_long, "\n");
98 try_fclose(file, world, f_name);
100 world->cmd_db = try_malloc(sizeof(struct CommandDB), world, f_name);
101 world->cmd_db->cmds = cmds;
102 world->cmd_db->n = lines;
107 extern void free_command_db(struct World * world)
110 while (i < world->cmd_db->n)
112 free(world->cmd_db->cmds[i].dsc_short);
113 free(world->cmd_db->cmds[i].dsc_long);
116 free(world->cmd_db->cmds);