aboutsummaryrefslogtreecommitdiff
path: root/usr.bin/pr/pr.c
blob: e853b9cdf6a68bc5e6e5af9330e3b2390bf56bf3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
/*	$OpenBSD: pr.c,v 1.41 2017/12/23 20:53:07 cheloha Exp $	*/

/*-
 * Copyright (c) 1991 Keith Muller.
 * Copyright (c) 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Keith Muller of the University of California, San Diego.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#define _GNU_SOURCE /* for vasprintf */

#include <sys/types.h>
#include <sys/stat.h>

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "pr.h"
#include "extern.h"

/*
 * pr:	a printing and pagination filter. If multiple input files
 *	are specified, each is read, formatted, and written to standard
 *	output. By default, input is separated into 66-line pages, each
 *	with a header that includes the page number, date, time and the
 *	files pathname.
 *
 *	Complies with posix P1003.2/D11
 */

/*
 * pr: more boundary conditions than a four-legged porcupine
 *
 * the original version didn't support form-feeds, while many of the ad-hoc
 * pr implementations out there do.  Addding this and making it work reasonably
 * in all four output modes required quite a bit of hacking and a few minor
 * bugs were noted and fixed in the process.  Some implementations have this
 * as the as -f, some as -F so we accept either.
 *
 * The implementation of form feeds on top of the existing I/O structure is
 * a bit idiosyncratic.  Basically they are treated as temporary end-of-file
 * conditions and an additional level of "loop on form feed" is added to each
 * of the output modes to continue after such a transient end-of-file's. This
 * has the general benefit of making the existing header/trailer logic work
 * and provides a usable framework for rational behavior in multi-column modes.
 *
 * The original "efficient" implementation of the "skip to page N" option was
 * bogus and I substituted the basic inhibit printing until page N approach.
 * This is still fairly bogus vis-a-vis numbering pages on multiple files
 * restarting at one, but at least lets you consistently reprint some large
 * document starting in the middle, in any of the output modes.
 *
 * Additional support for overprinting via <back-space> or <return> would
 * be nice, but is not trivial across tab interpretation, output formatting
 * and the different operating modes.  Support for line-wrapping, either
 * strict or word-wrapped would be really useful and not all that hard to
 * kludge into the inln() implementation.  The general notion is that -wc n
 * would specify width and wrapping with a marker character c and -Wc n
 * would add word wrapping with a minimum width n and delimiters c, defaulting
 * to tab, blank, and -, and column width.  Word wrapping always involves
 * painful policy questions which are difficult to specify unless you just
 * hardwire in some fixed rules. Think quotes, punctuation and white-space
 * elimination and whether you'd do the same thing with a C program and
 * something like columninated newspaper text.
 *
 *				George Robbins <grr@tharsis.com> 4/22/97.
 */

/*
 * parameter variables
 */
int	pgnm;		/* starting page number */
int	skipping;	/* we're skipping to page pgnum */
int	clcnt;		/* number of columns */
int	colwd;		/* column data width - multiple columns */
int	across;		/* mult col flag; write across page */
int	dspace;		/* double space flag */
char	inchar;		/* expand input char */
int	ingap;		/* expand input gap */
int	formfeed;	/* use formfeed as trailer */
int	inform;		/* grok formfeeds in input */
char	*header;	/* header name instead of file name */
char	ochar;		/* contract output char */
int	ogap;		/* contract output gap */
int	lines;		/* number of lines per page */
int	merge;		/* merge multiple files in output */
char	nmchar;		/* line numbering append char */
int	nmwd;		/* width of line number field */
int	offst;		/* number of page offset spaces */
int	nodiag;		/* do not report file open errors */
char	schar;		/* text column separation character */
int	sflag;		/* -s option for multiple columns */
int	nohead;		/* do not write head and trailer */
int	pgwd;		/* page width with multiple col output */

/*
 * misc globals
 */
volatile sig_atomic_t	ferr;	/* error message delayed */
int	addone = 0;	/* page length is odd with double space */
int	errcnt = 0;	/* error count on file processing */
int	beheaded = 0;	/* header / trailer link */
char	digs[] = "0123456789";	/* page number translation map */

int
main(int argc, char *argv[])
{
    int ret_val;

    if (pledge("stdio rpath", NULL) == -1) {
	perror("pledge");
	exit(1);
    }

    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
	(void)signal(SIGINT, terminate);
    ret_val = setup(argc, argv);
    if (!ret_val) {
	/*
	 * select the output format based on options
	 */
	if (merge)
	    ret_val = mulfile(argc, argv);
	else if (clcnt == 1)
	    ret_val = onecol(argc, argv);
	else if (across)
	    ret_val = horzcol(argc, argv);
	else
	    ret_val = vertcol(argc, argv);
    } else
	usage();
    flsh_errs();
    if (errcnt || ret_val)
	exit(1);
    return(0);
}

/*
 * onecol:    print files with only one column of output.
 *        Line length is unlimited.
 */
