3 * UCC (University [of WA] Computer Club) Electronic Accounting System
5 * itemdb.c - Dispense Item Databse
7 * This file is licenced under the 3-clause BSD Licence. See the file COPYING
18 extern tHandler gCoke_Handler;
21 void Load_Itemlist(void);
22 char *trim(char *__str);
26 tItem *gaItems = NULL;
27 tHandler gPseudo_Handler = {Name:"pseudo"};
28 tHandler *gaHandlers[] = {&gPseudo_Handler, &gCoke_Handler};
29 int giNumHandlers = sizeof(gaHandlers)/sizeof(gaHandlers[0]);
30 char *gsItemListFile = DEFAULT_ITEM_FILE;
34 * \brief Read the item list from disk
36 void Load_Itemlist(void)
38 FILE *fp = fopen(gsItemListFile, "r");
44 regmatch_t matches[5];
46 i = regcomp(®ex, "^([a-zA-Z][a-zA-Z0-9]*)\\s+([0-9]+)\\s+([0-9]+)\\s+(.*)", REG_EXTENDED);
49 size_t len = regerror(i, ®ex, NULL, 0);
50 char *errorStr = malloc(len);
51 regerror(i, ®ex, errorStr, len);
52 fprintf(stderr, "Rexex compilation failed - %s\n", errorStr);
59 fprintf(stderr, "Unable to open item file '%s'\n", gsItemListFile);
60 perror("Unable to open item file");
63 while( fgets(buffer, BUFSIZ, fp) )
73 tmp = strchr(buffer, '#');
75 tmp = strchr(buffer, ';');
81 if(strlen(line) == 0) continue;
83 // Pass regex over line
84 if( (i = regexec(®ex, line, 5, matches, 0)) ) {
85 size_t len = regerror(i, ®ex, NULL, 0);
86 char *errorStr = malloc(len);
87 regerror(i, ®ex, errorStr, len);
88 fprintf(stderr, "Syntax error on line %i of item file '%s'\n%s", lineNum, gsItemListFile, errorStr);
94 type = line + matches[1].rm_so; line[ matches[1].rm_eo ] = '\0';
95 num = atoi( line + matches[2].rm_so );
96 price = atoi( line + matches[3].rm_so );
97 desc = line + matches[4].rm_so;
99 printf("Item '%s' - %i cents, %s:%i\n", desc, price, type, num);
102 for( i = 0; i < giNumHandlers; i ++ )
104 if( strcmp(type, gaHandlers[i]->Name) == 0 ) {
105 handler = gaHandlers[i];
111 fprintf(stderr, "Unknow item type '%s' on line %i (%s)\n", type, lineNum, desc);
115 for( i = 0; i < giNumItems; i ++ )
117 if( gaItems[i].Handler != handler ) continue;
118 if( gaItems[i].ID != num ) continue;
120 printf("Redefinition of %s:%i, updated\n", handler->Name, num);
121 gaItems[i].Price = price;
122 free(gaItems[i].Name);
123 gaItems[i].Name = strdup(desc);
126 if( i < giNumItems ) continue;
128 gaItems = realloc( gaItems, (giNumItems + 1)*sizeof(gaItems[0]) );
129 gaItems[giNumItems].Handler = handler;
130 gaItems[giNumItems].ID = num;
131 gaItems[giNumItems].Price = price;
132 gaItems[giNumItems].Name = strdup(desc);
137 char *trim(char *__str)
142 while( isspace(*__str) )
147 while( i-- && isspace(__str[i]) ) {