summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 9b987184b2a8a29503e097a595743f0aeb4e9a6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "config.h"
#include "cmark.h"
#include "debug.h"
#include "bench.h"

void print_usage()
{
	printf("Usage:   cmark [FILE*]\n");
	printf("Options: --help, -h    Print usage information\n");
	printf("         --ast         Print AST instead of HTML\n");
	printf("         --version     Print version\n");
}

static void print_document(node_block *document, bool ast)
{
	if (ast) {
		cmark_debug_print(document);
	} else {
		printf("%s", cmark_render_html(document));
	}
}

int main(int argc, char *argv[])
{
	int i, numfps = 0;
	bool ast = false;
	int *files;
	unsigned char buffer[4096];
	cmark_doc_parser *parser;
	size_t offset;
	node_block *document;

	parser = cmark_new_doc_parser();
	files = (int *)malloc(argc * sizeof(*files));

	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--version") == 0) {
			printf("cmark %s", VERSION);
			printf(" - CommonMark converter (c) 2014 John MacFarlane\n");
			exit(0);
		} else if ((strcmp(argv[i], "--help") == 0) ||
			   (strcmp(argv[i], "-h") == 0)) {
			print_usage();
			exit(0);
		} else if (strcmp(argv[i], "--ast") == 0) {
			ast = true;
		} else if (*argv[i] == '-') {
			print_usage();
			exit(1);
		} else { // treat as file argument
			files[numfps++] = i;
		}
	}

	for (i = 0; i < numfps; i++) {
		FILE *fp = fopen(argv[files[i]], "r");
		if (fp == NULL) {
			fprintf(stderr, "Error opening file %s: %s\n",
				argv[files[i]], strerror(errno));
			exit(1);
		}

		start_timer();
		while (fgets((char *)buffer, sizeof(buffer), fp)) {
			offset = strlen((char *)buffer);
			cmark_process_line(parser, buffer, offset);
		}
		end_timer("processing lines");

		fclose(fp);
	}

	if (numfps == 0) {
		/*
		document = cmark_parse_file(stdin);
		print_document(document, ast);
		exit(0);
		*/

		while (fgets((char *)buffer, sizeof(buffer), stdin)) {
			offset = strlen((char *)buffer);
			cmark_process_line(parser, buffer, offset);
		}
	}

	start_timer();
	document = cmark_finish(parser);
	end_timer("finishing document");
	cmark_free_doc_parser(parser);

	start_timer();
	print_document(document, ast);
	end_timer("print_document");

	start_timer();
	cmark_free_blocks(document);
	end_timer("free_blocks");

	free(files);

	return 0;
}