/* more program by therat@ucscb.ucsc.edu */

#include <stdio.h>
#include <sys/file.h>
#include <sgtty.h>

#define ZMORE 0


main(argc, argv)
int argc;
char **argv;
{
 int c=1;

	while (c < argc)
		doc(argv[c++]);
}

doc(s)
char *s;
{
	char filename[128], tmpfile[128];
	int fd, pid;
	long t;

	sprintf(filename, "%s", s);
	/* could stat the file here to make sure it's there */

	time(&t);
	sprintf(tmpfile, "/usr/tmp/#GBtrash%05d", (t >> 4) & 0x7fff);
	fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0600);
	if (fd < 0) {
		fprintf(stderr, "doc(): %s: ", filename);
		perror("open failed");
		return;
	}

	switch (pid = fork()) {
		case -1 :
			perror("doc(): fork for zcat failed");
			break;

		case 0 :
			dup2(fd, 1);
#			if (ZMORE)
			  execl("/usr/ucb/zcat", "zcat", filename, 0);
			  perror("doc(): execl for zcat failed");
#			else
			  execl("/bin/cat", "cat", filename, 0);
#			endif

		default :
			while (wait(0) != pid)
				;
	}

	close(fd);
	page(tmpfile);
	unlink(tmpfile);
}

page(file)
char *file;
{
	char buf[4096];
	FILE *fp;
	int line;

	fp = fopen(file, "r");
	if (!fp) {
		fprintf(stderr, "page(): %s: ", file);
		perror("open failed");
		return;
	}

	while (fgets(buf, sizeof(buf), fp)) {
		++line;
		fputs(buf, stdout);
		if (line == 23) {
			char ch;

			fputs(" -- Hit SPACEBAR for more -- ", stdout);
			fflush(stdout);
			do
				ch = get_a_char();
			while (ch != ' ' && ch!='q');
			fputs("\b\b\b\b\b\b\b\b\b\b\b\b            \b\b\b\b\b\b\b\b\b\b\b\b", stdout);
			if (ch=='q') {
			 	fclose (fp);
				return;
			}
			line = 0;
		}
	}
	fclose(fp);
}

get_a_char()
{
	struct sgttyb foo, bar;
	char c;

	ioctl(0, TIOCGETP, &foo);
	bar = foo;
	foo.sg_flags |= CBREAK;
	foo.sg_flags &= ~ECHO;
	ioctl(0, TIOCSETN, &foo);

	c = getchar();
/* 	while (!read(0, &c, 1)) */
/* 		; */


	ioctl(0, TIOCSETN, &bar);

	return c;
}
