ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcollate.c
Revision: 2.4
Committed: Fri Sep 6 21:34:39 2013 UTC (10 years, 7 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.3: +12 -6 lines
Log Message:
Added -w option to turn off warnings

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.4 static const char RCSid[] = "$Id: rcollate.c,v 2.3 2013/09/05 18:47:12 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * Utility to re-order records in a binary or ASCII data file (matrix)
6     */
7    
8     #include <stdlib.h>
9     #include <unistd.h>
10     #include <string.h>
11     #include <ctype.h>
12     #include "platform.h"
13     #include "rtio.h"
14     #include "resolu.h"
15     #ifndef _WIN32
16     #include <sys/mman.h>
17     #endif
18    
19     #ifdef getc_unlocked /* avoid horrendous overhead of flockfile */
20     #undef getc
21     #undef putc
22     #define getc getc_unlocked
23     #define putc putc_unlocked
24     #endif
25    
26     typedef struct {
27     void *base; /* pointer to base memory */
28     size_t len; /* allocated memory length */
29     int mapped; /* memory-mapped file? */
30     } MEMLOAD; /* file loaded/mapped into memory */
31    
32     typedef struct {
33     int nw_rec; /* number of words per record */
34     int nrecs; /* number of records we found */
35     char *rec[1]; /* record array (extends struct) */
36     } RECINDEX;
37    
38 greg 2.4 int warnings = 1; /* report warnings? */
39    
40 greg 2.1 /* free loaded file */
41     static void
42     free_load(MEMLOAD *mp)
43     {
44     if (mp == NULL || (mp->base == NULL) | (mp->len <= 0))
45     return;
46     #ifdef MAP_FILE
47     if (mp->mapped)
48     munmap(mp->base, mp->len);
49     else
50     #endif
51     free(mp->base);
52     mp->base = NULL;
53     mp->len = 0;
54     }
55    
56     /* load a file into memory */
57     static int
58     load_file(MEMLOAD *mp, FILE *fp)
59     {
60     int fd;
61     off_t skip, flen;
62    
63     if (mp == NULL)
64     return(-1);
65     mp->base = NULL;
66     mp->len = 0;
67     mp->mapped = 0;
68     if (fp == NULL)
69     return(-1);
70     fd = fileno(fp);
71     skip = ftello(fp);
72     flen = lseek(fd, 0, SEEK_END);
73     if (flen <= skip)
74     return((int)(flen - skip));
75     mp->len = (size_t)(flen - skip);
76     #ifdef MAP_FILE
77     if (mp->len > 1L<<20) { /* map file if > 1 MByte */
78 greg 2.2 mp->base = mmap(NULL, mp->len, PROT_READ, MAP_PRIVATE, fd, skip);
79 greg 2.1 if (mp->base != MAP_FAILED) {
80     mp->mapped = 1;
81     return(1); /* mmap() success */
82     }
83     mp->base = NULL; /* fall back to reading it in... */
84     }
85     #endif
86     if (lseek(fd, skip, SEEK_SET) != skip ||
87     (mp->base = malloc(mp->len)) == NULL) {
88     mp->len = 0;
89     return(-1);
90     }
91     if (read(fd, (char *)mp->base, mp->len) != mp->len) {
92     free_load(mp);
93     return(-1);
94     }
95     return(1);
96     }
97    
98     /* load memory from an input stream, starting from current position */
99     static int
100     load_stream(MEMLOAD *mp, FILE *fp)
101     {
102     char buf[8192];
103     size_t nr;
104    
105     if (mp == NULL)
106     return(-1);
107     mp->base = NULL;
108     mp->len = 0;
109     mp->mapped = 0;
110     if (fp == NULL)
111     return(-1);
112     while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
113     if (!mp->len)
114     mp->base = malloc(nr);
115     else
116     mp->base = realloc(mp->base, mp->len+nr);
117     if (mp->base == NULL)
118     return(-1);
119     memcpy((char *)mp->base + mp->len, buf, nr);
120     mp->len += nr;
121     }
122     if (ferror(fp)) {
123     free_load(mp);
124     return(-1);
125     }
126     return(mp->len > 0);
127     }
128    
129     /* free a record index */
130     #define free_records(rp) free(rp)
131    
132     /* compute record index */
133     static RECINDEX *
134     index_records(const MEMLOAD *mp, int nw_rec)
135     {
136     RECINDEX *rp;
137     char *cp, *mend;
138     int n;
139    
140     if (mp == NULL || (mp->base == NULL) | (mp->len <= 0))
141     return(NULL);
142     if (nw_rec <= 0)
143     return(NULL);
144     rp = (RECINDEX *)malloc(sizeof(RECINDEX) + mp->len/(2*nw_rec)*sizeof(char *));
145     if (rp == NULL)
146     return(NULL);
147     rp->nw_rec = nw_rec;
148     rp->nrecs = 0;
149     cp = (char *)mp->base;
150     mend = cp + mp->len;
151     for ( ; ; ) { /* whitespace-separated words */
152     while (cp < mend && !*cp | isspace(*cp))
153     ++cp;
154     if (cp >= mend)
155     break;
156     rp->rec[rp->nrecs++] = cp; /* point to first non-white */
157     n = rp->nw_rec;
158     while (++cp < mend) /* find end of record */
159     if (!*cp | isspace(*cp)) {
160     if (--n <= 0)
161     break; /* got requisite # words */
162     do { /* else find next word */
163     if (*cp == '\n') {
164     fprintf(stderr,
165     "Unexpected EOL in record!\n");
166     free_records(rp);
167     return(NULL);
168     }
169     if (++cp >= mend)
170     break;
171     } while (!*cp | isspace(*cp));
172     }
173     }
174     rp->rec[rp->nrecs] = mend; /* reallocate to save space */
175     rp = (RECINDEX *)realloc(rp,
176     sizeof(RECINDEX) + rp->nrecs*sizeof(char *));
177     return(rp);
178     }
179    
180     /* count number of columns based on first EOL */
181     static int
182     count_columns(const RECINDEX *rp)
183     {
184     char *cp = rp->rec[0];
185     char *mend = rp->rec[rp->nrecs];
186     int i;
187    
188     while (*cp != '\n')
189     if (++cp >= mend)
190     return(0);
191     for (i = 0; i < rp->nrecs; i++)
192     if (rp->rec[i] >= cp)
193     break;
194     return(i);
195     }
196    
197     /* copy nth record from index to stdout */
198     static int
199     print_record(const RECINDEX *rp, int n)
200     {
201     int words2go = rp->nw_rec;
202     char *scp;
203    
204     if ((n < 0) | (n >= rp->nrecs))
205     return(0);
206     scp = rp->rec[n];
207     do {
208     putc(*scp++, stdout);
209     if (!*scp | isspace(*scp)) {
210     if (--words2go <= 0)
211     break;
212     putc(' ', stdout); /* single space btwn. words */
213     do
214     if (++scp >= rp->rec[n+1])
215     break;
216     while (!*scp | isspace(*scp));
217     }
218     } while (scp < rp->rec[n+1]);
219     /* caller adds record sep. */
220     return(1);
221     }
222    
223     /* copy a stream to stdout */
224     static int
225     output_stream(FILE *fp)
226     {
227     char buf[8192];
228     ssize_t n;
229    
230     if (fp == NULL)
231     return(0);
232     fflush(stdout); /* assumes nothing in input buffer */
233     while ((n = read(fileno(fp), buf, sizeof(buf))) > 0)
234     if (write(fileno(stdout), buf, n) != n)
235     return(0);
236     return(n >= 0);
237     }
238    
239     /* get next word from stream, leaving stream on EOL or start of next word */
240     static char *
241     fget_word(char buf[256], FILE *fp)
242     {
243     int c;
244     char *cp;
245     /* skip nul's and white space */
246     while (!(c = getc(fp)) || isspace(c))
247     ;
248     if (c == EOF)
249     return(NULL);
250     cp = buf;
251     do
252     *cp++ = c;
253     while ((c = getc(fp)) != EOF && !isspace(c) && cp < buf+255);
254     *cp = '\0';
255     while (isspace(c) & (c != '\n'))
256     c = getc(fp);
257     if (c != EOF)
258     ungetc(c, fp);
259     return(buf);
260     }
261    
262     char *fmtid = "ascii"; /* format id */
263     int record_width = 3; /* words/record (<0 binary) */
264     int ni_columns = 0; /* number of input columns */
265     int ni_rows = 0; /* number of input rows */
266     int no_columns = 0; /* number of output columns */
267     int no_rows = 0; /* number of output rows */
268    
269     /* output transposed ASCII or binary data from memory */
270     static int
271     do_transpose(const MEMLOAD *mp)
272     {
273     static const char tabEOL[2] = {'\t','\n'};
274     RECINDEX *rp = NULL;
275     long nrecords;
276     int i, j;
277     /* get # records (& index) */
278     if (record_width > 0) {
279     if ((rp = index_records(mp, record_width)) == NULL)
280     return(0);
281     if (ni_columns <= 0)
282     ni_columns = count_columns(rp);
283     nrecords = rp->nrecs;
284 greg 2.3 } else if ((ni_rows > 0) & (ni_columns > 0)) {
285 greg 2.1 nrecords = ni_rows*ni_columns;
286 greg 2.3 if (nrecords > mp->len / -record_width) {
287     fprintf(stderr,
288     "Input too small for specified size and type\n");
289     return(0);
290     }
291     } else
292 greg 2.1 nrecords = mp->len / -record_width;
293     /* check sizes */
294     if (ni_rows <= 0)
295     ni_rows = no_columns;
296     if (ni_columns <= 0)
297     ni_columns = no_rows;
298     if ((ni_rows <= 0) & (ni_columns > 0))
299     ni_rows = nrecords/ni_columns;
300     if ((ni_columns <= 0) & (ni_rows > 0))
301     ni_columns = nrecords/ni_rows;
302     if (nrecords != ni_rows*ni_columns)
303     goto badspec;
304     if (no_columns <= 0)
305     no_columns = ni_rows;
306     if (no_rows <= 0)
307     no_rows = ni_columns;
308     if ((no_rows != ni_columns) | (no_columns != ni_rows))
309     goto badspec;
310     /* transpose records */
311     for (i = 0; i < no_rows; i++) {
312     for (j = 0; j < no_columns; j++)
313     if (rp != NULL) { /* ASCII output */
314     print_record(rp, j*ni_columns + i);
315     putc(tabEOL[j >= no_columns-1], stdout);
316     } else { /* binary output */
317     fwrite((char *)mp->base +
318     -record_width*(j*ni_columns + i),
319     -record_width, 1, stdout);
320     }
321     if (ferror(stdout)) {
322     fprintf(stderr, "Error writing to stdout\n");
323     return(0);
324     }
325     }
326     if (rp != NULL)
327     free_records(rp);
328     return(1);
329     badspec:
330     fprintf(stderr, "Bad transpose specification -- check dimension(s)\n");
331     return(0);
332     }
333    
334     /* resize ASCII stream input by ignoring EOLs between records */
335     static int
336     do_resize(FILE *fp)
337     {
338     long records2go = ni_rows*ni_columns;
339     int columns2go = no_columns;
340     char word[256];
341     /* sanity checks */
342     if (record_width <= 0) {
343     fprintf(stderr, "Bad call to do_resize (record_width = %d)\n",
344     record_width);
345     return(0);
346     }
347     if (no_columns <= 0) {
348     fprintf(stderr, "Missing -oc specification\n");
349     return(0);
350     }
351     if ((records2go <= 0) & (no_rows > 0))
352     records2go = no_rows*no_columns;
353     else if (no_rows*no_columns != records2go) {
354     fprintf(stderr,
355     "Input and output data sizes disagree (%dx%d != %dx%d)\n",
356     ni_rows, ni_columns, no_rows, no_columns);
357     return(0);
358     }
359     do { /* reshape records */
360     int n;
361    
362     for (n = record_width; n--; ) {
363     if (fget_word(word, fp) == NULL) {
364     if (records2go > 0 || n < record_width-1)
365     break;
366     goto done; /* normal EOD */
367     }
368     fputs(word, stdout);
369     if (n) { /* mid-record? */
370     int c = getc(fp);
371     if ((c == '\n') | (c == EOF))
372     break;
373     ungetc(c, fp);
374     putc(' ', stdout);
375     }
376     }
377     if (n >= 0) {
378     fprintf(stderr, "Incomplete record / unexpected EOF\n");
379     return(0);
380     }
381     if (--columns2go <= 0) { /* time to end output row? */
382     putc('\n', stdout);
383     columns2go = no_columns;
384     } else /* else separate records */
385     putc('\t', stdout);
386     } while (--records2go); /* expected EOD? */
387     done:
388 greg 2.4 if (warnings && columns2go != no_columns)
389 greg 2.1 fprintf(stderr, "Warning -- incomplete final row\n");
390 greg 2.4 if (warnings && fget_word(word, fp) != NULL)
391     fprintf(stderr, "Warning -- characters beyond expected EOD\n");
392 greg 2.1 return(1);
393     }
394    
395     /* process a header line and copy to stdout */
396     static int
397     headline(char *s, void *p)
398     {
399     char fmt[32];
400    
401     if (formatval(fmt, s)) {
402     if (!strcmp(fmt, fmtid))
403     return(0);
404     fprintf(stderr, "Input format '%s' != '%s'\n", fmt, fmtid);
405     return(-1);
406     }
407     fputs(s, stdout); /* copy header info. */
408     return(0);
409     }
410    
411     /* main routine for converting rows/columns in data file */
412     int
413     main(int argc, char *argv[])
414     {
415     int do_header = 1; /* header i/o? */
416     int transpose = 0; /* transpose rows & cols? */
417     int i;
418    
419     for (i = 1; i < argc && argv[i][0] == '-'; i++)
420     switch (argv[i][1]) {
421     case 'i': /* input */
422     if (argv[i][2] == 'c') /* columns */
423     ni_columns = atoi(argv[++i]);
424     else if (argv[i][2] == 'r')
425     ni_rows = atoi(argv[++i]);
426     else
427     goto userr;
428     break;
429     case 'o': /* output */
430     if (argv[i][2] == 'c') /* columns */
431     no_columns = atoi(argv[++i]);
432     else if (argv[i][2] == 'r')
433     no_rows = atoi(argv[++i]);
434     else
435     goto userr;
436     break;
437     case 'h': /* header on/off */
438     do_header = !do_header;
439     break;
440     case 't': /* transpose on/off */
441     transpose = !transpose;
442     break;
443     case 'f': /* format */
444     switch (argv[i][2]) {
445     case 'a': /* ASCII */
446     case 'A':
447     fmtid = "ascii";
448     record_width = 1;
449     break;
450     case 'f': /* float */
451     case 'F':
452     fmtid = "float";
453     record_width = -(int)sizeof(float);
454     break;
455     case 'd': /* double */
456     case 'D':
457     fmtid = "double";
458     record_width = -(int)sizeof(double);
459     break;
460     case 'b': /* binary (bytes) */
461     case 'B':
462     fmtid = "byte";
463     record_width = -1;
464     break;
465     default:
466     goto userr;
467     }
468     if (argv[i][3]) {
469     if (!isdigit(argv[i][3]))
470     goto userr;
471     record_width *= atoi(argv[i]+3);
472     }
473     break;
474 greg 2.4 case 'w': /* warnings on/off */
475     warnings = !warnings;
476     break;
477 greg 2.1 default:
478     goto userr;
479     }
480     if (!record_width)
481     goto userr;
482     if (i < argc-1) /* arg count OK? */
483     goto userr;
484     /* open input file? */
485     if (i == argc-1 && freopen(argv[i], "r", stdin) == NULL) {
486     fprintf(stderr, "%s: cannot open for reading\n", argv[i]);
487     return(1);
488     }
489     if (record_width < 0) {
490     SET_FILE_BINARY(stdin);
491     SET_FILE_BINARY(stdout);
492     }
493     /* check for no-op */
494     if (!transpose && (record_width < 0 ||
495     (no_columns == ni_columns) & (no_rows == ni_rows))) {
496 greg 2.4 if (warnings)
497     fprintf(stderr, "%s: no-op -- copying input verbatim\n",
498 greg 2.1 argv[0]);
499     if (!output_stream(stdin))
500     return(1);
501     return(0);
502     }
503     if (do_header) { /* read/write header */
504     if (getheader(stdin, &headline, NULL) < 0)
505     return(1);
506     printargs(argc, argv, stdout);
507     fputformat(fmtid, stdout);
508     fputc('\n', stdout); /* finish new header */
509     }
510     if (transpose) { /* transposing rows & columns? */
511     MEMLOAD myMem; /* need to load into memory */
512     if (i == argc-1) {
513     if (load_file(&myMem, stdin) <= 0) {
514     fprintf(stderr, "%s: error loading file into memory\n",
515     argv[i]);
516     return(1);
517     }
518     } else if (load_stream(&myMem, stdin) <= 0) {
519     fprintf(stderr, "%s: error loading stdin into memory\n",
520     argv[0]);
521     return(1);
522     }
523     if (!do_transpose(&myMem))
524     return(1);
525     /* free_load(&myMem); */
526     } else if (!do_resize(stdin)) /* just reshaping input */
527     return(1);
528     return(0);
529     userr:
530     fprintf(stderr,
531 greg 2.4 "Usage: %s [-h][-w][-f[afdb][N]][-t][-ic in_col][-ir in_row][-oc out_col][-or out_row] [input.dat]\n",
532 greg 2.1 argv[0]);
533     return(1);
534     }