ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcollate.c
Revision: 2.11
Committed: Fri May 30 17:29:28 2014 UTC (9 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.10: +11 -5 lines
Log Message:
Added check for unsupported formats

File Contents

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