/* given PostScript input, output the Prolog and Setup sections,
 * plus the specified pages. Arguments:
 *	argv[1]		odd, even, or all
 *	argv[2]		lowest page number to print
 *	argv[3]		highest page to print
 * This program is a filter: it reads from stdin and writes to stdout.
 * It may be useful it you have a single-sided printer: you can print
 * odd pages, then turn the stack of paper over and print the even pages.
 * It may also be useful if you were printing a big document and a few
 * pages got spoiled, so you just want to reprint those specific pages.
 *
 * This program uses the second argument of the %%Page:
 * line to get page number, and requires input that is
 * at least minimally conforming to the PostScript structuring conventions.
 */

#include <stdio.h>
#include <string.h>

void usage(char *pname);


int
main(int argc, char **argv)
{
	char buff[BUFSIZ];
	int odd = 0;	/* if true, print odd pages */
	int even = 0;	/* if true, print even pages */
	int print;	/* if true, print current line */
	int begin, end;	/* range of pages to print */
	int page;	/* current page number */


	if (argc != 4) {
		usage(argv[0]);
	}

	/* determine if to print odd, even or all pages */
	if (strcmp(argv[1], "even") == 0) {
		even = 1;
	}
	else if (strcmp(argv[1], "odd") == 0) {
		odd = 1;
	}
	else if (strcmp(argv[1], "all") == 0) {
		even = odd = 1;
	}
	else {
		usage(argv[0]);
	}

	/* get range of pages to print */
	begin = atoi(argv[2]);
	end = atoi(argv[3]);

	/* start by printing prolog */
	print = 1;

	/* read input */
	while (fgets(buff, BUFSIZ, stdin)) {

		/* at beginning of each page, decide whether to output it */
		if (strncmp(buff, "%%Page: ", 8) == 0) {
			page = atoi(strrchr(buff, ' '));
			print = (page >= begin && page <= end &&
					( ((page & 1) == 1 && odd) ||
					((page & 1) == 0 && even) ));
		}

		/* print current line if appropriate */
		if (print) {
			printf("%s", buff);
		}

		/* stop printing at end of setup */
		if (strncmp(buff, "%%EndSetup", 10) == 0) {
			print = 0;
		}

		/* always print trailer */
		else if (strncmp(buff, "%%Trailer", 9) == 0) {
			print = 1;
		}
	}

	return(0);
}

void
usage(char *pname)
{
	fprintf(stderr, "usage: %s {odd|even|all} beginpage endpage\n", pname);
	fprintf(stderr, "\nPrints a subsets of pages from a PostScript file.\n");
	fprintf(stderr, "Reads from stdin and writes to stdout.\n");
	exit(1);
}
