/* print.c

 print (C) 1986 by Robert H. Leivian


	simple print file utility by: Bob Leivian


	print -nh^lwp:<string> file1 file2 file3 ...

	this is designed to be called from the pr driver with the
	expanded list of files to print with a option list
*/

#include <stdio.h>
#include <ctype.h>
char * fgets();

int numbers = 0;
int headers = 0;
int control = 0;
int prefix = 0;

char theprefix [132];
char buf[136];

main(argc, argv)
int argc;
char *argv[];
{
	int i;
	char *p;
	FILE *out;
	char buf[136];
	char name[30];
	char c;

	if (argc < 2) {
		printf("usage: print -hnpwl^:<string> file1 file2...\n");
		exit(27);
	}

	out = fopen("prt:", "w");
	if (!out) {
		printf("can't open the printer\n");
		exit(27);
	}

	while (argv[1]) {
		/* process options if any */
		while (*argv[1] == '-') {
			p = (char *) &*argv[1];

			p++;		/* point to the option chars */
			do {
				switch (*p) {
				case ' ':
				case '\0':		/* ignore nulls and spaces */
					break;

				case 'p':		/* turn on proportional mode */
					fputs("\n\x1b[2p\n", out);
					break;

				case 'w':		/* turn on wide (132 col) mode */
#define WORKS
#ifdef WORKS
					fputs("\n\x1b[4w\n", out);
#else
					fputs("\017", out);
#endif
					fflush(out);
					break;

				case 'l':		/* turn on letter quality mode */
					fputs("\n\x1b[2\"z\n", out);
					break;

				case ':':		/* print control string first */
					strcpy(theprefix, ++p);
					prefix++;
					goto next; /* consume rest of option */

				case '^':		/* print control chars as ^X */
					control++;
				break;

				case 'n':		/* print line numbers */
					numbers++;
					break;

				case 'h':		/* print a header */
					headers++;
					break;

				default:
					printf("'%c' is an invalid option\n", *p);
					exit(27);
				}
				p++; 
			} while (*p);
	next:
			argc--;
			argv++;
		}

		/* put out the control prefix if any */
		if (prefix) {
			p = theprefix;
			while(*p) {
				if (*p == '^') { 
					p++;
					c = *p - '@';
					putc(c, out);
				} else
					putc(*p, out);
				p++;
			}

			/* reset the prefix flag */
			prefix = 0;
		}

		/* now print the file */
		doPrint(argv[1], out);
		argv++;
	}
}


/* do the actual print for a file */
doPrint(name, out)
char * name;
FILE * out;
{
	extern errno;
	FILE *in;
	int line = 0;
	char *p;
	char buf[136];

	in = fopen(name, "r");

	if (in) {
		line = 0;

		/* print a file header if desired */
		if (headers)
			fprintf(out, "File: %s\n\n", name);

		while ((p = fgets(buf, 134, in)) != NULL){
			line++;

			/* print a line number id desired */
			if (numbers) 
				fprintf(out, "%4d ", line);

			/* interp control chars as ^X format */
			if (control) {
				while(*p) {
					if ((*p < ' ') && (*p != '\n') && (*p != '\t')){
						putc('^', out);
						putc(*p + '@', out);
					} else
						putc(*p, out);
					p++;
				}
			} else
				fputs(p, out);
	 	}
		putc('\f', out);
		fclose(in);
	} else
		fprintf(out, "unable to open: '%s', errno: %d\f", name, errno);
}
