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