Debian Codegraph @

texk/psutils/psutils-src/psbook.c

raw
1 /* psbook.c
2 * (c) Reuben Thomas 2012-2014
3 * (c) Angus J. C. Duggan 1991-1997
4 * See file LICENSE for details.
5 *
6 * rearrange pages in conforming PS file for printing in signatures
7 */
8
9 #include "config.h"
10
11 #include <unistd.h>
12 #include "progname.h"
13 #include "binary-io.h"
14
15 #include "psutil.h"
16
17 const char *syntax = "[-q] [-sSIGNATURE] [INFILE [OUTFILE]]\n SIGNATURE must be positive and divisible by 4\n";
18
19 const char *argerr_message = "";
20
21 int
22 main(int argc, char *argv[])
23 {
24 int signature = 0;
25 int currentpg, maxpage;
26 int opt;
27
28 set_program_name (argv[0]);
29
30 verbose = 1;
31
32 while((opt = getopt(argc, argv, "vqs:")) != EOF) {
33 switch(opt) {
34 case 's': /* signature size */
35 signature = atoi(optarg);
36 if (signature < 1 || signature % 4) usage();
37 break;
38 case 'q': /* quiet */
39 verbose = 0;
40 break;
41 case 'v': /* version */
42 default:
43 usage();
44 break;
45 }
46 }
47
48 infile = stdin;
49 outfile = stdout;
50
51 /* Be defensive */
52 if((argc - optind) < 0 || (argc - optind) > 2) usage();
53
54 if (optind != argc) {
55 /* User specified an input file */
56 if ((infile = fopen(argv[optind], "rb")) == NULL)
57 die("can't open input file %s", argv[optind]);
58 optind++;
59 }
60
61 if (optind != argc) {
62 /* User specified an output file */
63 if ((outfile = fopen(argv[optind], "wb")) == NULL)
64 die("can't open output file %s", argv[optind]);
65 optind++;
66 }
67
68 if(optind != argc) usage();
69
70 if (infile == stdin && set_binary_mode(fileno(stdin), O_BINARY) < 0)
71 die("can't reset stdin to binary mode");
72 if (outfile == stdout && set_binary_mode(fileno(stdout), O_BINARY) < 0)
73 die("can't reset stdout to binary mode");
74
75 if ((infile=seekable(infile))==NULL)
76 die("can't seek input");
77
78 scanpages(NULL);
79
80 if (!signature)
81 signature = maxpage = pages+(4-pages%4)%4;
82 else
83 maxpage = pages+(signature-pages%signature)%signature;
84
85 /* rearrange pages */
86 writeheader(maxpage, NULL);
87 writeprolog();
88 writesetup();
89 for (currentpg = 0; currentpg < maxpage; currentpg++) {
90 int actualpg = currentpg - currentpg%signature;
91 switch(currentpg%4) {
92 case 0:
93 case 3:
94 actualpg += signature-1-(currentpg%signature)/2;
95 break;
96 case 1:
97 case 2:
98 actualpg += (currentpg%signature)/2;
99 break;
100 default: /* Avoid a compiler warning */
101 break;
102 }
103 if (actualpg < pages)
104 writepage(actualpg);
105 else
106 writeemptypage();
107 }
108 writetrailer();
109
110 return 0;
111 }