int
onecol(int argc, char *argv[])
{
    int off;
    int lrgln;
    int linecnt;
    int num;
    int cnt;
    int rc;
    int lncnt;
    int pagecnt;
    int ips;
    int ops;
    int cps;
    char *obuf = NULL;
    char *lbuf;
    char *nbuf;
    char *hbuf = NULL;
    char *ohbuf;
    FILE *inf = NULL;
    char *fname;
    int mor;
    int error = 1;

    if (nmwd)
	num = nmwd + 1;
    else
	num = 0;
    off = num + offst;

    /*
     * allocate line buffer
     */
    if ((obuf = malloc((unsigned)(LBUF + off)*sizeof(char))) == NULL)
	goto oomem;

    /*
     * allocate header buffer
     */
    if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL)
	goto oomem;

    ohbuf = hbuf + offst;
    nbuf = obuf + offst;
    lbuf = nbuf + num;

    if (num)
	nbuf[--num] = nmchar;

    if (offst) {
	(void)memset(obuf, (int)' ', offst);
	(void)memset(hbuf, (int)' ', offst);
    }

    /*
     * loop by file
     */
    while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
	pagecnt = 0;
	lncnt = 0;

	/*
	 * loop by "form"
	 */
	for(;;) {

	    /*
	     * loop by page
	     */
	    for(;;) {
		linecnt = 0;
		lrgln = 0;
		ops = 0;
		ips = 0;
		cps = 0;

		/*
		 * loop by line
		 */
		while (linecnt < lines) {

		    /*
		     * input next line
		     */
		    rc = inln(inf,lbuf,LBUF,&cnt,&cps,0,&mor);
		    if (cnt >= 0) {
			if (!lrgln)
			    if (!linecnt && prhead(hbuf, fname, ++pagecnt))
			         goto out;

			/*
			 * start new line or continue a long one
			 */
			if (!lrgln) {
			    if (num)
				addnum(nbuf, num, ++lncnt);
			    if (otln(obuf,cnt+off, &ips, &ops, mor))
				goto out;
			} else
			    if (otln(lbuf, cnt, &ips, &ops, mor))
				goto out;

			/*
			 * if line bigger than buffer, get more
			 */
			if (mor) {
			    lrgln = 1;
			} else {
			    /*
			     * whole line rcvd. reset tab proc. state
			     */
			    ++linecnt;
			    lrgln = 0;
			    ops = 0;
			    ips = 0;
			}
		    }

		    if (rc != NORMAL)
			break;
		}

		/*
		 * fill to end of page
		 */
		if (prtail(lines - linecnt, lrgln))
		    goto out;

		/*
		 * unless END continue
		 */
		if (rc == END)
		    break;
	    }

	    /*
	     * On EOF go to next file
	     */
	    if (rc == END)
	    break;
	}

	if (inf != stdin)
	    (void)fclose(inf);
    }
    /*
     * If we didn't process all the files, return error
     */
    if (eoptind < argc) {
	goto out;
    } else {
	error = 0;
	goto out;
    }

oomem:
    mfail();
out:
    free(obuf);
    free(hbuf);
    if (inf != NULL && inf != stdin)
	(void)fclose(inf);
    return error;
}

/*
 * vertcol:	print files with more than one column of output down a page
 *		the general approach is to buffer a page of data, then print
 */
