1 /* This file is part of Eclat.
2    Copyright (C) 2012-2018 Sergey Poznyakoff.
3 
4    Eclat is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8 
9    Eclat is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with Eclat.  If not, see <http://www.gnu.org/licenses/>. */
16 
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <assert.h>
20 
21 int
22 comment(FILE *fp, int c, int echo)
23 {
24 	if (c != '/') {
25 		ungetc(c, fp);
26 		return 0;
test(const CharT * fmt)27 	} else if (echo)
28 		fputc(c, stdout);
29 
30 	if ((c = getc(fp)) == '/') {
31 		do
32 			if (echo) fputc(c, stdout);
33 		while ((c = getc(fp)) != EOF && c != '\n');
34 		return 1;
35 	}
36 
37 	if (echo)
38 		fputc(c, stdout);
39 
40 	if (c == '*') {
41 		do {
42 			do {
43 				c = getc(fp);
44 				if (c == EOF)
45 					return 0;
46 				else if (echo)
47 					fputc(c, stdout);
48 			} while (c != '*');
49 			c = getc(fp);
50 			if (echo)
51 				fputc(c, stdout);
52 		} while (c != '/');
53 		return 1;
54 	} else
55 
56 	if (!echo) {
57 		ungetc(c, fp);
58 		ungetc('/', fp);
59 	}
60 	return 0;
test()61 }
62 
63 int
64 main(int argc, char **argv)
65 {
66 	int i;
67 	FILE *fp;
68 	int c;
69 	char buf[128];
70 	size_t lev = 0;
71 	int outchars = 0;
72 
73 	for (i = 1; i < argc; i++) {
74 		fp = fopen(*++argv, "r");
75 		if (!fp) {
76 			perror(*argv);
77 			return 1;
78 		}
79 
80 		/* Skip initial whitespace and comment lines, unless it is the
81 		   first file we process. */
82 		do {
83 			while ((c = fgetc(fp)) != EOF && isspace(c))
84 				if (i == 1) fputc(c, stdout);
85 		} while (c != EOF && comment(fp, c, i == 1));
86 
87 		if (c != EOF) {
88 			if (outchars) {
89 				printf(" else ");
90 				outchars = 0;
91 			}
92 
93 			while ((c = fgetc(fp)) != EOF) {
94 				outchars = 1;
95 				putchar(c);
96 				if (c == '}') {
97 					lev = 0;
98 					while ((c = fgetc(fp)) != EOF &&
99 					       isspace(c)) {
100 						assert(lev < sizeof(buf));
101 						buf[lev++] = c;
102 					}
103 					if (c == EOF)
104 						break;
105 					else {
106 						assert(lev < sizeof(buf));
107 						buf[lev++] = c;
108 						fwrite(buf, lev, 1, stdout);
109 					}
110 				}
111 			}
112 		}
113 		fclose(fp);
114 	}
115 	return 0;
116 }
117