#include <stdio.h>
#include <ctype.h>

char	*incl_path[100];
int	incl_count;

main(argc, argv)
int	argc;
char	*argv[];
{
if (argc < 2) {
	fprintf(stderr, "usage: %s [-Idir...] file [file...]\n", argv[0]);
	exit(1);
	}
incl_path[0] = ".";
incl_count = 1;
while (--argc > 0) {
	argv++;
	if ((*argv)[0] == '-' && (*argv)[1] == 'I') {
		if ((*argv)[2] == '\0') {
			incl_path[incl_count++] = *++argv;
			argc--;
			}
		else
			incl_path[incl_count++] = *argv + 2;
		}
	else if (doincl(*argv) != 0)
		perror(*argv);
	}
}

doincl(file)
char	*file;
{
register FILE	*fp;
register long	line_number;
char		line[512];

if ((fp = fopen(file, "r")) == (FILE *)NULL)
	return(-1);
line_number = 0;
while (fgets(line, sizeof line, fp) != (char *)NULL) {
	line_number++;
	if (line[0] != '#')
		fputs(line, stdout);
	else {
		register char	*c, *newfile;

		c = &line[1];
		while (isspace(*c))
			c++;
		if (strncmp(c, "include", 7) != 0)
			fputs(line, stdout);
		else {
			putchar('\n');
			while (*++c != '\0')
				if (*c == '"') {
					newfile = ++c;
					while (*c != '\0')
						if (*++c == '"') {
							*c = '\0';
							doincl_with_path(newfile);
							goto double_break;
							}
					fprintf(stderr, "%s: missing closing quote on line %ld\n", file, line_number);
					}
			fprintf(stderr, "%s: missing opening quote on line %ld\n", file, line_number);
			}
		}
double_break: ;
	}
(void)fclose(fp);
return(0);
}

doincl_with_path(file)
char	*file;
{
int		i;
char		full_name[128];
extern int	errno;

if (file[0] == '/') {
	if (doincl(file) != 0)
		perror(file);
	}
else {
	for (i = 0; i < incl_count; i++) {
		sprintf(full_name, "%s/%s", incl_path[i], file);
		if (doincl(full_name) == 0)
			return;
		if (errno != 2)		/* No such file or directory */
			perror(full_name);
		}
	errno = 2;
	perror(file);
	}
}
