/*
 * coorno
 */

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

#ifdef	DOCUMENTATION

title	coorno	Cookie text file formatter
index		Cookie text file formatter

synopsis

	coorno [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.

	The output is in runoff format.

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];
int	ncookies = 0;

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

	nfiles = 0;
	puts(".lm 0.rm 72.nf");
	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
	}
}

int percent = TRUE;

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

	while (fgets(line, sizeof line, fp) != NULL) {
	    if (percent && line[0] == '\n')
		continue;
	    flag = (line[0] == '%' && line[1] == '%');
	    if (flag && percent)
		continue;
	    if (flag)
		puts(".tp 6.s");
	    else {
		for (tp = line; *tp != EOS; tp++) {
		    switch (*tp) {
		    case '\\':
		    case '_':
		    case '^':
		    case '#':
		    case '%':
		    case '&':
			putchar('_');
		    default:
			putchar(*tp);
		    }
		}
	    }
	    percent = flag;
	}
	if (!percent) {
	    puts(".tp 6.s");
	    percent = TRUE;
	}
}

