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;
20 extern tHandler gDoor_Handler;
23 void Load_Itemlist(void);
24 char *trim(char *__str);
28 tItem *gaItems = NULL;
29 tHandler gPseudo_Handler = {Name:"pseudo"};
30 tHandler *gaHandlers[] = {&gPseudo_Handler, &gCoke_Handler, &gSnack_Handler, &gDoor_Handler};
31 int giNumHandlers = sizeof(gaHandlers)/sizeof(gaHandlers[0]);
32 char *gsItemListFile = DEFAULT_ITEM_FILE;
38 for( i = 0; i < giNumHandlers; i ++ )
40 if( gaHandlers[i]->Init )
41 gaHandlers[i]->Init(0, NULL); // TODO: Arguments
46 * \brief Read the item list from disk
48 void Load_Itemlist(void)
50 FILE *fp = fopen(gsItemListFile, "r");
56 regmatch_t matches[5];
58 i = regcomp(®ex, "^([a-zA-Z][a-zA-Z0-9]*)\\s+([0-9]+)\\s+([0-9]+)\\s+(.*)", REG_EXTENDED);
61 size_t len = regerror(i, ®ex, NULL, 0);
62 char *errorStr = malloc(len);
63 regerror(i, ®ex, errorStr, len);
64 fprintf(stderr, "Rexex compilation failed - %s\n", errorStr);
71 fprintf(stderr, "Unable to open item file '%s'\n", gsItemListFile);
72 perror("Unable to open item file");
75 while( fgets(buffer, BUFSIZ, fp) )
85 tmp = strchr(buffer, '#');
87 tmp = strchr(buffer, ';');
93 if(strlen(line) == 0) continue;
95 // Pass regex over line
96 if( (i = regexec(®ex, line, 5, matches, 0)) ) {
97 size_t len = regerror(i, ®ex, NULL, 0);
98 char *errorStr = malloc(len);
99 regerror(i, ®ex, errorStr, len);
100 fprintf(stderr, "Syntax error on line %i of item file '%s'\n%s", lineNum, gsItemListFile, errorStr);
106 type = line + matches[1].rm_so; line[ matches[1].rm_eo ] = '\0';
107 num = atoi( line + matches[2].rm_so );
108 price = atoi( line + matches[3].rm_so );
109 desc = line + matches[4].rm_so;
111 printf("Item '%s' - %i cents, %s:%i\n", desc, price, type, num);
114 for( i = 0; i < giNumHandlers; i ++ )
116 if( strcmp(type, gaHandlers[i]->Name) == 0 ) {
117 handler = gaHandlers[i];
123 fprintf(stderr, "Unknow item type '%s' on line %i (%s)\n", type, lineNum, desc);
127 for( i = 0; i < giNumItems; i ++ )
129 if( gaItems[i].Handler != handler ) continue;
130 if( gaItems[i].ID != num ) continue;
132 printf("Redefinition of %s:%i, updated\n", handler->Name, num);
133 gaItems[i].Price = price;
134 free(gaItems[i].Name);
135 gaItems[i].Name = strdup(desc);
138 if( i < giNumItems ) continue;
140 gaItems = realloc( gaItems, (giNumItems + 1)*sizeof(gaItems[0]) );
141 gaItems[giNumItems].Handler = handler;
142 gaItems[giNumItems].ID = num;
143 gaItems[giNumItems].Price = price;
144 gaItems[giNumItems].Name = strdup(desc);
149 char *trim(char *__str)
154 while( isspace(*__str) )
159 while( i-- && isspace(__str[i]) ) {