int
vertcol(int argc, char *argv[])
{
    char *ptbf;
    char **lstdat = NULL;
    int i;
    int j;
    int pln;
    int *indy = NULL;
    int cnt;
    int rc;
    int cvc;
    int *lindy = NULL;
    int lncnt;
    int stp;
    int pagecnt;
    int col = colwd + 1;
    int mxlen = pgwd + offst + 1;
    int mclcnt = clcnt - 1;
    struct vcol *vc = NULL;
    int mvc;
    int tvc;
    int cw = nmwd + 1;
    int fullcol;
    char *buf = NULL;
    char *hbuf = NULL;
    char *ohbuf;
    char *fname;
    FILE *inf = NULL;
    int ips = 0;
    int cps = 0;
    int ops = 0;
    int mor = 0;
    int error = 1;

    /*
     * allocate page buffer
     */
    if ((buf = calloc((unsigned)lines, mxlen)) == NULL)
	goto oomem;

    /*
     * allocate page header
     */
    if ((hbuf = malloc((unsigned)HDBUF + offst)) == NULL)
	goto oomem;

    ohbuf = hbuf + offst;
    if (offst)
	(void)memset(hbuf, (int)' ', offst);

    /*
     * col pointers when no headers
     */
    mvc = lines * clcnt;
    if ((vc = calloc((unsigned)mvc, sizeof(struct vcol))) == NULL)
	goto oomem;

    /*
     * pointer into page where last data per line is located
     */
    if ((lstdat = calloc((unsigned)lines, sizeof(char *))) == NULL)
	goto oomem;

    /*
     * fast index lookups to locate start of lines
     */
    if ((indy = calloc((unsigned)lines, sizeof(int))) == NULL)
	goto oomem;
    if ((lindy = calloc((unsigned)lines, sizeof(int))) == NULL)
	goto oomem;

    if (nmwd)
	fullcol = col + cw;
    else
	fullcol = col;

    /*
     * initialize buffer lookup indexes and offset area
     */
    for (j = 0; j < lines; ++j) {
	lindy[j] = j * mxlen;
	indy[j] = lindy[j] + offst;
	if (offst) {
	    ptbf = buf + lindy[j];
	    (void)memset(ptbf, (int)' ', offst);
	    ptbf += offst;
	} else
	    ptbf = buf + indy[j];
	lstdat[j] = ptbf;
    }

    /*
     * loop by file
     */
    while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
	pagecnt = 0;
	lncnt = 0;

	/*
	 * loop by "form"
	 */
	 for (;;) {

	    /*
	     * loop by page
	     */
	    for(;;) {

		/*
		 * loop by column
		 */
		cvc = 0;
		for (i = 0; i < clcnt; ++i) {
		    j = 0;
		    /*
		     * if last column, do not pad
		     */
		    if (i == mclcnt)
			stp = 1;
		    else
			stp = 0;

		    /*
		     * loop by line
		     */
		    for(;;) {
			/*
			 * is this first column
			 */
			if (!i) {
			    ptbf = buf + indy[j];
			    lstdat[j] = ptbf;
			} else 
			    ptbf = lstdat[j];
			vc[cvc].pt = ptbf;

			/*
			 * add number
			 */
			if (nmwd) {
			    addnum(ptbf, nmwd, ++lncnt);
			    ptbf += nmwd;
			    *ptbf++ = nmchar;
			}

			/*
			 * input next line
			 */
			rc = inln(inf,ptbf,colwd,&cnt,&cps,1,&mor);
			vc[cvc++].cnt = cnt;
			if (cnt >= 0) {
			    ptbf += cnt;

			    /*
			     * pad all but last column on page
			     */
			    if (!stp) {
				/*
				 * pad to end of column
				 */
				if (sflag)
				    *ptbf++ = schar;
				else if ((pln = col-cnt) > 0) {
				    (void)memset(ptbf,
					(int)' ',pln);
				    ptbf += pln;
				}
			    }

			    /*
			     * remember last char in line
			     */
			    lstdat[j] = ptbf;
			    if (++j >= lines)
				break;
			} /* end of if cnt >= 0 */

			if (rc != NORMAL)
			    break;
		    } /* end of for line */

		    if (rc != NORMAL)
			break;
		} /* end of for column */

		/*
		 * when -t (no header) is specified the spec requires
		 * the min number of lines. The last page may not have
		 * balanced length columns. To fix this we must reorder
		 * the columns. This is a very slow technique so it is
		 * only used under limited conditions. Without -t, the
		 * balancing of text columns is unspecified. To NOT
		 * balance the last page, add the global variable
		 * nohead to the if statement below e.g.
		 */

		/*
		 * print header iff we got anything on the first read
		 */
		if (vc[0].cnt >= 0) {
		    if (prhead(hbuf, fname, ++pagecnt))
		    	goto out;

		    /*
		     * check to see if "last" page needs to be reordered
		     */
		    --cvc;
		    if ((rc != NORMAL) && cvc && ((mvc-cvc) >= clcnt)){
			pln = cvc/clcnt;
			if (cvc % clcnt)
			    ++pln;

			for (i = 0; i < pln; ++i) {
			    ips = 0;
			    ops = 0;
			    if (offst && otln(buf,offst,&ips,&ops,1))
				goto out;
			    tvc = i;

			    for (j = 0; j < clcnt; ++j) {
				/*
				 * determine column length
				 */
				if (j == mclcnt) {
				    /*
				     * last column
				     */
				    cnt = vc[tvc].cnt;
				    if (nmwd)
					cnt += cw;
				} else if (sflag) {
				    /*
				     * single ch between
				     */
				    cnt = vc[tvc].cnt + 1;
				    if (nmwd)
					cnt += cw;
				} else
				    cnt = fullcol;

				if (otln(vc[tvc].pt, cnt, &ips, &ops, 1))
				    goto out;
				tvc += pln;
				if (tvc > cvc)
				    break;
			    }
			    /*
			     * terminate line
			     */
			    if (otln(buf, 0, &ips, &ops, 0))
				goto out;
			}

		    } else {

			/*
			 * just a normal page...
			 * determine how many lines to output
			 */
			if (i > 0)
			    pln = lines;
			else
			    pln = j;

			/*
			 * output each line
			 */
			for (i = 0; i < pln; ++i) {
			    ptbf = buf + lindy[i];
			    if ((j = lstdat[i] - ptbf) <= offst)
				break;
			    else {
				ips = 0;
				ops = 0;
				if (otln(ptbf, j, &ips, &ops, 0))
				    goto out;
			    }
			}
		    }
		}

		/*
		 * pad to end of page
		 */
		if (prtail((lines - pln), 0))
		    goto out;

		/*
		 * if FORM continue
		 */
		if (rc != NORMAL)
		    break;
	    }

	    /*
	     * if EOF go to next file
	     */
	    if (rc == END)
		break;
	}

	if (inf != stdin)
	    (void)fclose(inf);
    }

    if (eoptind < argc){
	goto out;
    } else {
	error = 0;
	goto out;
    }

oomem:
    mfail();
out:
    free(buf);
    free(hbuf);
    free(vc);
    free(lstdat);
    free(lindy);
    if (inf != NULL && inf != stdin)
	(void)fclose(inf);
    return error;

}

/*
 * horzcol:    print files with more than one column of output across a page
 */
int
horzcol(int argc, char *argv[])
{
    char *ptbf;
    int pln;
    char *lstdat;
    int col = colwd + 1;
    int j;
    int i;
    int cnt;
    int rc;
    int lncnt;
    int pagecnt;
    char *buf = NULL;
    char *hbuf = NULL;
    char *ohbuf;
    char *fname;
    FILE *inf = NULL;
    int cps = 0;
    int mor = 0;
    int ips = 0;
    int ops = 0;
    int error = 1;

    if ((buf = malloc((unsigned)pgwd + offst + 1)) == NULL)
	goto oomem;

    /*
     * page header
     */
    if ((hbuf = malloc((unsigned)HDBUF + offst)) == NULL)
	goto oomem;

    ohbuf = hbuf + offst;
    if (offst) {
	(void)memset(buf, (int)' ', offst);
	(void)memset(hbuf, (int)' ', offst);
    }

    /*
     * loop by file
     */
    while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
	pagecnt = 0;
	lncnt = 0;

	/*
	 * loop by form
	 */
	for (;;) {

	    /*
	     * loop by page
	     */
	    for(;;) {

		/*
		 * loop by line
		 */
		for (i = 0; i < lines; ++i) {
		    ptbf = buf + offst;
		    lstdat = ptbf;
		    j = 0;

		    /*
		     * loop by col
		     */
		    for(;;) {
			if (nmwd) {
			    /*
			     * add number to column
			     */
			    addnum(ptbf, nmwd, ++lncnt);
			    ptbf += nmwd;
			    *ptbf++ = nmchar;
			}
			/*
			 * input line
			 */
			rc = inln(inf,ptbf,colwd,&cnt,&cps,1, &mor);
			if (cnt >= 0) {
			    if (!i && !j && prhead(hbuf, fname, ++pagecnt))
			        goto out;

			    ptbf += cnt;
			    lstdat = ptbf;

			    /*
			     * if last line skip padding
			     */
			    if (++j >= clcnt)
				break;

			    /*
			     * pad to end of column
			     */
			    if (sflag)
				*ptbf++ = schar;
			    else if ((pln = col - cnt) > 0) {
				(void)memset(ptbf,(int)' ',pln);
				ptbf += pln;
			    }
			}
			if (rc != NORMAL)
			    break;
		    }

		    /*
		     * output line if any columns on it
		     */
		    if (j) {
			if (otln(buf, lstdat-buf, &ips, &ops, 0))
			    goto out;
		    }

		    if (rc != NORMAL)
			break;
		}

		/*
		 * pad to end of page
		 */
		if (prtail(lines - i, 0))
		    return(1);

		/*
		 * if FORM continue
		 */
		if (rc == END)
		    break;
	    }
	    /*
	     * if EOF go to next file
	     */
	    if (rc == END)
		break;
	}
	if (inf != stdin)
	    (void)fclose(inf);
    }
    if (eoptind < argc){
	goto out;
    } else {
	error = 0;
	goto out;
    }

