#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAXWIDTH 132
#define MAXREP 10
char buf[MAXREP][MAXWIDTH];
int maxcol[MAXREP] = {-1};
int lineno;
int width = 132;
int length = 66;
int indent;
int npages = 1;
int literal;
int onlcr;
char *name;
char *host;
char *acctfile;
__dead void usage(void);
int
main(int argc, char **argv)
{
FILE *p = stdin, *o = stdout;
int i, col;
char *cp;
int done, linedone, maxrep, ch;
char *limit;
while ((ch = getopt(argc, argv, "crh:i:j:l:n:w:")) != -1) {
switch (ch) {
case 'n':
name = optarg;
break;
case 'h':
host = optarg;
break;
case 'w':
if ((i = atoi(optarg)) > 0 && i <= MAXWIDTH)
width = i;
break;
case 'l':
length = atoi(optarg);
break;
case 'i':
indent = atoi(optarg);
break;
case 'r':
onlcr = 1;
break;
case 'c':
literal++;
break;
case 'j':
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc)
acctfile = *argv;
memset(buf, ' ', sizeof(buf));
done = 0;
while (!done) {
col = indent;
maxrep = -1;
linedone = 0;
while (!linedone) {
switch (ch = getc(p)) {
case EOF:
linedone = done = 1;
ch = '\n';
break;
case '\f':
lineno = length;
case '\n':
if (maxrep < 0)
maxrep = 0;
linedone = 1;
break;
case '\b':
if (--col < indent)
col = indent;
break;
case '\r':
col = indent;
break;
case '\t':
col = ((col - indent) | 07) + indent + 1;
break;
case '\031':
if ((ch = getchar()) == '\1') {
fflush(stdout);
kill(getpid(), SIGSTOP);
break;
} else {
ungetc(ch, stdin);
ch = '\031';
}
default:
if (col >= width || (!literal && ch < ' ')) {
col++;
break;
}
cp = &buf[0][col];
for (i = 0; i < MAXREP; i++) {
if (i > maxrep)
maxrep = i;
if (*cp == ' ') {
*cp = ch;
if (col > maxcol[i])
maxcol[i] = col;
break;
}
cp += MAXWIDTH;
}
col++;
break;
}
}
for (i = 0; i <= maxrep; i++) {
for (cp = buf[i], limit = cp+maxcol[i]; cp <= limit;) {
putc(*cp, o);
*cp++ = ' ';
}
if (i < maxrep)
putc('\r', o);
else {
if (onlcr)
putc('\r', o);
putc(ch, o);
}
if (++lineno >= length) {
fflush(o);
npages++;
lineno = 0;
}
maxcol[i] = -1;
}
}
if (lineno) {
putchar('\f');
npages++;
}
if (name && acctfile && access(acctfile, 02) >= 0 &&
freopen(acctfile, "a", stdout) != NULL) {
printf("%7.2f\t%s:%s\n", (float)npages, host, name);
}
exit(0);
}
__dead void
usage(void)
{
extern char *__progname;
fprintf(stderr, "usage: %s [-c] [-r] [-h host] [-i indent] [-l length]"
" [-n name] [-w width] [acctfile]\n", __progname);
exit(1);
}