3 #include "command_db.h"
4 #include <stdlib.h> /* for free() */
5 #include <stdio.h> /* for FILE typedef */
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(),
12 #include "misc.h" /* for try_malloc() */
16 /* Build string pointed to by "ch_ptr" from next token delimited by "delim". */
17 static void copy_tokenized_string(char ** ch_ptr, char * delim);
21 static void copy_tokenized_string(char ** ch_ptr, char * delim)
23 char * f_name = "copy_tokenized_string()";
24 char * dsc_ptr = strtok(NULL, delim);
25 * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
26 memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
31 extern uint8_t is_command_id_shortdsc(uint8_t id, char * shortdsc)
33 struct Command * cmd_ptr = world.cmd_db->cmds;
36 if (id == cmd_ptr->id)
38 if (strcmp(shortdsc, cmd_ptr->dsc_short))
44 cmd_ptr = &cmd_ptr[1];
50 extern uint8_t get_command_id(char * dsc_short)
52 struct Command * cmd_ptr = world.cmd_db->cmds;
55 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
59 cmd_ptr = &cmd_ptr[1];
65 extern char * get_command_longdsc(char * dsc_short)
67 struct Command * cmd_ptr = world.cmd_db->cmds;
70 if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
72 return cmd_ptr->dsc_long;
74 cmd_ptr = &cmd_ptr[1];
80 extern void init_command_db()
82 char * f_name = "init_command_db()";
83 char * path = "config/commands";
84 FILE * file = try_fopen(path, "r", f_name);
86 uint16_t linemax = textfile_sizes(file, &lines);
87 char line[linemax + 1];
88 struct Command * cmds = try_malloc(lines * sizeof(struct Command), f_name);
90 while (try_fgets(line, linemax + 1, file, f_name))
92 if ('\n' == line[0] || 0 == line[0])
96 cmds[i].id = atoi(strtok(line, " "));
97 copy_tokenized_string(&cmds[i].dsc_short, " ");
98 copy_tokenized_string(&cmds[i].dsc_long, "\n");
101 try_fclose(file, f_name);
102 world.cmd_db = try_malloc(sizeof(struct CommandDB), f_name);
103 world.cmd_db->cmds = cmds;
104 world.cmd_db->n = lines;
109 extern void free_command_db()
112 while (i < world.cmd_db->n)
114 free(world.cmd_db->cmds[i].dsc_short);
115 free(world.cmd_db->cmds[i].dsc_long);
118 free(world.cmd_db->cmds);