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