#define INITIALBUFSIZE 2
-struct nest {
- long pos;
- struct nest *next;
+struct cs {
+ long pl;
+ struct cs *next;
};
int main(int argc, char *argv[])
{
- size_t offset, stacksize, depth;
+ size_t offset, bufsize, depth;
char *buf, *ptr;
- struct nest *temp, *stack;
+ struct cs *temp, *cs;
FILE *in;
- if(argc != 2){
+ if(argc != 2)
die("Usage: %s PROGRAM\n", argv[0]);
- }
check_null(in = fopen(argv[1], "r"), "fopen");
- check_null(buf = calloc(stacksize = INITIALBUFSIZE, 1), "calloc");
+ check_null(buf = calloc(bufsize = INITIALBUFSIZE, 1), "calloc");
ptr = buf;
- while(1){
- switch(fgetc(in)){
- case EOF:
- free(buf);
- check_fail(fclose(in), "fclose", -1);
- return EXIT_SUCCESS;
- case '>':
- if(++ptr >= buf+stacksize){
- offset = ptr-buf;
- check_null(buf = realloc(buf, stacksize *=2), "realloc");
- ptr = buf+offset;
- memset(ptr, 0, stacksize/2);
- }
- break;
- case '<':
- if(ptr-- == buf){
- die("There is no stack position -1\n");
- }
- break;
- case '+':
- ++*ptr;
- break;
- case '-':
- --*ptr;
- break;
- case '.':
- putchar(*ptr);
- break;
- case ',':
- *ptr = getchar();
- break;
- case '[':
- if(*ptr){
- temp = stack;
- check_null(stack = malloc(sizeof(struct nest)), "malloc");
- stack->next = temp;
- check_fail(stack->pos = ftell(in), "ftell", -1);
- } else {
- depth = 1;
- while(depth > 0){
- switch(fgetc(in)){
- case ']':
- depth--;
- break;
- case '[':
- depth++;
- }
+ while (1){
+ switch (fgetc(in)){
+ case EOF:
+ free(buf);
+ check_fail(fclose(in), "fclose", -1);
+ return EXIT_SUCCESS;
+ case '>':
+ if (++ptr >= buf+bufsize){
+ offset = ptr-buf;
+ check_null(buf = realloc(buf, bufsize *=2),
+ "realloc");
+ ptr = buf+offset;
+ memset(ptr, 0, bufsize/2);
+ }
+ break;
+ case '<':
+ if (ptr-- == buf)
+ die("There is no stack position -1\n");
+ break;
+ case '+':
+ ++*ptr;
+ break;
+ case '-':
+ --*ptr;
+ break;
+ case '.':
+ putchar(*ptr);
+ break;
+ case ',':
+ *ptr = getchar();
+ break;
+ case '[':
+ if (*ptr){
+ temp = cs;
+ check_null(cs = malloc(sizeof(struct cs)),
+ "malloc");
+ cs->next = temp;
+ check_fail(cs->pl = ftell(in), "ftell", -1);
+ } else {
+ depth = 1;
+ while(depth > 0){
+ switch(fgetc(in)){
+ case ']':
+ depth--;
+ break;
+ case '[':
+ depth++;
}
}
- break;
- case ']':
- check_fail(fseek(in, stack->pos-1, SEEK_SET), "fseek", -1);
- temp = stack;
- stack = stack->next;
- free(temp);
+ }
+ break;
+ case ']':
+ check_fail(fseek(in, cs->pl-1, SEEK_SET), "fseek", -1);
+ temp = cs;
+ cs = cs->next;
+ free(temp);
}
}
}