/*
 * Kwik index generator.
 */
#include <stdio.h>

#define  TEMP	"kwik.tmp"
#define	 FOLD	'\001'
#define	 NBUF	128

int	width	= 80;
int	rflag;
FILE	*tfp;
char	lbuf[NBUF];
char	rbuf[NBUF];

char	ok[] = {
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
	0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};

main(argc, argv)
char *argv[];
{
	register char *cp;
	register c, i;
	FILE *fp;
	int nf;

	nf = argc-1;
	for (i=1; i<argc; ++i) {
		cp = argv[i];
		if (*cp == '-') {
			--nf;
			argv[i] = NULL;
			++cp;
			while (c = *cp++)
				switch (c) {

				case 'R':
				case 'r':
					++rflag;
					break;

				case 'W':
				case 'w':
					if (++i >= argc)
						usage();
					width = atoi(argv[i]);
					if (width < 2 || width > NBUF) {
						fprintf(stderr, "Bad width.\n");
						exit(1);
					}
					--nf;
					argv[i] = NULL;
					break;

				default:
					usage();
				}
		}
	}
	if ((tfp = fopen(TEMP, "w")) == NULL) {
		fprintf(stderr, "Cannot create temp. file.\n");
		exit(1);
	}
	if (nf <= 0)
		rotate(stdin);
	else
		for (i=1; i<argc; ++i) {
			if ((cp = argv[i]) == NULL)
				continue;
			if ((fp = fopen(cp, "r")) == NULL) {
				fprintf(stderr, "%s: cannot open.\n", cp);
				fmkdl(tfp);
				exit(1);
			}
			rotate(fp);
			fclose(fp);
		}
	fclose(tfp);
	sprintf(lbuf, "sort%s -o %s %s", rflag?" -r":"", TEMP, TEMP);
	system(lbuf);
	if ((tfp = fopen(TEMP, "r")) == NULL) {
		fprintf(stderr, "Cannot reopen temp. file.\n");
		exit(1);
	}
	unrotate();
	fmkdl(tfp);
}

rotate(fp)
FILE *fp;
{
	register char *p;
	register c;

	while (fgets(lbuf, fp) != NULL) {
		p = lbuf;
		while (c = *p++) {
			if (ok[c]) {
				output(p-1);
				while (ok[*p])
					++p;
			}
		}
	}
}

output(rp)
register char *rp;
{
	register char *p;
	register c;

	p = rp;
	while (c = *p++)
		putc(c, tfp);
	putc(FOLD, tfp);
	p = lbuf;
	while (p < rp)
		putc(*p++, tfp);
	putc('\n', tfp);
}

unrotate()
{
	register char *p1, *p2;
	register c;

	while (fgets(lbuf, tfp) != NULL) {
		p1 = rbuf;
		while (p1 < &rbuf[width])
			*p1++ = ' ';
		p1 = &rbuf[width/2];
		p2 = lbuf;
		while ((c = *p2++) && c != FOLD) {
			if(p1 >= &rbuf[width])
				p1 = rbuf;
			*p1++ = c;
		}
		if (c == FOLD) {
			p1 = &rbuf[width/2];
			while (*p2++)
				;
			--p2;
			while (p2 > lbuf && (c = *--p2) != FOLD) {
				if (p1 == rbuf)
					p1 = &rbuf[width];
				*--p1 = c;
			}
		}
		p1 = &rbuf[width];
		while (p1 > rbuf) {
			if (*--p1 != ' ') {
				++p1;
				break;
			}
		}
		p2 = rbuf;
		while (p2 < p1)
			putchar(*p2++);
		putchar('\n');
	}
}

usage()
{
	fprintf(stderr, "Usage: kwik [-r] [-w width] [file ...]\n");
	exit(1);
}
