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;
36 for( i = 0; i < giNumHandlers; i ++ )
38 if( gaHandlers[i]->Init )
39 gaHandlers[i]->Init(0, NULL); // TODO: Arguments
44 * \brief Read the item list from disk
46 void Load_Itemlist(void)
48 FILE *fp = fopen(gsItemListFile, "r");
54 regmatch_t matches[5];
56 i = regcomp(®ex, "^([a-zA-Z][a-zA-Z0-9]*)\\s+([0-9]+)\\s+([0-9]+)\\s+(.*)", REG_EXTENDED);
59 size_t len = regerror(i, ®ex, NULL, 0);
60 char *errorStr = malloc(len);
61 regerror(i, ®ex, errorStr, len);
62 fprintf(stderr, "Rexex compilation failed - %s\n", errorStr);
69 fprintf(stderr, "Unable to open item file '%s'\n", gsItemListFile);
70 perror("Unable to open item file");
73 while( fgets(buffer, BUFSIZ, fp) )
83 tmp = strchr(buffer, '#');
85 tmp = strchr(buffer, ';');
91 if(strlen(line) == 0) continue;
93 // Pass regex over line
94 if( (i = regexec(®ex, line, 5, matches, 0)) ) {
95 size_t len = regerror(i, ®ex, NULL, 0);
96 char *errorStr = malloc(len);
97 regerror(i, ®ex, errorStr, len);
98 fprintf(stderr, "Syntax error on line %i of item file '%s'\n%s", lineNum, gsItemListFile, errorStr);
104 type = line + matches[1].rm_so; line[ matches[1].rm_eo ] = '\0';
105 num = atoi( line + matches[2].rm_so );
106 price = atoi( line + matches[3].rm_so );
107 desc = line + matches[4].rm_so;
109 printf("Item '%s' - %i cents, %s:%i\n", desc, price, type, num);
112 for( i = 0; i < giNumHandlers; i ++ )
114 if( strcmp(type, gaHandlers[i]->Name) == 0 ) {
115 handler = gaHandlers[i];
121 fprintf(stderr, "Unknow item type '%s' on line %i (%s)\n", type, lineNum, desc);
125 for( i = 0; i < giNumItems; i ++ )
127 if( gaItems[i].Handler != handler ) continue;
128 if( gaItems[i].ID != num ) continue;
130 printf("Redefinition of %s:%i, updated\n", handler->Name, num);
131 gaItems[i].Price = price;
132 free(gaItems[i].Name);
133 gaItems[i].Name = strdup(desc);
136 if( i < giNumItems ) continue;
138 gaItems = realloc( gaItems, (giNumItems + 1)*sizeof(gaItems[0]) );
139 gaItems[giNumItems].Handler = handler;
140 gaItems[giNumItems].ID = num;
141 gaItems[giNumItems].Price = price;
142 gaItems[giNumItems].Name = strdup(desc);
147 char *trim(char *__str)
152 while( isspace(*__str) )
157 while( i-- && isspace(__str[i]) ) {