#include #include "buf.h" #include #include typedef enum { false, true } bool; FILE* getfile(int argc, char** argv){ if (argc >= 2) return fopen(argv[1], "r"); else return stdin; } FILE* in; buf* inbuf; int width = 80; bool brk = false; // not implemented size_t fillbuf(size_t len){ // returns real len int c; size_t set; for (set = buflen(inbuf); set < len && (c = fgetc(in)) != EOF;set++) inschrbuf(inbuf, c); return set; } size_t chrfill(char chr){ size_t line; size_t len = buflen(inbuf); char* str = peekstrbuf(inbuf, 0, len); for (line = 0; line < len; line++) if (str[line] == chr) return line+1; for (int c = 0; c != chr && (c = fgetc(in)) != EOF; line++) inschrbuf(inbuf, c); return line; } char* center(char* text){ size_t len = strlen(text); int max = width/2 + len/2; // excluding terminator int min = max-len+1; // first index of *text char* str = malloc(sizeof(char)*(max + 1)); str[max] = 0; for (int i=0; i < min; i++) str[i] = ' '; memcpy(str+min, text, len); return str; } char* cmd(void){ char* dat = popstrbuf(inbuf, chrfill('\n')); if (!strncmp(dat, "CT ", 3)){ return center(dat+3); } return NULL; } char* typeset(void){ return popstrbuf(inbuf, chrfill('\n')); } char* line(void){ size_t sz; if ( (sz = fillbuf(2)) == 0) return ""; char* twobytes = peekstrbuf(inbuf, 0, 2); // .., .\n, or ^.? if (sz == 1 || twobytes[1] == '\n') return typeset(); if (twobytes[0] == '.') popchrbuf(inbuf); if (twobytes[0] == '.' && twobytes[1] != '.'){ char* data = cmd(); if (data) return data; return line(); } else { return typeset(); } } int main(int argc, char** argv){ int c; in = getfile(argc, argv); inbuf = newbuf(256); if (in == NULL){ perror(argv[1]); return 1; } char* out; while ( (out = line())[0] != '\0'){ printf("%s",out); } fclose(in); return 0; }