oomem:
    mfail();
out:
    free(buf);
    free(hbuf);
    if (inf != NULL && inf != stdin)
	(void)fclose(inf);
    return error;
}

struct ferrlist {
	struct ferrlist *next;
	char *buf;
};
struct ferrlist *ferrhead, *ferrtail;

/*
 * flsh_errs():    output saved up diagnostic messages after all normal
 *        processing has completed
 */
void
flsh_errs(void)
{
    struct ferrlist *f;

    if (ferr) {
	for (f = ferrhead; f; f = f->next)
	    (void)write(STDERR_FILENO, f->buf, strlen(f->buf));
    }
}

static void ferrout(char *fmt, ...) __attribute__((format (printf, 1, 2)));
static void
ferrout(char *fmt, ...)
{
    sigset_t block, oblock;
    struct ferrlist *f;
    va_list ap;
    char *p;

    va_start(ap, fmt);
    if (ferr == 0)
        vfprintf(stderr, fmt, ap);
    else {
	sigemptyset(&block);
	sigaddset(&block, SIGINT);
	sigprocmask(SIG_BLOCK, &block, &oblock);

	if (vasprintf(&p, fmt, ap) == -1 || (f = malloc(sizeof(*f))) == NULL) {
		va_end(ap);
		va_start(ap, fmt);
		flsh_errs();
		vfprintf(stderr, fmt, ap);
		fputs("pr: memory allocation failed\n", stderr);
		exit(1);
	}

	f->next = NULL;
	f->buf = p;
	if (ferrhead == NULL)
	    ferrhead = f;
	if (ferrtail)
		ferrtail->next = f;
	ferrtail = f;
	sigprocmask(SIG_SETMASK, &oblock, NULL);
    }
    va_end(ap);
}

/*
 * mulfile:    print files with more than one column of output and
 *        more than one file concurrently
 */
int
mulfile(int argc, char *argv[])
{
    char *ptbf;
    int j;
    int pln;
    int *rc;
    int cnt;
    char *lstdat;
    int i;
    FILE **fbuf = NULL;
    int actf;
    int lncnt;
    int col;
    int pagecnt;
    int fproc;
    char *buf = NULL;
    char *hbuf = NULL;
    char *ohbuf;
    char *fname;
    int ips = 0;
    int cps = 0;
    int ops = 0;
    int mor = 0;
    int error = 1;

    /*
     * array of FILE *, one for each operand
     */
    if ((fbuf = calloc((unsigned)clcnt, sizeof(FILE *))) == NULL)
	goto oomem;

    /*
     * array of int *, one for each operand
     */
    if ((rc = calloc((unsigned)clcnt, sizeof(int))) == NULL)
	goto oomem;

    /*
     * page header
     */
    if ((hbuf = malloc((unsigned)HDBUF + offst)) == NULL)
	goto oomem;

    ohbuf = hbuf + offst;

    /*
     * do not know how many columns yet. The number of operands provide an
     * upper bound on the number of columns. We use the number of files
     * we can open successfully to set the number of columns. The operation
     * of the merge operation (-m) in relation to unsuccessful file opens
     * is unspecified by posix.
     *
     * XXX - this seems moderately bogus, you'd think that specifying
     * "pr -2 a b c d" would run though all the files in pairs, but
     * the existing code says up two files, or fewer if one is bogus.
     * fixing it would require modifying the looping structure, so be it.
     */
    j = 0;
    while (j < clcnt) {
	if ((fbuf[j] = nxtfile(argc, argv, &fname, ohbuf, 1)) != NULL) {
	    rc[j] = NORMAL;
	    j++;
	}
    }

    /*
     * if no files, exit
     */
    if (j)
	clcnt = j;
    else
	goto out;

    /*
     * calculate page boundaries based on open file count
     */
    if (nmwd) {
	colwd = (pgwd - clcnt - nmwd)/clcnt;
	pgwd = ((colwd + 1) * clcnt) - nmwd - 2;
    } else {
	colwd = (pgwd + 1 - clcnt)/clcnt;
	pgwd = ((colwd + 1) * clcnt) - 1;
    }
    if (colwd < 1) {
	ferrout("pr: page width too small for %d columns\n", clcnt);
	goto out;
    }
    col = colwd + 1;

    /*
     * line buffer
     */
    if ((buf = malloc((unsigned)pgwd + offst + 1)) == NULL)
	goto oomem;

    if (offst) {
	(void)memset(buf, (int)' ', offst);
	(void)memset(hbuf, (int)' ', offst);
    }

    pagecnt = 0;
    lncnt = 0;
    actf = clcnt;

    /*
     * continue to loop while any file still has data
     */
    while (actf > 0) {

	/*
	 * loop on "form"
	 */
	for (;;) {

	    /*
	     * loop by line
	     */
	    for (i = 0; i < lines; ++i) {
		ptbf = buf + offst;
		lstdat = ptbf;
		if (nmwd) {
		    /*
		     * add line number to line
		     */
		    addnum(ptbf, nmwd, ++lncnt);
		    ptbf += nmwd;
		    *ptbf++ = nmchar;
		}

		fproc = 0;
		/*
		 * loop by column
		 */
		for (j = 0; j < clcnt; ++j) {
		    if (rc[j] == NORMAL ) {
			rc[j] = inln(fbuf[j], ptbf, colwd, &cnt, &cps, 1, &mor);
			if (cnt >= 0) {
			    /*
			     * process file data
			     */
			    ptbf += cnt;
			    lstdat = ptbf;
			    fproc++;
			} else
			    cnt = 0;
			
			if (rc[j] == END) {
			    /*
			     * EOF close file
			     */
			    if (fbuf[j] != stdin)
				(void)fclose(fbuf[j]);
			    --actf;
			}
		    } else
			cnt = 0;

		    /*
		     * if last ACTIVE column, done with line
		     */
		    if (fproc >= actf)
			break;

		    /*
		     * pad to end of column
		     */
		    if (sflag) {
			*ptbf++ = schar;
		    } else {
			if (cnt >= 0)
			    pln = col - cnt;
			else
			    pln = col;
			if (pln > 0) {
			    (void)memset(ptbf, (int)' ', pln);
			    ptbf += pln;
			}
		    }
		}

		/*
		 * if there was anything to do, print it
		 */
		if (fproc != 0) {
		    if (!i && prhead(hbuf, fname, ++pagecnt))
			goto out;

		    /*
		     * output line
		     */
		    if (otln(buf, lstdat-buf, &ips, &ops, 0))
			goto out;
		} else
		    break;
	    }

	    /*
	     * pad to end of page
	     */
	    if (prtail(lines - i, 0))
		return(1);

	    for (j = 0; j < clcnt; ++j)
		if (rc[j] != END)
		    rc[j] = NORMAL;

	    if (actf <= 0)
		break;
	}
	if (actf <= 0)
	break;
    }
    if (eoptind < argc){
	goto out;
    } else {
	error = 0;
	goto out;
    }

oomem:
	mfail();
out:
    if (fbuf) {
	for (j = 0; j < clcnt; j++) {
	    if (fbuf[j] && fbuf[j] != stdin)
		(void)fclose(fbuf[j]);
	}
	free(fbuf);
    }
    free(hbuf);
    free(buf);
    return error;
}

