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