]> Pileus Git - ~andy/ct/blob - ct.c
Update knots
[~andy/ct] / ct.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <glib.h>
4
5 #include "parse.h"
6
7 gpointer parse(FILE *input, GList **data, GList **code);
8
9 int main(int argc, char **argv)
10 {
11         /* Parse arguments */
12         char *option_output = NULL;
13         GOptionEntry entries[] = {
14                 {"output", 'o', 0, G_OPTION_ARG_STRING,  &option_output,
15                         "Output file", ""},
16                 {NULL}
17         };
18         GOptionContext *context = g_option_context_new("[template]");
19         g_option_context_add_main_entries(context, entries, NULL);
20         g_option_context_parse(context, &argc, &argv, NULL);
21
22         /* Handle input and output */
23         FILE *input = stdin;
24         if (argv[1] && !g_str_equal(input, "-"))
25                 input = fopen(argv[1], "r");
26         if (!input)
27                 g_error("invalid input file");
28
29         FILE *output = stdout;
30         if (option_output && !g_str_equal(option_output, "-"))
31                 output = fopen(option_output, "w");
32         else if (input != stdin && option_output == NULL) {
33                 char *outf = g_strdup(argv[1]);
34                 outf[strlen(outf)-1] = '\0';
35                 output = fopen(outf, "w");
36                 g_free(outf);
37         }
38         if (!output)
39                 g_error("invalid output file");
40
41         /* Start compiling */
42         GList *data = NULL;
43         GList *code = NULL;
44         parse(input, &data, &code);
45         data = g_list_reverse(data);
46         code = g_list_reverse(code);
47
48         fprintf(output, "#include <stdio.h>\n");
49         fprintf(output, "\n");
50         for (GList *cur = data; cur; cur = cur->next)
51                 fprintf(output, "%s", (gchar *)cur->data);
52         fprintf(output, "\n");
53         for (GList *cur = code; cur; cur = cur->next)
54                 fprintf(output, "%s", (gchar *)cur->data);
55
56         fclose(input);
57         fclose(output);
58 }