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