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;
19 extern tHandler gSnack_Handler;
22 void Load_Itemlist(void);
23 char *trim(char *__str);
27 tItem *gaItems = NULL;
28 tHandler gPseudo_Handler = {Name:"pseudo"};
29 tHandler *gaHandlers[] = {&gPseudo_Handler, &gCoke_Handler, &gSnack_Handler};
30 int giNumHandlers = sizeof(gaHandlers)/sizeof(gaHandlers[0]);
31 char *gsItemListFile = DEFAULT_ITEM_FILE;
37 for( i = 0; i < giNumHandlers; i ++ )
39 if( gaHandlers[i]->Init )
40 gaHandlers[i]->Init(0, NULL); // TODO: Arguments
45 * \brief Read the item list from disk
47 void Load_Itemlist(void)
49 FILE *fp = fopen(gsItemListFile, "r");
55 regmatch_t matches[5];
57 i = regcomp(®ex, "^([a-zA-Z][a-zA-Z0-9]*)\\s+([0-9]+)\\s+([0-9]+)\\s+(.*)", REG_EXTENDED);
60 size_t len = regerror(i, ®ex, NULL, 0);
61 char *errorStr = malloc(len);
62 regerror(i, ®ex, errorStr, len);
63 fprintf(stderr, "Rexex compilation failed - %s\n", errorStr);
70 fprintf(stderr, "Unable to open item file '%s'\n", gsItemListFile);
71 perror("Unable to open item file");
74 while( fgets(buffer, BUFSIZ, fp) )
84 tmp = strchr(buffer, '#');
86 tmp = strchr(buffer, ';');
92 if(strlen(line) == 0) continue;
94 // Pass regex over line
95 if( (i = regexec(®ex, line, 5, matches, 0)) ) {
96 size_t len = regerror(i, ®ex, NULL, 0);
97 char *errorStr = malloc(len);
98 regerror(i, ®ex, errorStr, len);
99 fprintf(stderr, "Syntax error on line %i of item file '%s'\n%s", lineNum, gsItemListFile, errorStr);
105 type = line + matches[1].rm_so; line[ matches[1].rm_eo ] = '\0';
106 num = atoi( line + matches[2].rm_so );
107 price = atoi( line + matches[3].rm_so );
108 desc = line + matches[4].rm_so;
110 printf("Item '%s' - %i cents, %s:%i\n", desc, price, type, num);
113 for( i = 0; i < giNumHandlers; i ++ )
115 if( strcmp(type, gaHandlers[i]->Name) == 0 ) {
116 handler = gaHandlers[i];
122 fprintf(stderr, "Unknow item type '%s' on line %i (%s)\n", type, lineNum, desc);
126 for( i = 0; i < giNumItems; i ++ )
128 if( gaItems[i].Handler != handler ) continue;
129 if( gaItems[i].ID != num ) continue;
131 printf("Redefinition of %s:%i, updated\n", handler->Name, num);
132 gaItems[i].Price = price;
133 free(gaItems[i].Name);
134 gaItems[i].Name = strdup(desc);
137 if( i < giNumItems ) continue;
139 gaItems = realloc( gaItems, (giNumItems + 1)*sizeof(gaItems[0]) );
140 gaItems[giNumItems].Handler = handler;
141 gaItems[giNumItems].ID = num;
142 gaItems[giNumItems].Price = price;
143 gaItems[giNumItems].Name = strdup(desc);
148 char *trim(char *__str)
153 while( isspace(*__str) )
158 while( i-- && isspace(__str[i]) ) {