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 global */
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(char ** ch_ptr, char * delim);
20 static void copy_tokenized_string(char ** ch_ptr, char * delim)
22 char * f_name = "copy_tokenized_string()";
23 char * dsc_ptr = strtok(NULL, delim);
24 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
25 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
30 extern uint8_t is_command_id_shortdsc(uint8_t id, char * shortdsc)
32 struct Command * cmd_ptr = world.cmd_db->cmds;
35 if (id == cmd_ptr->id)
37 if (strcmp(shortdsc, cmd_ptr->dsc_short))
43 cmd_ptr = &cmd_ptr[1];
49 extern uint8_t get_command_id(char * dsc_short)
51 struct Command * cmd_ptr = world.cmd_db->cmds;
54 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
58 cmd_ptr = &cmd_ptr[1];
64 extern char * get_command_longdsc(char * dsc_short)
66 struct Command * cmd_ptr = world.cmd_db->cmds;
69 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
71 return cmd_ptr->dsc_long;
73 cmd_ptr = &cmd_ptr[1];
79 extern void init_command_db()
81 char * f_name = "init_command_db()";
82 char * err_s = "Trouble in init_cmds() with textfile_sizes().";
84 char * path = "config/commands";
85 FILE * file = try_fopen(path, "r", f_name);
86 uint16_t lines, linemax;
87 exit_err(textfile_sizes(file, &linemax, &lines), err_s);
88 char line[linemax + 1];
90 struct Command * cmds = try_malloc(lines * sizeof(struct Command), f_name);
92 while (fgets(line, linemax + 1, file))
94 if ('\n' == line[0] || 0 == line[0])
98 cmds[i].id = atoi(strtok(line, " "));
99 copy_tokenized_string(&cmds[i].dsc_short, " ");
100 copy_tokenized_string(&cmds[i].dsc_long, "\n");
103 try_fclose(file, f_name);
105 world.cmd_db = try_malloc(sizeof(struct CommandDB), f_name);
106 world.cmd_db->cmds = cmds;
107 world.cmd_db->n = lines;
112 extern void free_command_db()
115 while (i < world.cmd_db->n)
117 free(world.cmd_db->cmds[i].dsc_short);
118 free(world.cmd_db->cmds[i].dsc_long);
121 free(world.cmd_db->cmds);