/*
 * inln():    input a line of data (unlimited length lines supported)
 *        Input is optionally expanded to spaces
 *        Returns 0 if normal LF, FORM on Formfeed, and END on EOF
 *
 *    inf:    file
 *    buf:    buffer
 *    lim:    buffer length
 *    cnt:    line length or -1 if no line (EOF for example)
 *    cps:    column position 1st char in buffer (large line support)
 *    trnc:    throw away data more than lim up to \n 
 *    mor:    set if more data in line (not truncated)
 */
int
inln(FILE *inf, char *buf, int lim, int *cnt, int *cps, int trnc, int *mor)
{
    int col;
    int gap = ingap;
    int ch = -1;
    char *ptbuf;
    int chk = (int)inchar;

    ptbuf = buf;

    if (gap) {
	/*
	 * expanding input option
	 */
	while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
	    /*
	     * is this the input "tab" char
	     */
	    if (ch == chk) {
		/*
		 * expand to number of spaces
		 */
		col = (ptbuf - buf) + *cps;
		col = gap - (col % gap);

		/*
		 * if more than this line, push back
		 */
		if ((col > lim) && (ungetc(ch, inf) == EOF)) {
		    *cnt = -1;
		    return(END);    /* shouldn't happen */
		}

		/*
		 * expand to spaces
		 */
		while ((--col >= 0) && (--lim >= 0))
		    *ptbuf++ = ' ';
		continue;
	    }
	    if (ch == '\n' || (inform && ch == INFF))
		break;
	    *ptbuf++ = ch;
	}
    } else {
	/*
	 * no expansion
	 */
	while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
	    if (ch == '\n' || (inform && ch == INFF))
		break;
	    *ptbuf++ = ch;
	}
    }
    col = ptbuf - buf;
    if (ch == EOF) {
	*mor = 0;
	*cps = 0;
	*cnt = col ? col : -1;
	return(END);
    }
    if (inform && ch == INFF) {
	*mor = 0;
	*cps = 0;
	*cnt = col;
	return(FORM);
    }
    if (ch == '\n') {
	/*
	 * entire line processed
	 */
	*mor = 0;
	*cps = 0;
	*cnt = col;
	return(NORMAL);
    }

    /*
     * line was larger than limit
     */
    if (trnc) {
	/*
	 * throw away rest of line
	 */
	while ((ch = getc(inf)) != EOF) {
	    if (ch == '\n')
		break;
	}
	*cps = 0;
	*mor = 0;
    } else {
	/*
	 * save column offset if not truncated
	 */
	*cps += col;
	*mor = 1;
    }

    *cnt = col;
    return(NORMAL);
}

/*
 * otln():    output a line of data. (Supports unlimited length lines)
 *        output is optionally contracted to tabs
 *
 *    buf:    output buffer with data
 *    cnt:    number of chars of valid data in buf
 *    svips:    buffer input column position (for large lines)
 *    svops:    buffer output column position (for large lines)
 *    mor:    output line not complete in this buf; more data to come.    
 *        1 is more, 0 is complete, -1 is no \n's
 */
