+#include "c2html.h"
+
+inputfile_t *inputfilebuffer(size_t capacity) {
+ inputfile_t *inputfile = (inputfile_t*) malloc(sizeof(inputfile_t));
+ inputfile->lines = (char**) malloc(capacity * sizeof(char*));
+ inputfile->capacity = capacity;
+ inputfile->count = 0;
+
+ return inputfile;
+}
+
+void addline(inputfile_t *inputfile, char* line, size_t width) {
+ char *l = (char*) malloc(width+1);
+ memcpy(l, line, width);
+ l[width] = 0;
+ if (inputfile->count >= inputfile->capacity) {
+ inputfile->capacity <<= 1;
+ inputfile->lines = realloc(inputfile->lines, inputfile->capacity);
+ }
+ inputfile->lines[inputfile->count] = l;
+ inputfile->count++;
+}
+
+void freeinputfilebuffer(inputfile_t *inputfile) {
+ for (int i = 0 ; i < inputfile->count ; i++) {
+ free(inputfile->lines[i]);
+ }
+ free(inputfile->lines);
+ free(inputfile);
}
+inputfile_t *readinput(char *filename) {
+
+ int fd = open(filename, O_RDONLY);
+ if (fd == -1) return NULL;
+
+ inputfile_t *inputfile = inputfilebuffer(512);
+
+ const size_t bufsize = 1024;
+ char buf[bufsize];
+ ssize_t r;
+
+ size_t maxlinewidth = 80;
+ char *line = (char*) malloc(maxlinewidth);
+ size_t col = 0;
+
+ while ((r = read(fd, buf, bufsize)) > 0) {
+ for (size_t i = 0 ; i < r ; i++) {
+ if (col >= maxlinewidth-4) {
+ maxlinewidth <<= 1;
+ line = realloc(line, maxlinewidth);
+ }
+
+ if (buf[i] == '\n') {
+ line[col] = 0;
+ addline(inputfile, line, col);
+ col = 0;
+ } else if (buf[i] == '<') {
+ line[col++] = '&'; line[col++] = 'l';
+ line[col++] = 't'; line[col++] = ';';
+ } else if (buf[i] == '>') {
+ line[col++] = '&'; line[col++] = 'g';
+ line[col++] = 't'; line[col++] = ';';
+ } else {
+ line[col++] = buf[i];
+ }
+ }
+ }
+
+ free(line);
+
+ close(fd);
+
+ return inputfile;
+}
+
+void printhelp() {
+ printf("Formats source code using HTML.\n\nUsage:\n"
+ " c2html [FILE...]"
+ "\n");
+
+
+}
+
+int lnw(size_t lnc) {
+ int w = 1, p = 1;
+ while ((p*=10) < lnc) w++;
+ return w;
+}
+
+int main(int argc, char** argv) {
+
+ if (argc == 1) {
+ printhelp();
+ return 0;
+ } else {
+
+ inputfile_t *inputfile = readinput(argv[1]);
+ if (inputfile) {
+ printf("\n");
+ for (int i = 0 ; i < inputfile->count ; i++) {
+ printf("%*d: %s\n", lnw(inputfile->count),
+ i, inputfile->lines[i]);
+ }
+ printf("
\n");
+ freeinputfilebuffer(inputfile);
+ }
+
+ return 0;
+ }
+}
+