/*
 * cootxt
 */

/*)BUILD	$(TKBOPTIONS) = {
			TASK	= ...CTX
		}
*/

#ifdef	DOCUMENTATION

title	cootxt	Cookie text file concatenator
index		Cookie text file concatenator

synopsis

	cootxt [name ...]

description

	Concatenate each file, making sure that the last
	cookie of each file is terminated by '%%' and
	that there are no null-cookies.
	
	cootxt accepts wild-card file name arguments; if no
	files are given, it copies stdin.

diagnostics

	.lm +8
	.s.i -8;"file name": cannot open
	.s.i -8;"file name": illegal file name
	.lm -8

author

	Martin Minow

bugs

#endif

#include <stdio.h>

char	line[513];

main(argc, argv)
int		argc;
char		*argv[];
{
	register int	i, nfiles;
	register FILE	*fp;
	int		gotcha;

	nfiles = 0;
	if (argc < 2) {
	    ++nfiles;
	    process(stdin);
	}
	else {
#ifdef unix
	    for (i = 1; i < argc; ++i) {
		if ((fp = fopen(argv[i], "r")) == NULL) {
		    perror(argv[i]);
		}
		else {
		    ++nfiles;
		    process(fp);
		    fclose(fp);
		}
	    }
#else
	    for (i = 1; i < argc; ++i) {
		if ((fp = fwild(argv[i], "r")) == NULL) {
		    perror(argv[i]);
		}
		else {
		    for (gotcha = 0; fnext(fp) != NULL; gotcha++) {
			++nfiles;
			process(fp);
		    }
		    if (gotcha == 0) {
			fprintf(stderr, "\"%s\": no matching files\n",
			    argv[i]);
		    }
		}
	    }
#endif
	}
}

process(fp)
FILE		*fp;			/* File pointer			*/
{
	register int	percent;
	register int	flag;

	percent = FALSE;
	while (fgets(line, sizeof line, fp) != NULL) {
	    flag = (line[0] == '%' && line[1] == '%');
	    if (flag && percent)
		continue;
	    fputs(line, stdout);
	    percent = flag;
	}
	if (!percent)
	    fputs("%%\n", stdout);
}