int
otln(char *buf, int cnt, int *svips, int *svops, int mor)
{
    int ops;        /* last col output */
    int ips;        /* last col in buf examined */
    int gap = ogap;
    int tbps;
    char *endbuf;

    /* skipping is only changed at header time not mid-line! */
    if (skipping)
	return (0);

    if (ogap) {
	/*
	 * contracting on output
	 */
	endbuf = buf + cnt;
	ops = *svops;
	ips = *svips;
	while (buf < endbuf) {
	    /*
	     * count number of spaces and ochar in buffer
	     */
	    if (*buf == ' ') {
		++ips;
		++buf;
		continue;
	    }

	    /*
	     * simulate ochar processing
	     */
	    if (*buf == ochar) {
		ips += gap - (ips % gap);
		++buf;
		continue;
	    }

	    /*
	     * got a non space char; contract out spaces
	     */
	    while (ops < ips) {
		/*
		 * use one space if necessary
		 */
		if (ips - ops == 1) {
			putchar(' ');
			break;
		}
		/*
		 * use as many ochar as will fit
		 */
		if ((tbps = ops + gap - (ops % gap)) > ips)
		    break;
		if (putchar(ochar) == EOF) {
		    pfail();
		    return(1);
		}
		ops = tbps;
	    }

	    while (ops < ips) {
		/*
		 * finish off with spaces
		 */
		if (putchar(' ') == EOF) {
		    pfail();
		    return(1);
		}
		++ops;
	    }

	    /*
	     * output non space char
	     */
	    if (putchar(*buf++) == EOF) {
		pfail();
		return(1);
	    }
	    ++ips;
	    ++ops;
	}

	if (mor > 0) {
	    /*
	     * if incomplete line, save position counts
	     */
	    *svops = ops;
	    *svips = ips;
	    return(0);
	}

	if (mor < 0) {
	    while (ops < ips) {
		/*
		 * use one space if necessary
		 */
		if (ips - ops == 1) {
			putchar(' ');
			break;
		}
		/*
		 * use as many ochar as will fit
		 */
		if ((tbps = ops + gap - (ops % gap)) > ips)
		    break;
		if (putchar(ochar) == EOF) {
		    pfail();
		    return(1);
		}
		ops = tbps;
	    }

	    while (ops < ips) {
		/*
		 * finish off with spaces
		 */
		if (putchar(' ') == EOF) {
		    pfail();
		    return(1);
		}
		++ops;
	    }
	    return(0);
	}
    } else {
	/*
	 * output is not contracted
	 */
	if (cnt && (fwrite(buf, sizeof(char), cnt, stdout) < cnt)) {
	    pfail();
	    return(1);
	}
	if (mor != 0)
	    return(0);
    }

    /*
     * process line end and double space as required
     */
    if ((putchar('\n') == EOF) || (dspace && (putchar('\n') == EOF))) {
	pfail();
	return(1);
    }
    return(0);
}

#ifdef notused
/*
 * inskip():    skip over pgcnt pages with lncnt lines per page
 *        file is closed at EOF (if not stdin).
 *
 *    inf    FILE * to read from
 *    pgcnt    number of pages to skip
 *    lncnt    number of lines per page
 */
int
inskip(FILE *inf, int pgcnt, int lncnt)
{
    int c;
    int cnt;

    while(--pgcnt > 0) {
	cnt = lncnt;
	while ((c = getc(inf)) != EOF) {
	    if ((c == '\n') && (--cnt == 0))
		break;
	}
	if (c == EOF) {
	    if (inf != stdin)
		(void)fclose(inf);
	    return(1);
	}
    }
    return(0);
}
#endif

/*
 * nxtfile:    returns a FILE * to next file in arg list and sets the
 *        time field for this file (or current date).
 *
 *    buf    array to store proper date for the header.
 *    dt    if set skips the date processing (used with -m)
 */
FILE *
nxtfile(int argc, char *argv[], char **fname, char *buf, int dt)
{
    FILE *inf = NULL;
    struct tm *timeptr = NULL;
    struct stat statbuf;
    time_t curtime;
    static int twice = -1;

    ++twice;
    if (eoptind >= argc) {
	/*
	 * no file listed; default, use standard input
	 */
	if (twice)
	    return(NULL);
	clearerr(stdin);
	inf = stdin;
	if (header != NULL)
	    *fname = header;
	else
	    *fname = FNAME;
	if (nohead)
	    return(inf);
	curtime = time(NULL);;
	timeptr = localtime(&curtime);
    }
    for (; eoptind < argc; ++eoptind) {
	if (strcmp(argv[eoptind], "-") == 0) {
	    /*
	     * process a "-" for filename
	     */
	    clearerr(stdin);
	    inf = stdin;
	    if (header != NULL)
		*fname = header;
	    else
		*fname = FNAME;
	    ++eoptind;
	    if (nohead || (dt && twice))
		return(inf);
	    curtime = time(NULL);
	    timeptr = localtime(&curtime);
	} else {
	    /*
	     * normal file processing
	     */
	    if ((inf = fopen(argv[eoptind], "r")) == NULL) {
		++errcnt;
		if (nodiag)
		    continue;
		ferrout("pr: Cannot open %s, %s\n",
		    argv[eoptind], strerror(errno));
		continue;
	    }
	    if (header != NULL)
		*fname = header;
	    else if (dt)
		*fname = FNAME;
	    else
		*fname = argv[eoptind];
	    ++eoptind;
	    if (nohead || (dt && twice))
		return(inf);

	    if (dt) {
		curtime = time(NULL);
		timeptr = localtime(&curtime);
	    } else {
		if (fstat(fileno(inf), &statbuf) < 0) {
		    ++errcnt;
		    (void)fclose(inf);
		    ferrout("pr: Cannot stat %s, %s\n",
			argv[eoptind], strerror(errno));
		    return(NULL);
		}
		timeptr = localtime(&(statbuf.st_mtime));
	    }
	}
	break;
    }
    if (inf == NULL)
	return(NULL);

    /*
     * set up time field used in header
     */
    if (strftime(buf, HDBUF, TIMEFMT, timeptr) == 0) {
	++errcnt;
	if (inf != stdin)
	    (void)fclose(inf);
	ferrout("pr: time conversion failed\n");
	return(NULL);
    }
    return(inf);
}

