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 "readwrite.h" /* for textfile_sizes(), try_fopen(), try_fclose() */
10 #include "misc.h" /* for try_malloc(), exit_trouble */
14 /* Build string pointed to by "ch_ptr" from next token delimited by "delim". */
15 static void copy_tokenized_string(char ** ch_ptr, char * delim);
19 static void copy_tokenized_string(char ** ch_ptr, char * delim)
21 char * f_name = "copy_tokenized_string()";
22 char * dsc_ptr = strtok(NULL, delim);
23 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
24 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
29 extern uint8_t is_command_id_shortdsc(uint8_t id, char * shortdsc)
31 struct Command * cmd_ptr = world.cmd_db->cmds;
34 if (id == cmd_ptr->id)
36 if (strcmp(shortdsc, cmd_ptr->dsc_short))
42 cmd_ptr = &cmd_ptr[1];
48 extern uint8_t get_command_id(char * dsc_short)
50 struct Command * cmd_ptr = world.cmd_db->cmds;
53 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
57 cmd_ptr = &cmd_ptr[1];
63 extern char * get_command_longdsc(char * dsc_short)
65 struct Command * cmd_ptr = world.cmd_db->cmds;
68 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
70 return cmd_ptr->dsc_long;
72 cmd_ptr = &cmd_ptr[1];
78 extern void init_command_db()
80 char * f_name = "init_command_db()";
82 char * path = "config/commands";
83 FILE * file = try_fopen(path, "r", f_name);
84 uint16_t lines, linemax;
85 uint8_t test = textfile_sizes(file, &linemax, &lines);
86 exit_trouble(test, f_name, "textfile_sizes()");
87 char line[linemax + 1];
89 struct Command * cmds = try_malloc(lines * sizeof(struct Command), f_name);
91 while (fgets(line, linemax + 1, file))
93 if ('\n' == line[0] || 0 == line[0])
97 cmds[i].id = atoi(strtok(line, " "));
98 copy_tokenized_string(&cmds[i].dsc_short, " ");
99 copy_tokenized_string(&cmds[i].dsc_long, "\n");
102 try_fclose(file, f_name);
104 world.cmd_db = try_malloc(sizeof(struct CommandDB), f_name);
105 world.cmd_db->cmds = cmds;
106 world.cmd_db->n = lines;
111 extern void free_command_db()
114 while (i < world.cmd_db->n)
116 free(world.cmd_db->cmds[i].dsc_short);
117 free(world.cmd_db->cmds[i].dsc_long);
120 free(world.cmd_db->cmds);