ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcollate.c
Revision: 2.23
Committed: Sun Mar 6 01:13:18 2016 UTC (8 years, 1 month ago) by schorsch
Content type: text/plain
Branch: MAIN
Changes since 2.22: +9 -8 lines
Log Message:
Prepare for SCons build on Win32 and Win64

File Contents

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