/*
 * addnum():    adds the line number to the column
 *        Truncates from the front or pads with spaces as required.
 *        Numbers are right justified.
 *
 *    buf    buffer to store the number
 *    wdth    width of buffer to fill
 *    line    line number
 *
 *        NOTE: numbers occupy part of the column. The posix
 *        spec does not specify if -i processing should or should not
 *        occur on number padding. The spec does say it occupies
 *        part of the column. The usage of addnum    currently treats
 *        numbers as part of the column so spaces may be replaced.
 */
void
addnum(char *buf, int wdth, int line)
{
    char *pt = buf + wdth;

    do {
	*--pt = digs[line % 10];
	line /= 10;
    } while (line && (pt > buf));

    /*
     * pad with space as required
     */
    while (pt > buf)
	*--pt = ' ';
}

/*
 * prhead():    prints the top of page header
 *
 *    buf    buffer with time field (and offset)
 *    cnt    number of chars in buf
 *    fname    fname field for header
 *    pagcnt    page number
 *
 * prhead() should be used carefully, we don't want to print out headers
 * for null input files or orphan headers at the end of files, and also
 * trailer processing is typically conditional on whether you've called
 * prhead() at least once for a file and incremented pagecnt.  Exactly
 * how to determine whether to print a header is a little different in
 * the context each output mode, but we let the caller figure that out.
 */
int
prhead(char *buf, char *fname, int pagcnt)
{
    int ips = 0;
    int ops = 0;

    beheaded = 1;

    if (skipping && pagcnt >= pgnm)
	skipping = 0;

    if (nohead || skipping)
	return (0);

    if ((putchar('\n') == EOF) || (putchar('\n') == EOF)) {
	pfail();
	return(1);
    }
    /*
     * posix is not clear if the header is subject to line length
     * restrictions. The specification for header line format
     * in the spec clearly does not limit length. No pr currently
     * restricts header length. However if we need to truncate in
     * an reasonable way, adjust the length of the printf by
     * changing HDFMT to allow a length max as an argument printf.
     * buf (which contains the offset spaces and time field could
     * also be trimmed
     *
     * note only the offset (if any) is processed for tab expansion
     */
    if (offst && otln(buf, offst, &ips, &ops, -1))
	return(1);
    (void)printf(HDFMT,buf+offst, fname, pagcnt);
    return(0);
}

/*
 * prtail():    pad page with empty lines (if required) and print page trailer
 *        if requested
 *
 *    cnt    	number of lines of padding needed
 *    incomp    was a '\n' missing from last line output
 *
 * prtail() can now be invoked unconditionally, with the notion that if
 * we haven't printed a header, there is no need for a trailer
 */
int
prtail(int cnt, int incomp)
{
    /*
     * if were's skipping to page N or haven't put out anything yet just exit
     */
    if (skipping || beheaded == 0)
	return (0);
    beheaded = 0;

    /*
     * if noheaders, only terminate an incomplete last line
     */
    if (nohead) {

	if (incomp) {
	    if (dspace)
		if (putchar('\n') == EOF) {
		    pfail();
		    return(1);
		}
	    if (putchar('\n') == EOF) {
		pfail();
		return(1);
	     }
	}
	/*
	 * but honor the formfeed request
	 */
	if (formfeed)
	    if (putchar(OUTFF) == EOF) {
		pfail();
		return(1);
	    }

    } else {

	/*
	 * if double space output two \n
	 *
  	 * XXX this all seems bogus, why are we doing it here???
	 * page length is in terms of output lines and only the input is
	 * supposed to be double spaced...  otln() users should be doing
	 * something like linect+=(dspace ? 2:1).
	 */
	if (dspace)
	    cnt *= 2;

	/*
	 * if an odd number of lines per page, add an extra \n
	 */
	if (addone)
	    ++cnt;

	/*
	 * either put out a form-feed or pad page with blanks
	 */
	if (formfeed) {
	    if (incomp)
		if (putchar('\n') == EOF) {
		    pfail();
		    return(1);
		}
	    if (putchar(OUTFF) == EOF) {
		    pfail();
		    return(1);
	    }

	} else {

	    if (incomp)
		cnt++;

	    cnt += TAILLEN;
	    while (--cnt >= 0) {
		if (putchar('\n') == EOF) {
		    pfail();
		    return(1);
		}
	    }
	}
    }

    return(0);
}

/*
 * terminate():    when a SIGINT is recvd
 */
/*ARGSUSED*/
void
terminate(int which_sig)
{
    flsh_errs();
    _exit(1);
}

void
mfail(void)
{
    ferrout("pr: memory allocation failed\n");
}

void
pfail(void)
{
    ferrout("pr: write failure, %s\n", strerror(errno));
}

void
usage(void)
{
    ferrout(
     "usage: pr [+page] [-column] [-adFfmrt] [-e[char][gap]] [-h header]\n");
    ferrout(
     "\t[-i[char][gap]] [-l lines] [-n[char][width]] [-o offset] [-s[char]]\n");
    ferrout(
     "\t[-w width] [file ...]\n");
}

/*
 * setup:    Validate command args, initialize and perform sanity 
 *        checks on options
 */
