xref: /openbsd-src/usr.bin/rs/rs.c (revision a4afd6dad3fba28f80e70208181c06c482259988)
1 /*	$OpenBSD: rs.c,v 1.3 1996/06/26 05:38:47 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 static char copyright[] =
38 "@(#) Copyright (c) 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 static char sccsid[] = "@(#)rs.c	8.1 (Berkeley) 6/6/93";
44 #endif /* not lint */
45 
46 /*
47  *	rs - reshape a data array
48  *	Author:  John Kunze, Office of Comp. Affairs, UCB
49  *		BEWARE: lots of unfinished edges
50  */
51 
52 #include <ctype.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 
57 long	flags;
58 #define	TRANSPOSE	000001
59 #define	MTRANSPOSE	000002
60 #define	ONEPERLINE	000004
61 #define	ONEISEPONLY	000010
62 #define	ONEOSEPONLY	000020
63 #define	NOTRIMENDCOL	000040
64 #define	SQUEEZE		000100
65 #define	SHAPEONLY	000200
66 #define	DETAILSHAPE	000400
67 #define	RIGHTADJUST	001000
68 #define	NULLPAD		002000
69 #define	RECYCLE		004000
70 #define	SKIPPRINT	010000
71 #define	ICOLBOUNDS	020000
72 #define	OCOLBOUNDS	040000
73 #define ONEPERCHAR	0100000
74 #define NOARGS		0200000
75 
76 short	*colwidths;
77 short	*cord;
78 short	*icbd;
79 short	*ocbd;
80 int	nelem;
81 char	**elem;
82 char	**endelem;
83 char	*curline;
84 int	allocsize = BUFSIZ;
85 int	curlen;
86 int	irows, icols;
87 int	orows, ocols;
88 int	maxlen;
89 int	skip;
90 int	propgutter;
91 char	isep = ' ', osep = ' ';
92 int	owidth = 80, gutter = 2;
93 
94 void	  usage __P((char *, char *));
95 void	  getargs __P((int, char *[]));
96 void	  getfile __P((void));
97 int	  getline __P((void));
98 char	 *getlist __P((short **, char *));
99 char	 *getnum __P((int *, char *, int));
100 char	**getptrs __P((char **));
101 void	  prepfile __P((void));
102 void	  prints __P((char *, int));
103 void	  putfile __P((void));
104 
105 #define INCR(ep) do {			\
106 	if (++ep >= endelem)		\
107 		ep = getptrs(ep);	\
108 } while(0)
109 
110 int
111 main(argc, argv)
112 	int argc;
113 	char *argv[];
114 {
115 	getargs(argc, argv);
116 	getfile();
117 	if (flags & SHAPEONLY) {
118 		printf("%d %d\n", irows, icols);
119 		exit(0);
120 	}
121 	prepfile();
122 	putfile();
123 	exit(0);
124 }
125 
126 void
127 getfile()
128 {
129 	register char *p;
130 	register char *endp;
131 	register char **ep = 0;
132 	int multisep = (flags & ONEISEPONLY ? 0 : 1);
133 	int nullpad = flags & NULLPAD;
134 	char **padto;
135 
136 	while (skip--) {
137 		getline();
138 		if (flags & SKIPPRINT)
139 			puts(curline);
140 	}
141 	getline();
142 	if (flags & NOARGS && curlen < owidth)
143 		flags |= ONEPERLINE;
144 	if (flags & ONEPERLINE)
145 		icols = 1;
146 	else				/* count cols on first line */
147 		for (p = curline, endp = curline + curlen; p < endp; p++) {
148 			if (*p == isep && multisep)
149 				continue;
150 			icols++;
151 			while (*p && *p != isep)
152 				p++;
153 		}
154 	ep = getptrs(elem);
155 	p = curline;
156 	do {
157 		if (flags & ONEPERLINE) {
158 			*ep = curline;
159 			INCR(ep);		/* prepare for next entry */
160 			if (maxlen < curlen)
161 				maxlen = curlen;
162 			irows++;
163 			continue;
164 		}
165 		for (p = curline, endp = curline + curlen; p < endp; p++) {
166 			if (*p == isep && multisep)
167 				continue;	/* eat up column separators */
168 			if (*p == isep)		/* must be an empty column */
169 				*ep = "";
170 			else			/* store column entry */
171 				*ep = p;
172 			while (p < endp && *p != isep)
173 				p++;		/* find end of entry */
174 			*p = '\0';		/* mark end of entry */
175 			if (maxlen < p - *ep)	/* update maxlen */
176 				maxlen = p - *ep;
177 			INCR(ep);		/* prepare for next entry */
178 		}
179 		irows++;			/* update row count */
180 		if (nullpad) {			/* pad missing entries */
181 			padto = elem + irows * icols;
182 			while (ep < padto) {
183 				*ep = "";
184 				INCR(ep);
185 			}
186 		}
187 	} while (getline() != EOF);
188 	*ep = 0;				/* mark end of pointers */
189 	nelem = ep - elem;
190 }
191 
192 void
193 putfile()
194 {
195 	register char **ep;
196 	register int i, j, n;
197 
198 	ep = elem;
199 	if (flags & TRANSPOSE) {
200 		for (i = 0; i < orows; i++) {
201 			for (j = i; j < nelem; j += orows)
202 				prints(ep[j], (j - i) / orows);
203 			putchar('\n');
204 		}
205 	} else {
206 		for (n = 0, i = 0; i < orows && n < nelem; i++) {
207 			for (j = 0; j < ocols; j++) {
208 				if (n++ >= nelem)
209 					break;
210 				prints(*ep++, j);
211 			}
212 			putchar('\n');
213 		}
214 	}
215 }
216 
217 void
218 prints(s, col)
219 	char *s;
220 	int col;
221 {
222 	register int n;
223 	register char *p = s;
224 
225 	while (*p)
226 		p++;
227 	n = (flags & ONEOSEPONLY ? 1 : colwidths[col] - (p - s));
228 	if (flags & RIGHTADJUST)
229 		while (n-- > 0)
230 			putchar(osep);
231 	for (p = s; *p; p++)
232 		putchar(*p);
233 	while (n-- > 0)
234 		putchar(osep);
235 }
236 
237 void
238 usage(msg, s)
239 	char *msg, *s;
240 {
241 	warnx(msg, s);
242 	fprintf(stderr,
243 "Usage:  rs [ -[csCS][x][kKgGw][N]tTeEnyjhHm ] [ rows [ cols ] ]\n");
244 	exit(1);
245 }
246 
247 void
248 prepfile()
249 {
250 	register char **ep;
251 	register int  i;
252 	register int  j;
253 	char **lp;
254 	int colw;
255 	int max = 0;
256 	int n;
257 
258 	if (!nelem)
259 		exit(0);
260 	gutter += maxlen * propgutter / 100.0;
261 	colw = maxlen + gutter;
262 	if (flags & MTRANSPOSE) {
263 		orows = icols;
264 		ocols = irows;
265 	}
266 	else if (orows == 0 && ocols == 0) {	/* decide rows and cols */
267 		ocols = owidth / colw;
268 		if (ocols == 0) {
269 			warnx("Display width %d is less than column width %d\n", owidth, colw);
270 			ocols = 1;
271 		}
272 		if (ocols > nelem)
273 			ocols = nelem;
274 		orows = nelem / ocols + (nelem % ocols ? 1 : 0);
275 	}
276 	else if (orows == 0)			/* decide on rows */
277 		orows = nelem / ocols + (nelem % ocols ? 1 : 0);
278 	else if (ocols == 0)			/* decide on cols */
279 		ocols = nelem / orows + (nelem % orows ? 1 : 0);
280 	lp = elem + orows * ocols;
281 	while (lp > endelem) {
282 		getptrs(elem + nelem);
283 		lp = elem + orows * ocols;
284 	}
285 	if (flags & RECYCLE) {
286 		for (ep = elem + nelem; ep < lp; ep++)
287 			*ep = *(ep - nelem);
288 		nelem = lp - elem;
289 	}
290 	if (!(colwidths = (short *) malloc(ocols * sizeof(short))))
291 		errx(1, "malloc:  No gutter space");
292 	if (flags & SQUEEZE) {
293 		if (flags & TRANSPOSE)
294 			for (ep = elem, i = 0; i < ocols; i++) {
295 				for (j = 0; j < orows; j++)
296 					if ((n = strlen(*ep++)) > max)
297 						max = n;
298 				colwidths[i] = max + gutter;
299 			}
300 		else
301 			for (i = 0; i < ocols; i++) {
302 				for (j = i; j < nelem; j += ocols)
303 					if ((n = strlen(ep[j])) > max)
304 						max = n;
305 				colwidths[i] = max + gutter;
306 			}
307 	}
308 	/*	for (i = 0; i < orows; i++) {
309 			for (j = i; j < nelem; j += orows)
310 				prints(ep[j], (j - i) / orows);
311 			putchar('\n');
312 		}
313 	else
314 		for (i = 0; i < orows; i++) {
315 			for (j = 0; j < ocols; j++)
316 				prints(*ep++, j);
317 			putchar('\n');
318 		}*/
319 	else
320 		for (i = 0; i < ocols; i++)
321 			colwidths[i] = colw;
322 	if (!(flags & NOTRIMENDCOL)) {
323 		if (flags & RIGHTADJUST)
324 			colwidths[0] -= gutter;
325 		else
326 			colwidths[ocols - 1] = 0;
327 	}
328 	n = orows * ocols;
329 	if (n > nelem && (flags & RECYCLE))
330 		nelem = n;
331 	/*for (i = 0; i < ocols; i++)
332 		fprintf(stderr, "%d ",colwidths[i]);
333 	fprintf(stderr, "is colwidths, nelem %d\n", nelem);*/
334 }
335 
336 #define	BSIZE	2048
337 char	ibuf[BSIZE];		/* two screenfuls should do */
338 
339 int
340 getline()	/* get line; maintain curline, curlen; manage storage */
341 {
342 	static	int putlength;
343 	static	char *endblock = ibuf + BSIZE;
344 	register char *p;
345 	register int c, i;
346 
347 	if (!irows) {
348 		curline = ibuf;
349 		putlength = flags & DETAILSHAPE;
350 	}
351 	else if (skip <= 0) {			/* don't waste storage */
352 		curline += curlen + 1;
353 		if (putlength)		/* print length, recycle storage */
354 			printf(" %d line %d\n", curlen, irows);
355 	}
356 	if (!putlength && endblock - curline < BUFSIZ) {   /* need storage */
357 		/*ww = endblock-curline; tt += ww;*/
358 		/*printf("#wasted %d total %d\n",ww,tt);*/
359 		if (!(curline = (char *) malloc(BSIZE)))
360 			errx(1, "File too large");
361 		endblock = curline + BSIZE;
362 		/*printf("#endb %d curline %d\n",endblock,curline);*/
363 	}
364 	for (p = curline, i = 1; i < BUFSIZ; *p++ = c, i++)
365 		if ((c = getchar()) == EOF || c == '\n')
366 			break;
367 	*p = '\0';
368 	curlen = i - 1;
369 	return(c);
370 }
371 
372 char **
373 getptrs(sp)
374 	char **sp;
375 {
376 	register char **p;
377 
378 	allocsize += allocsize;
379 	p = (char **)realloc(elem, allocsize * sizeof(char *));
380 	if (p == (char **)0)
381 		err(1, "no memory");
382 
383 	sp += (p - elem);
384 	endelem = (elem = p) + allocsize;
385 	return(sp);
386 }
387 
388 void
389 getargs(ac, av)
390 	int ac;
391 	char *av[];
392 {
393 	register char *p;
394 
395 	if (ac == 1) {
396 		flags |= NOARGS | TRANSPOSE;
397 	}
398 	while (--ac && **++av == '-')
399 		for (p = *av+1; *p; p++)
400 			switch (*p) {
401 			case 'T':
402 				flags |= MTRANSPOSE;
403 			case 't':
404 				flags |= TRANSPOSE;
405 				break;
406 			case 'c':		/* input col. separator */
407 				flags |= ONEISEPONLY;
408 			case 's':		/* one or more allowed */
409 				if (p[1])
410 					isep = *++p;
411 				else
412 					isep = '\t';	/* default is ^I */
413 				break;
414 			case 'C':
415 				flags |= ONEOSEPONLY;
416 			case 'S':
417 				if (p[1])
418 					osep = *++p;
419 				else
420 					osep = '\t';	/* default is ^I */
421 				break;
422 			case 'w':		/* window width, default 80 */
423 				p = getnum(&owidth, p, 0);
424 				if (owidth <= 0)
425 				usage("Width must be a positive integer", "");
426 				break;
427 			case 'K':			/* skip N lines */
428 				flags |= SKIPPRINT;
429 			case 'k':			/* skip, do not print */
430 				p = getnum(&skip, p, 0);
431 				if (!skip)
432 					skip = 1;
433 				break;
434 			case 'm':
435 				flags |= NOTRIMENDCOL;
436 				break;
437 			case 'g':		/* gutter space */
438 				p = getnum(&gutter, p, 0);
439 				break;
440 			case 'G':
441 				p = getnum(&propgutter, p, 0);
442 				break;
443 			case 'e':		/* each line is an entry */
444 				flags |= ONEPERLINE;
445 				break;
446 			case 'E':
447 				flags |= ONEPERCHAR;
448 				break;
449 			case 'j':			/* right adjust */
450 				flags |= RIGHTADJUST;
451 				break;
452 			case 'n':	/* null padding for missing values */
453 				flags |= NULLPAD;
454 				break;
455 			case 'y':
456 				flags |= RECYCLE;
457 				break;
458 			case 'H':			/* print shape only */
459 				flags |= DETAILSHAPE;
460 			case 'h':
461 				flags |= SHAPEONLY;
462 				break;
463 			case 'z':			/* squeeze col width */
464 				flags |= SQUEEZE;
465 				break;
466 			/*case 'p':
467 				ipagespace = atoi(++p);	(default is 1)
468 				break;*/
469 			case 'o':			/* col order */
470 				p = getlist(&cord, p);
471 				break;
472 			case 'b':
473 				flags |= ICOLBOUNDS;
474 				p = getlist(&icbd, p);
475 				break;
476 			case 'B':
477 				flags |= OCOLBOUNDS;
478 				p = getlist(&ocbd, p);
479 				break;
480 			default:
481 				usage("Bad flag:  %.1s", p);
482 			}
483 	/*if (!osep)
484 		osep = isep;*/
485 	switch (ac) {
486 	/*case 3:
487 		opages = atoi(av[2]);*/
488 	case 2:
489 		ocols = atoi(av[1]);
490 	case 1:
491 		orows = atoi(av[0]);
492 	case 0:
493 		break;
494 	default:
495 		usage("Too many arguments.", "");
496 	}
497 }
498 
499 char *
500 getlist(list, p)
501 	short **list;
502 	char *p;
503 {
504 	register int count = 1;
505 	register char *t;
506 
507 	for (t = p + 1; *t; t++) {
508 		if (!isdigit(*t))
509 			usage("Option %.1s requires a list of unsigned numbers separated by commas", t);
510 		count++;
511 		while (*t && isdigit(*t))
512 			t++;
513 		if (*t != ',')
514 			break;
515 	}
516 	if (!(*list = (short *) malloc(count * sizeof(short))))
517 		errx(1, "No list space");
518 	count = 0;
519 	for (t = p + 1; *t; t++) {
520 		(*list)[count++] = atoi(t);
521 		printf("++ %d ", (*list)[count-1]);
522 		fflush(stdout);
523 		while (*t && isdigit(*t))
524 			t++;
525 		if (*t != ',')
526 			break;
527 	}
528 	(*list)[count] = 0;
529 	return(t - 1);
530 }
531 
532 char *
533 getnum(num, p, strict)	/* num = number p points to; if (strict) complain */
534 	int *num, strict;	/* returns pointer to end of num */
535 	char *p;
536 {
537 	register char *t = p;
538 
539 	if (!isdigit(*++t)) {
540 		if (strict || *t == '-' || *t == '+')
541 			usage("Option %.1s requires an unsigned integer", p);
542 		*num = 0;
543 		return(p);
544 	}
545 	*num = atoi(t);
546 	while (*++t)
547 		if (!isdigit(*t))
548 			break;
549 	return(--t);
550 }
551