int
setup(int argc, char *argv[])
{
    int c;
    int eflag = 0;
    int iflag = 0;
    int wflag = 0;
    int cflag = 0;
    const char *errstr;

    if (isatty(fileno(stdout)))
	ferr = 1;

    while ((c = egetopt(argc, argv, "#adfFmrte?h:i?l:n?o:s?w:")) != -1) {
	switch (c) {
	case '+':
	    pgnm = strtonum(eoptarg, 1, INT_MAX, &errstr);
	    if (errstr) {
		ferrout("pr: +page number is %s: %s\n", errstr, eoptarg);
		return(1);
	    }
	    skipping = 1;
	    break;
	case '-':
	    clcnt = strtonum(eoptarg, 1, INT_MAX, &errstr);
	    if (errstr) {
		ferrout("pr: -columns number is %s: %s\n", errstr, eoptarg);
		return(1);
	    }
	    if (clcnt > 1)
		cflag = 1;
	    break;
	case 'a':
	    across = 1;
	    break;
	case 'd':
	    dspace = 1;
	    break;
	case 'e':
	    eflag = 1;
	    if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
		inchar = *eoptarg++;
	    else
		inchar = INCHAR;
	    if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
		ingap = strtonum(eoptarg, 0, INT_MAX, &errstr);
		if (errstr) {
		    ferrout("pr: -e gap is %s: %s\n", errstr, eoptarg);
		    return(1);
		}
		if (ingap == 0)
		    ingap = INGAP;
	    } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
		ferrout("pr: invalid value for -e %s\n", eoptarg);
		return(1);
	    } else
		ingap = INGAP;
	    break;
	case 'f':
	case 'F':
	    formfeed = 1;
	    break;
	case 'h':
	    header = eoptarg;
	    break;
	case 'i':
	    iflag = 1;
	    if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
		ochar = *eoptarg++;
	    else
		ochar = OCHAR;
	    if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
		ogap = strtonum(eoptarg, 0, INT_MAX, &errstr);
		if (errstr) {
		    ferrout("pr: -i gap is %s: %s\n", errstr, eoptarg);
		    return(1);
		}
		if (ogap == 0)
		    ogap = OGAP;
	    } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
		ferrout("pr: invalid value for -i %s\n", eoptarg);
		return(1);
	    } else
		ogap = OGAP;
	    break;
	case 'l':
	    lines = strtonum(eoptarg, 1, INT_MAX, &errstr);
	    if (errstr) {
		ferrout("pr: number of lines is %s: %s\n", errstr, eoptarg);
		return(1);
	    }
	    break;
	case 'm':
	    merge = 1;
	    break;
	case 'n':
	    if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
		nmchar = *eoptarg++;
	    else
		nmchar = NMCHAR;
	    if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
		nmwd = strtonum(eoptarg, 1, INT_MAX, &errstr);
		if (errstr) {
		    ferrout("pr: -n width is %s: %s\n", errstr, eoptarg);
		    return(1);
		}
	    } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
		ferrout("pr: invalid value for -n %s\n", eoptarg);
		return(1);
	    } else
		nmwd = NMWD;
	    break;
	case 'o':
	    offst = strtonum(eoptarg, 1, INT_MAX, &errstr);
	    if (errstr) {
		ferrout("pr: -o offset is %s: %s\n", errstr, eoptarg);
		return(1);
	    }
	    break;
	case 'r':
	    nodiag = 1;
	    break;
	case 's':
	    sflag = 1;
	    if (eoptarg == NULL)
		schar = SCHAR;
	    else {
		schar = *eoptarg++;
		if (*eoptarg != '\0') {
		    ferrout("pr: invalid value for -s %s\n", eoptarg);
		    return(1);
		}
	    }
	    break;
	case 't':
	    nohead = 1;
	    break;
	case 'w':
	    wflag = 1;
	    pgwd = strtonum(eoptarg, 1, INT_MAX, &errstr);
	    if (errstr) {
		ferrout("pr: -w width is %s: %s\n", errstr, eoptarg);
		return(1);
	    }
	    break;
	default:
	    return(1);
	}
    }

    /*
     * default and sanity checks
     */
    inform++;

    if (!clcnt) {
	if (merge) {
	    if ((clcnt = argc - eoptind) <= 1) {
		clcnt = CLCNT;
#ifdef stupid
		merge = 0;
#endif
	    }
	} else
	    clcnt = CLCNT;
    }
    if (across) {
	if (clcnt == 1) {
	    ferrout("pr: -a flag requires multiple columns\n");
	    return(1);
	}
	if (merge) {
	    ferrout("pr: -m cannot be used with -a\n");
	    return(1);
	}
    }
    if (!wflag) {
	if (sflag)
	    pgwd = SPGWD;
	else
	    pgwd = PGWD;
    }
    if (cflag || merge) {
	if (!eflag) {
	    inchar = INCHAR;
	    ingap = INGAP;
	}
	if (!iflag) {
	    ochar = OCHAR;
	    ogap = OGAP;
	}
    }
    if (cflag) {
	if (merge) {
	    ferrout("pr: -m cannot be used with multiple columns\n");
	    return(1);
	}
	if (nmwd) {
	    colwd = (pgwd + 1 - (clcnt * (nmwd + 2)))/clcnt;
	    pgwd = ((colwd + nmwd + 2) * clcnt) - 1;
	} else {
	    colwd = (pgwd + 1 - clcnt)/clcnt;
	    pgwd = ((colwd + 1) * clcnt) - 1;
	}
	if (colwd < 1) {
	    ferrout("pr: page width is too small for %d columns\n",clcnt);
	    return(1);
	}
    }
    if (!lines)
	lines = LINES;

    /*
     * make sure long enough for headers. if not disable
     */
    if (lines <= HEADLEN + TAILLEN)
	nohead = 1;
    else if (!nohead)
	lines -= HEADLEN + TAILLEN;

    /*
     * adjust for double space on odd length pages
     */
    if (dspace) {
	if (lines == 1)
	    dspace = 0;
	else {
	    if (lines & 1)
		++addone;
	    lines /= 2;
	}
    }

    return(0);
}