]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/picsmap.c
ncurses 6.0 - patch 20171223
[ncurses.git] / test / picsmap.c
1 /****************************************************************************
2  * Copyright (c) 2017 Free Software Foundation, Inc.                        *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 /*
29  * $Id: picsmap.c,v 1.114 2017/12/16 23:49:40 tom Exp $
30  *
31  * Author: Thomas E. Dickey
32  *
33  * A little more interesting than "dots", read a simple image into memory and
34  * measure the time taken to paint it normally vs randomly.
35  *
36  * TODO improve use of rgb-names using tsearch.
37  *
38  * TODO add option to dump picture in non-optimized mode, e.g., like tput.
39  * TODO write cells/second to stderr (or log)
40  * TODO write picture left-to-right/top-to-bottom
41  * TODO write picture randomly
42  * TODO add one-shot option vs repeat-count before exiting
43  * TODO add option "-xc" for init_color vs init_extended_color
44  * TODO add option "-xa" for init_pair vs alloc_pair
45  * TODO use pad to allow pictures larger than screen
46  * TODO add option to just use convert (which can scale) vs builtin xbm/xpm.
47  * TODO add scr_dump and scr_restore calls
48  * TODO add option for assume_default_colors
49  */
50 #include <test.priv.h>
51
52 #include <sys/types.h>
53 #include <sys/stat.h>
54
55 #ifdef HAVE_STDINT_H
56 #include <stdint.h>
57 #define my_intptr_t     intptr_t
58 #else
59 #define my_intptr_t     long
60 #endif
61
62 #if HAVE_TSEARCH
63 #include <search.h>
64 #endif
65
66 #undef CUR                      /* use only the curses interface */
67
68 #define  L_BLOCK '['
69 #define  R_BLOCK ']'
70
71 #define  L_CURLY '{'
72 #define  R_CURLY '}'
73
74 #define okCOLOR(n)      ((n) >= 0 && (n) < COLORS)
75 #define okRGB(n)        ((n) >= 0 && (n) <= 1000)
76 #define Scaled256(n)    (NCURSES_COLOR_T) (int)(((n) * 1000.0) / 256)
77 #define ScaledColor(n)  (NCURSES_COLOR_T) (int)(((n) * 1000.0) / scale)
78
79 #ifndef RGB_PATH
80 #define RGB_PATH "/etc/X11/rgb.txt"
81 #endif
82
83 #include <picsmap.h>
84
85 typedef struct {
86     size_t file;
87     size_t name;
88     size_t list;
89     size_t data;
90     size_t head;
91     size_t pair;
92     size_t cell;
93 } HOW_MUCH;
94
95 #undef MAX
96 #define MAX(a,b) ((a)>(b)?(a):(b))
97
98 /*
99  * tfind will return null on failure, so we map subscripts starting at one.
100  */
101 #define P2I(n) (((int)(my_intptr_t)(n)) - 1)
102 #define I2P(n) (void *)(my_intptr_t)((n) + 1)
103
104 #define stop_curses() if (in_curses) endwin()
105
106 #define debugmsg if (debugging) logmsg
107 #define debugmsg2 if (debugging) logmsg2
108
109 static void cleanup(int) GCC_NORETURN;
110 static void giveup(const char *fmt,...) GCC_PRINTFLIKE(1, 2);
111 static void logmsg(const char *fmt,...) GCC_PRINTFLIKE(1, 2);
112 static void logmsg2(const char *fmt,...) GCC_PRINTFLIKE(1, 2);
113 static void warning(const char *fmt,...) GCC_PRINTFLIKE(1, 2);
114 static int gather_c_values(int);
115
116 static FILE *logfp = 0;
117 static double aspect_ratio = 0.6;
118 static bool in_curses = FALSE;
119 static bool debugging = FALSE;
120 static bool quiet = FALSE;
121 static int slow_time = -1;
122 static RGB_NAME *rgb_table;
123 static RGB_DATA *all_colors;
124 static HOW_MUCH how_much;
125
126 static int reading_last;
127 static int reading_size;
128 static FG_NODE *reading_ncols;
129
130 #if HAVE_TSEARCH
131 static void *reading_ntree;
132 #endif
133
134 #if HAVE_ALLOC_PAIR && HAVE_INIT_EXTENDED_COLOR
135 #define USE_EXTENDED_COLORS 1
136 static bool use_extended_pairs = FALSE;
137 static bool use_extended_colors = FALSE;
138 #else
139 #define USE_EXTENDED_COLORS 0
140 #endif
141
142 static void
143 logmsg(const char *fmt,...)
144 {
145     if (logfp != 0) {
146         va_list ap;
147         va_start(ap, fmt);
148         vfprintf(logfp, fmt, ap);
149         va_end(ap);
150         fputc('\n', logfp);
151         fflush(logfp);
152     }
153 }
154
155 static void
156 logmsg2(const char *fmt,...)
157 {
158     if (logfp != 0) {
159         va_list ap;
160         va_start(ap, fmt);
161         vfprintf(logfp, fmt, ap);
162         va_end(ap);
163         fflush(logfp);
164     }
165 }
166
167 static void
168 close_log(void)
169 {
170     if (logfp != 0) {
171         logmsg("Allocations:");
172         logmsg("%8ld file", (long) how_much.file);
173         logmsg("%8ld name", (long) how_much.name);
174         logmsg("%8ld list", (long) how_much.list);
175         logmsg("%8ld data", (long) how_much.data);
176         logmsg("%8ld head", (long) how_much.head);
177         logmsg("%8ld pair", (long) how_much.pair);
178         logmsg("%8ld cell", (long) how_much.cell);
179         logmsg("%8ld window", LINES * COLS * (long) sizeof(NCURSES_CH_T));
180         fclose(logfp);
181         logfp = 0;
182     }
183 }
184
185 static void
186 cleanup(int code)
187 {
188     stop_curses();
189     close_log();
190     ExitProgram(code);
191     /* NOTREACHED */
192 }
193
194 static void
195 failed(const char *msg)
196 {
197     int save = errno;
198     perror(msg);
199     logmsg("failed with %s", strerror(save));
200     cleanup(EXIT_FAILURE);
201 }
202
203 static void
204 warning(const char *fmt,...)
205 {
206     if (logfp != 0) {
207         va_list ap;
208         va_start(ap, fmt);
209         vfprintf(logfp, fmt, ap);
210         va_end(ap);
211         fputc('\n', logfp);
212         fflush(logfp);
213     } else {
214         va_list ap;
215         va_start(ap, fmt);
216         vfprintf(stderr, fmt, ap);
217         va_end(ap);
218         fputc('\n', stderr);
219         cleanup(EXIT_FAILURE);
220     }
221 }
222
223 static void
224 free_data(char **data)
225 {
226     if (data != 0) {
227         free(data[0]);
228         free(data);
229     }
230 }
231
232 static PICS_HEAD *
233 free_pics_head(PICS_HEAD * pics)
234 {
235     if (pics != 0) {
236         free(pics->fgcol);
237         free(pics->cells);
238         free(pics->name);
239         free(pics);
240         pics = 0;
241     }
242     return pics;
243 }
244
245 static void
246 begin_c_values(int size)
247 {
248     reading_last = 0;
249     reading_size = size;
250     reading_ncols = typeCalloc(FG_NODE, size + 1);
251     how_much.pair += (sizeof(FG_NODE) * (size_t) size);
252     /* black is always the first slot, to work around P2I/I2P logic */
253     gather_c_values(0);
254 }
255
256 #if HAVE_TSEARCH
257 static int
258 compare_c_values(const void *p, const void *q)
259 {
260     const int a = P2I(p);
261     const int b = P2I(q);
262     return (reading_ncols[a].fgcol - reading_ncols[b].fgcol);
263 }
264
265 #ifdef DEBUG_TSEARCH
266 static void
267 check_c_values(int ln)
268 {
269     static int oops = 5;
270     FG_NODE **ft;
271     int n;
272     for (n = 0; n < reading_last; ++n) {
273         ft = tfind(I2P(n), &reading_ntree, compare_c_values);
274         if (ft != 0) {
275             int q = P2I(*ft);
276             if (reading_ncols[q].fgcol != reading_ncols[n].fgcol) {
277                 logmsg("@%d, %d:%d (%d) %d %d fgcol %06X %06X", ln, n,
278                        reading_last - 1,
279                        reading_size,
280                        q, n,
281                        reading_ncols[n].fgcol,
282                        reading_ncols[q].fgcol);
283             }
284         } else {
285             logmsg("@%d, %d:%d (%d) ? %d null %06X", ln, n,
286                    reading_last - 1,
287                    reading_size,
288                    n,
289                    reading_ncols[n].fgcol);
290             if (oops-- <= 0)
291                 return;
292         }
293     }
294 }
295 #else
296 #define check_c_values(n)       /* nothing */
297 #endif
298 #endif
299
300 static int
301 gather_c_values(int fg)
302 {
303     int found = -1;
304 #if HAVE_TSEARCH
305     FG_NODE **ft;
306     int next = reading_last;
307
308     reading_ncols[next].fgcol = fg;
309     reading_ncols[next].count = 0;
310
311     check_c_values(__LINE__);
312     if ((ft = tfind(I2P(next), &reading_ntree, compare_c_values)) != 0) {
313         found = P2I(*ft);
314     } else {
315         if (reading_last + 2 >= reading_size) {
316             int more = ((MAX(reading_last, reading_size) + 2) * 3) / 2;
317             int last = reading_last + 1;
318             FG_NODE *p = typeRealloc(FG_NODE, more, reading_ncols);
319             if (p == 0)
320                 goto done;
321
322             reading_size = more;
323             reading_ncols = p;
324             memset(reading_ncols + last, 0,
325                    sizeof(FG_NODE) * (size_t) (more - last));
326             check_c_values(__LINE__);
327         }
328         ++reading_last;
329         how_much.pair += sizeof(FG_NODE);
330         if ((ft = tsearch(I2P(next), &reading_ntree, compare_c_values)) != 0) {
331             found = P2I(*ft);
332             if (found != next)
333                 logmsg("OOPS expected slot %d, got %d", next, found);
334             debugmsg("allocated color #%d as #%06X", next, fg);
335             check_c_values(__LINE__);
336         }
337     }
338 #else
339     int n;
340
341     for (n = 0; n < reading_last; ++n) {
342         if (reading_ncols[n].fgcol == fg) {
343             found = n;
344             break;
345         }
346     }
347     if (found < 0) {
348         if (reading_last + 2 >= reading_size) {
349             int more = ((reading_last + 2) * 3) / 2;
350             FG_NODE *p = typeRealloc(FG_NODE, more, reading_ncols);
351             if (p == 0)
352                 goto done;
353
354             how_much.pair -= (sizeof(FG_NODE) * (size_t) reading_size);
355             how_much.pair += (sizeof(FG_NODE) * (size_t) more);
356             reading_size = more;
357             reading_ncols = p;
358             memset(reading_ncols + reading_last, 0,
359                    sizeof(FG_NODE) * (size_t) (more - reading_last));
360         }
361         reading_ncols[reading_last].fgcol = fg;
362         found = reading_last++;
363     }
364 #endif
365   done:
366     return found;
367 }
368
369 static void
370 finish_c_values(PICS_HEAD * head)
371 {
372     head->colors = reading_last;
373     head->fgcol = reading_ncols;
374
375     reading_last = 0;
376     reading_size = 0;
377     reading_ncols = 0;
378 }
379
380 #if HAVE_TSEARCH && HAVE_TDESTROY
381 static void
382 never_free(void *node GCC_UNUSED)
383 {
384 }
385 #endif
386
387 static void
388 dispose_c_values(void)
389 {
390 #if HAVE_TSEARCH
391     if (reading_ntree != 0) {
392 #if HAVE_TDESTROY
393         tdestroy(reading_ntree, never_free);
394 #else
395         int n;
396         for (n = 0; n < reading_last; ++n) {
397             tdelete(I2P(n), &reading_ntree, compare_c_values);
398         }
399 #endif
400         reading_ntree = 0;
401     }
402 #endif
403     if (reading_ncols != 0) {
404         free(reading_ncols);
405         reading_ncols = 0;
406     }
407     reading_last = 0;
408     reading_size = 0;
409 }
410
411 static int
412 is_file(const char *filename, struct stat *sb)
413 {
414     int result = 0;
415     if (stat(filename, sb) == 0
416         && (sb->st_mode & S_IFMT) == S_IFREG
417         && sb->st_size != 0) {
418         result = 1;
419     }
420     debugmsg("is_file(%s) %d", filename, result);
421     return result;
422 }
423
424 /*
425  * Simplify reading xbm/xpm files by first making an array of lines.  Blank
426  * lines are filtered out.
427  */
428 static char **
429 read_file(const char *filename)
430 {
431     char **result = 0;
432     struct stat sb;
433
434     if (!quiet) {
435         stop_curses();
436         printf("** %s\n", filename);
437     }
438
439     if (is_file(filename, &sb)) {
440         size_t size = (size_t) sb.st_size;
441         char *blob = typeCalloc(char, size + 1);
442         bool had_line = TRUE;
443         bool binary = FALSE;
444         unsigned j;
445         unsigned k = 0;
446
447         result = typeCalloc(char *, size + 1);
448         how_much.file += ((size + 1) * 2);
449
450         if (blob != 0 && result != 0) {
451             FILE *fp = fopen(filename, "r");
452             if (fp != 0) {
453                 logmsg("opened %s", filename);
454                 if (fread(blob, sizeof(char), size, fp) == size) {
455                     for (j = 0; (size_t) j < size; ++j) {
456                         if (blob[j] == '\0' ||
457                             (UChar(blob[j]) < 32 &&
458                              !isspace(UChar(blob[j]))) ||
459                             (UChar(blob[j]) >= 128 && UChar(blob[j]) < 160)) {
460                             binary = TRUE;
461                         }
462                         if (blob[j] == '\n') {
463                             blob[j] = '\0';
464                             if (k && !binary) {
465                                 debugmsg2("[%5d] %s\n", k, result[k - 1]);
466                             }
467                             had_line = TRUE;
468                         } else if (had_line) {
469                             had_line = FALSE;
470                             result[k++] = blob + j;
471                         }
472                     }
473                     result[k] = 0;
474                     if (k && !binary) {
475                         debugmsg2("[%5d] %s\n", k, result[k - 1]);
476                     }
477                 }
478                 fclose(fp);
479             } else {
480                 logmsg("cannot open %s", filename);
481             }
482         }
483         if (k == 0) {
484             debugmsg("...file is empty");
485             free(blob);
486             free(result);
487             result = 0;
488         } else if (binary) {
489             debugmsg("...file is non-text");
490         }
491     }
492     return result;
493 }
494
495 static void
496 usage(void)
497 {
498     static const char *msg[] =
499     {
500         "Usage: picsmap [options] [imagefile [...]]"
501         ,"Read/display one or more xbm/xpm files (possibly use \"convert\")"
502         ,""
503         ,"Options:"
504         ,"  -a ratio     aspect-ratio correction for ImageMagick"
505 #if HAVE_USE_DEFAULT_COLORS
506         ,"  -d           invoke use_default_colors"
507 #endif
508         ,"  -L           add debugging information to logfile"
509         ,"  -l logfile   write informational messages to logfile"
510         ,"  -p palette   color-palette file (default \"$TERM.dat\")"
511         ,"  -q           less verbose"
512         ,"  -r rgb-path  xpm uses X rgb color-names (default \"" RGB_PATH "\")"
513         ,"  -s SECS      pause for SECS seconds after display vs getch"
514 #if USE_EXTENDED_COLORS
515         ,"  -x [pc]      use extension (p=extended-pairs, c=extended-colors)"
516         ,"               Either/both extension may be given"
517 #endif
518     };
519     size_t n;
520
521     stop_curses();
522
523     fflush(stdout);
524     for (n = 0; n < SIZEOF(msg); n++)
525         fprintf(stderr, "%s\n", msg[n]);
526     cleanup(EXIT_FAILURE);
527 }
528
529 static void
530 giveup(const char *fmt,...)
531 {
532     va_list ap;
533
534     stop_curses();
535     fflush(stdout);
536
537     va_start(ap, fmt);
538     vfprintf(stderr, fmt, ap);
539     fputc('\n', stderr);
540     va_end(ap);
541
542     if (logfp) {
543         va_start(ap, fmt);
544         vfprintf(logfp, fmt, ap);
545         fputc('\n', logfp);
546         va_end(ap);
547         fflush(logfp);
548     }
549
550     usage();
551 }
552
553 /*
554  * Palette files are named for $TERM values.  However, there are fewer palette
555  * files than $TERM's.  Although there are known problems (some cannot even get
556  * black and white correct), for the purpose of comparison, pretending that
557  * those map into "xterm" is useful.
558  */
559 static char **
560 read_palette(const char *filename)
561 {
562     static const char *data_dir = DATA_DIR;
563     char **result = 0;
564     char *full_name = malloc(strlen(data_dir) + 20 + strlen(filename));
565     char *s;
566     struct stat sb;
567
568     if (full_name != 0) {
569         int tries;
570         for (tries = 0; tries < 8; ++tries) {
571
572             *(s = full_name) = '\0';
573             if (tries & 1) {
574                 if (strchr(filename, '/') == 0) {
575                     sprintf(full_name, "%s/", data_dir);
576                 } else {
577                     continue;
578                 }
579             }
580             s += strlen(s);
581
582             strcpy(s, filename);
583             if (tries & 4) {
584                 char *t = s;
585                 int num;
586                 char chr;
587                 int found = 0;
588                 while (*t != '\0') {
589                     if (*t == '-') {
590                         if (sscanf(t, "-%d%c", &num, &chr) == 2 &&
591                             chr == 'c' &&
592                             !strncmp(strchr(t, chr), "color", 5)) {
593                             found = 1;
594                         }
595                         break;
596                     }
597                     ++t;
598                 }
599                 if (found && (t != s)
600                     && strncmp(s, "xterm", (size_t) (t - s))) {
601                     sprintf(s, "xterm%s", filename + (t - s));
602                 } else {
603                     continue;
604                 }
605             }
606             s += strlen(s);
607
608             if (tries & 2) {
609                 int len = (int) strlen(filename);
610                 if (len <= 4 || strcmp(filename + len - 4, ".dat")) {
611                     strcpy(s, ".dat");
612                 } else {
613                     continue;
614                 }
615             }
616             if (is_file(full_name, &sb))
617                 goto ok;
618         }
619         goto failed;
620       ok:
621         result = read_file(full_name);
622       failed:
623         free(full_name);
624     }
625     return result;
626 }
627
628 static void
629 init_palette(const char *palette_file)
630 {
631     if (palette_file != 0) {
632         char **data = read_palette(palette_file);
633
634         all_colors = typeMalloc(RGB_DATA, (unsigned) COLORS);
635         how_much.data += (sizeof(RGB_DATA) * (unsigned) COLORS);
636
637 #if HAVE_COLOR_CONTENT
638         {
639             int cp;
640             for (cp = 0; cp < COLORS; ++cp) {
641                 color_content((short) cp,
642                               &all_colors[cp].red,
643                               &all_colors[cp].green,
644                               &all_colors[cp].blue);
645             }
646         }
647 #else
648         memset(all_colors, 0, sizeof(RGB_DATA) * (size_t) COLORS);
649 #endif
650         if (data != 0) {
651             int n;
652             int red, green, blue;
653             int scale = 1000;
654             int c;
655             for (n = 0; data[n] != 0; ++n) {
656                 if (sscanf(data[n], "scale:%d", &c) == 1) {
657                     scale = c;
658                 } else if (sscanf(data[n], "%d:%d %d %d",
659                                   &c,
660                                   &red,
661                                   &green,
662                                   &blue) == 4
663                            && okCOLOR(c)
664                            && okRGB(red)
665                            && okRGB(green)
666                            && okRGB(blue)) {
667                     /* *INDENT-EQLS* */
668                     all_colors[c].red   = ScaledColor(red);
669                     all_colors[c].green = ScaledColor(green);
670                     all_colors[c].blue  = ScaledColor(blue);
671                 }
672             }
673         }
674         free_data(data);
675         /* *INDENT-EQLS* */
676     } else if (COLORS > 1) {
677         int power2 = 1;
678         int shift = 0;
679
680         while (power2 < COLORS) {
681             ++shift;
682             power2 <<= 1;
683         }
684
685         if ((power2 != COLORS) || ((shift % 3) != 0)) {
686             if (all_colors == 0) {
687                 init_palette(getenv("TERM"));
688             }
689             if (all_colors == 0) {
690                 giveup("With %d colors, you need a palette-file", COLORS);
691             }
692         }
693     }
694 }
695
696 /*
697  * Map the 24-bit RGB value to a color index if using a palette, otherwise to a
698  * direct color value.
699  */
700 static int
701 map_color(int value)
702 {
703     int result = value;
704
705     if (result < 0) {
706         result = -1;
707     } else {
708         /* *INDENT-EQLS* */
709         int red   = (value & 0xff0000) >> 16;
710         int green = (value & 0x00ff00) >> 8;
711         int blue  = (value & 0x0000ff) >> 0;
712
713         if (all_colors != 0) {
714 #define Diff2(n,m) ((m) - all_colors[n].m) * ((m) - all_colors[n].m)
715 #define Diff2S(n) Diff2(n,red) + Diff2(n,green) + Diff2(n,blue)
716             int d2 = Diff2S(0);
717             int n;
718
719             /* *INDENT-EQLS* */
720             red   = Scaled256(red);
721             green = Scaled256(green);
722             blue  = Scaled256(blue);
723
724             for (result = 0, n = 1; n < COLORS; ++n) {
725                 int d = Diff2(n, red) + Diff2(n, green) + Diff2(n, blue);
726                 if (d < d2) {
727                     d2 = d;
728                     result = n;
729                 }
730             }
731         } else {                /* direct color */
732             int power2 = 1;
733             int shifts = 8;
734
735             while (power2 < COLORS) {
736                 power2 <<= 3;
737                 shifts--;
738             }
739
740             if (shifts > 0) {
741                 /* TODO: round up */
742                 red >>= shifts;
743                 green >>= shifts;
744                 blue >>= shifts;
745                 result = ((red << (2 * (8 - shifts)))
746                           + (green << (8 - shifts))
747                           + blue);
748             }
749         }
750     }
751     return result;
752 }
753
754 static int
755 bytes_of(int value)
756 {
757     if (value & 7) {
758         value |= 7;
759         value++;
760     }
761     return value;
762 }
763
764 static int match_c(const char *, const char *,...) GCC_SCANFLIKE(2,3);
765
766 static char *
767 skip_s(char *s)
768 {
769     while (isspace(UChar(*s)))
770         s++;
771     return s;
772 }
773
774 static const char *
775 skip_cs(const char *s)
776 {
777     while (isspace(UChar(*s)))
778         s++;
779     return s;
780 }
781
782 static char *
783 skip_word(char *s)
784 {
785     s = skip_s(s);
786     while (isgraph(UChar(*s)))
787         s++;
788     return s;
789 }
790
791 static int
792 match_c(const char *source, const char *pattern,...)
793 {
794     int limit = (int) strlen(source);
795     const char *last_s = source + limit;
796     va_list ap;
797     int ch;
798     int *ip;
799     char *cp;
800     long lv;
801
802     va_start(ap, pattern);
803
804     limit = -1;
805     while (*pattern != '\0') {
806         ch = UChar(*pattern++);
807         /* blank in the pattern matches zero-or-more blanks in source */
808         if (isspace(ch)) {
809             source = skip_cs(source);
810             continue;
811         }
812         /* %c, %d, %s are like sscanf except for special treatment of blanks */
813         if (ch == '%' && *pattern != '\0' && strchr("cdnsx", *pattern)) {
814             bool found = FALSE;
815             ch = *pattern++;
816             switch (ch) {
817             case 'c':
818                 cp = va_arg(ap, char *);
819                 do {
820                     *cp++ = *source++;
821                 } while (--limit > 0);
822                 break;
823             case 'd':
824             case 'x':
825                 limit = -1;
826                 ip = va_arg(ap, int *);
827                 lv = strtol(source, &cp, ch == 'd' ? 10 : 16);
828                 if (cp != 0 && cp != source) {
829                     *ip = (int) lv;
830                     source = cp;
831                 } else {
832                     goto finish;
833                 }
834                 break;
835             case 'n':
836                 /* not really sscanf... */
837                 limit = *va_arg(ap, int *);
838                 break;
839             case 's':
840                 limit = -1;
841                 cp = va_arg(ap, char *);
842                 while (*source != '\0') {
843                     ch = UChar(*source);
844                     if (isspace(ch)) {
845                         break;
846                     } else if (found && (ch == *skip_cs(pattern))) {
847                         break;
848                     } else {
849                         *cp++ = *source++;
850                         found = TRUE;
851                     }
852                 }
853                 *cp = '\0';
854                 break;
855             }
856             continue;
857         }
858         /* other characters are matched literally */
859         if (*source++ != ch) {
860             break;
861         }
862     }
863   finish:
864
865     va_end(ap);
866     if (source > last_s)
867         source = last_s;
868     return (*source || *pattern) ? 0 : 1;
869 }
870
871 static int
872 match_colors(const char *source, int cpp, char *arg1, char *arg2, char *arg3)
873 {
874     int result = 0;
875
876     /* most files use a quasi-fixed format */
877     if (match_c(source, " \"%n%c %s %s \" , ", &cpp, arg1, arg2, arg3)) {
878         arg1[cpp] = '\0';
879         result = 1;
880     } else {
881         char *t;
882         const char *s = skip_cs(source);
883         size_t have = strlen(source);
884
885         if (*s++ == '"' && have > ((size_t) cpp + 2)) {
886             memcpy(arg1, s, (size_t) cpp);
887             s += cpp;
888             while (*s++ == '\t') {
889                 for (t = arg2; (*s != '\0') && strchr("\t\"", *s) == 0;) {
890                     if (*s == ' ') {
891                         s = skip_cs(s);
892                         break;
893                     }
894                     *t++ = *s++;
895                     *t = '\0';
896                 }
897                 for (t = arg3; (*s != '\0') && strchr("\t\"", *s) == 0;) {
898                     *t++ = *s++;
899                     *t = '\0';
900                 }
901                 if (!strcmp(arg2, "c")) {
902                     result = 1;
903                     break;
904                 }
905             }
906         }
907     }
908     return result;
909 }
910
911 static RGB_NAME *
912 parse_rgb(char **data)
913 {
914     char buf[BUFSIZ];
915     int n;
916     unsigned long r, g, b;
917     char *s, *t;
918     size_t item = 0;
919     size_t need;
920     RGB_NAME *result = 0;
921
922     for (need = 0; data[need] != 0; ++need) ;
923
924     result = typeCalloc(RGB_NAME, need + 2);
925     how_much.name += (sizeof(RGB_NAME) * (need + 2));
926
927     for (n = 0; data[n] != 0; ++n) {
928         if (strlen(t = data[n]) >= sizeof(buf) - 1)
929             continue;
930         if (*(s = skip_s(t)) == '!')
931             continue;
932
933         r = strtoul(s, &t, 10);
934         s = skip_s(t);
935         g = strtoul(s, &t, 10);
936         s = skip_s(t);
937         b = strtoul(s, &t, 10);
938         s = skip_s(t);
939
940         result[item].name = s;
941         t = s + strlen(s);
942         while (t-- != s && isspace(UChar(*t))) {
943             *t = '\0';
944         }
945         result[item].value = (int) ((r & 0xff) << 16 |
946                                     (g & 0xff) << 8 |
947                                     (b & 0xff));
948         ++item;
949     }
950
951     result[item].name = "none";
952     result[item].value = -1;
953
954     return result;
955 }
956
957 static RGB_NAME *
958 lookup_rgb(const char *name)
959 {
960     RGB_NAME *result = 0;
961     if (rgb_table != 0) {
962         int n;
963         for (n = 0; rgb_table[n].name != 0; ++n) {
964             if (!strcasecmp(name, rgb_table[n].name)) {
965                 result = &rgb_table[n];
966                 break;
967             }
968         }
969     }
970     return result;
971 }
972
973 static PICS_HEAD *
974 parse_xbm(char **data)
975 {
976     int n;
977     int state = 0;
978     char buf[BUFSIZ];
979     int num;
980     char ch;
981     char *s;
982     char *t;
983     PICS_HEAD *result;
984     size_t which = 0;
985     size_t cells = 0;
986
987     debugmsg("called parse_xbm");
988
989     result = typeCalloc(PICS_HEAD, 1);
990     how_much.head += sizeof(PICS_HEAD);
991
992     begin_c_values(2);
993     gather_c_values(0);
994     gather_c_values(0xffffff);
995
996     for (n = 0; data[n] != 0; ++n) {
997         if (strlen(s = data[n]) >= sizeof(buf) - 1)
998             continue;
999         switch (state) {
1000         case 0:
1001         case 1:
1002         case 2:
1003             if (sscanf(s, "#define %s %d%c", buf, &num, &ch) >= 2) {
1004                 if ((t = strstr(buf, "_width")) != 0) {
1005                     state |= 1;
1006                     result->wide = (short) bytes_of(num);
1007                 } else if ((t = strstr(buf, "_height")) != 0) {
1008                     state |= 2;
1009                     result->high = (short) num;
1010                 }
1011                 *t = '\0';
1012                 if (result->name) {
1013                     if (strcmp(result->name, buf)) {
1014                         goto finish;
1015                     }
1016                 } else {
1017                     result->name = strdup(buf);
1018                 }
1019             }
1020             break;
1021         case 3:
1022             if (sscanf(s, "static char %[^_ ]_bits[]%c", buf, &ch) >= 1) {
1023                 if (strcmp(result->name, buf)) {
1024                     goto finish;
1025                 }
1026                 state = 4;
1027                 cells = (size_t) (result->wide * result->high);
1028
1029                 result->cells = typeCalloc(PICS_CELL, cells);
1030                 how_much.cell += (sizeof(PICS_CELL) * cells);
1031
1032                 if ((s = strchr(s, L_CURLY)) == 0)
1033                     break;
1034                 ++s;
1035             } else {
1036                 break;
1037             }
1038         case 4:
1039             while (*s != '\0') {
1040                 while (isspace(UChar(*s))) {
1041                     ++s;
1042                 }
1043                 if (isdigit(UChar(*s))) {
1044                     long value = strtol(s, &t, 0);
1045                     int b;
1046                     if (t != s || value > 255 || value < 0) {
1047                         s = t;
1048                     } else {
1049                         state = -1;
1050                         goto finish;
1051                     }
1052                     for (b = 0; b < 8; ++b) {
1053                         if (((1L << b) & value) != 0) {
1054                             result->cells[which].ch = '*';
1055                             result->cells[which].fg = 1;
1056                             reading_ncols[1].count++;
1057                         } else {
1058                             result->cells[which].ch = ' ';
1059                             result->cells[which].fg = 0;
1060                             reading_ncols[0].count++;
1061                         }
1062                         if (++which > cells) {
1063                             state = -1;
1064                             goto finish;
1065                         }
1066                     }
1067                 }
1068                 if (*s == R_CURLY) {
1069                     state = 5;
1070                     goto finish;
1071                 } else if (*s == ',') {
1072                     ++s;
1073                 }
1074             }
1075             break;
1076         default:
1077             break;
1078         }
1079     }
1080   finish:
1081     if (state < 4) {
1082         debugmsg("...state was only %d", state);
1083         if (result) {
1084             result = free_pics_head(result);
1085         }
1086     } else {
1087         finish_c_values(result);
1088     }
1089     return result;
1090 }
1091
1092 static PICS_HEAD *
1093 parse_xpm(char **data)
1094 {
1095     int state = 0;
1096     PICS_HEAD *result;
1097     RGB_NAME *by_name;
1098     int n;
1099     int cells = 0;
1100     int cpp = 1;                /* chars per pixel */
1101     int num[6];
1102     int found;
1103     int which = 0;
1104     int num_colors = 0;
1105     char ch;
1106     const char *cs;
1107     char *s;
1108     char buf[BUFSIZ];
1109     char arg1[BUFSIZ];
1110     char arg2[BUFSIZ];
1111     char arg3[BUFSIZ];
1112     char **list = 0;
1113
1114     debugmsg("called parse_xpm");
1115
1116     result = typeCalloc(PICS_HEAD, 1);
1117     how_much.head += sizeof(PICS_HEAD);
1118
1119     for (n = 0; data[n] != 0; ++n) {
1120         if (strlen(s = data[n]) >= sizeof(buf) - 1)
1121             continue;
1122         switch (state) {
1123         case 0:
1124             if (match_c(s, " /* XPM */ ")) {
1125                 state = 1;
1126             }
1127             break;
1128         case 1:
1129             if (match_c(s, " static char * %s [] = %c ", arg1, &ch) &&
1130                 ch == L_CURLY) {
1131                 result->name = strdup(arg1);
1132                 state = 2;
1133             }
1134             break;
1135         case 2:
1136             if (match_c(s, " \" %d %d %d %d \" , ",
1137                         num + 0, num + 1, num + 2, num + 3) ||
1138                 match_c(s, " \" %d %d %d %d %d %d \" , ",
1139                         num + 0, num + 1, num + 2, num + 3, num + 4, num + 5)) {
1140                 result->wide = (short) num[0];
1141                 result->high = (short) num[1];
1142                 result->colors = num[2];
1143
1144                 begin_c_values(num[2]);
1145
1146                 cells = (result->wide * result->high);
1147
1148                 result->cells = typeCalloc(PICS_CELL, cells);
1149                 how_much.cell += sizeof(PICS_CELL) * (size_t) cells;
1150
1151                 list = typeCalloc(char *, result->colors + 1);
1152                 how_much.list += sizeof(char *) * (size_t) (result->colors + 1);
1153
1154                 cpp = num[3];
1155                 state = 3;
1156             }
1157             break;
1158         case 3:
1159             if (!match_colors(s, cpp, arg1, arg2, arg3)) {
1160                 break;
1161             }
1162             num_colors++;
1163             free(list[reading_last]);
1164             list[reading_last] = strdup(arg1);
1165             if ((by_name = lookup_rgb(arg3)) != 0) {
1166                 found = gather_c_values(by_name->value);
1167             } else if (*arg3 == '#') {
1168                 char *rgb = arg3 + 1;
1169                 unsigned long value = strtoul(rgb, &s, 16);
1170                 switch ((int) strlen(rgb)) {
1171                 case 6:
1172                     break;
1173                 case 12:
1174                     value = (((value >> 24) & 0xff0000L)
1175                              | ((value >> 16) & 0xff00L)
1176                              | ((value >> 8) & 0xffL));
1177                     break;
1178                 default:
1179                     warning("unexpected rgb value %s", rgb);
1180                     break;
1181                 }
1182                 found = gather_c_values((int) value);
1183             } else {
1184                 found = gather_c_values(0);     /* actually an error */
1185             }
1186             debugmsg("  [%d:%d] %06X", num_colors, result->colors,
1187                      reading_ncols[(found >= 0) ? found : 0].fgcol);
1188             if (num_colors >= result->colors) {
1189                 finish_c_values(result);
1190                 state = 4;
1191                 if (list != 0 && list[0] == 0)
1192                     list[0] = strdup("\033");
1193             }
1194             break;
1195         case 4:
1196             if (*(cs = skip_cs(s)) == '"') {
1197                 ++cs;
1198                 while (*cs != '\0' && *cs != '"') {
1199                     int c;
1200
1201                     /* FIXME - factor out */
1202                     for (c = 0; c < result->colors; ++c) {
1203                         if (list[c] == 0) {
1204                             /* should not happen... */
1205                             continue;
1206                         }
1207                         if (!strncmp(cs, list[c], (size_t) cpp)) {
1208                             result->cells[which].ch = list[c][0];
1209                             result->cells[which].fg = c;
1210                             result->fgcol[c].count++;
1211                             break;
1212                         }
1213                     }
1214
1215                     if (result->cells[which].ch == 0) {
1216                         result->cells[which].ch = '?';
1217                         result->cells[which].fg = 0;
1218                     }
1219
1220                     if (++which >= cells) {
1221                         state = 5;
1222                         break;
1223                     }
1224                     for (c = cpp; c > 0; --c, ++cs) {
1225                         if (*cs == '\0')
1226                             break;
1227                     }
1228                 }
1229             }
1230             break;
1231         }
1232     }
1233
1234     if (result && list) {
1235         for (n = 0; n < result->colors; ++n)
1236             free(list[n]);
1237         free(list);
1238     }
1239
1240     if (state < 5) {
1241         debugmsg("...state was only %d", state);
1242         result = free_pics_head(result);
1243     }
1244
1245     if (result) {
1246         debugmsg("...allocated %d colors", result->colors);
1247     }
1248
1249     return result;
1250 }
1251
1252 /*
1253  * The obscurely-named "convert" is provided by ImageMagick
1254  */
1255 static PICS_HEAD *
1256 parse_img(const char *filename)
1257 {
1258     char *cmd = malloc(strlen(filename) + 256);
1259     FILE *pp;
1260     char buffer[BUFSIZ];
1261     char dummy[BUFSIZ];
1262     bool okay = TRUE;
1263     PICS_HEAD *result;
1264     int pic_x = 0;
1265     int pic_y = 0;
1266     int width = in_curses ? COLS : 80;
1267
1268     sprintf(cmd, "identify \"%s\"", filename);
1269     if (quiet)
1270         strcat(cmd, " 2>/dev/null");
1271
1272     logmsg("...opening pipe to %s", cmd);
1273
1274     result = typeCalloc(PICS_HEAD, 1);
1275     how_much.head += sizeof(PICS_HEAD);
1276
1277     if ((pp = popen(cmd, "r")) != 0) {
1278         if (fgets(buffer, sizeof(buffer), pp) != 0) {
1279             size_t n = strlen(filename);
1280             debugmsg2("...read %s", buffer);
1281             if (strlen(buffer) > n &&
1282                 !strncmp(buffer, filename, n) &&
1283                 isspace(UChar(buffer[n])) &&
1284                 sscanf(skip_word(buffer + n), " %dx%d ", &pic_x, &pic_y) == 2) {
1285                 /* distort image to make it show normally on terminal */
1286                 pic_x = (int) ((double) pic_x / aspect_ratio);
1287             } else {
1288                 pic_x = pic_y = 0;
1289             }
1290         }
1291         pclose(pp);
1292     }
1293     if (pic_x <= 0 || pic_y <= 0)
1294         goto finish;
1295
1296     sprintf(cmd, "convert " "-resize %dx%d\\! " "-thumbnail %dx \"%s\" "
1297             "-define txt:compliance=SVG txt:-",
1298             pic_x, pic_y, width, filename);
1299     if (quiet)
1300         strcat(cmd, " 2>/dev/null");
1301
1302     logmsg("...opening pipe to %s", cmd);
1303     if ((pp = popen(cmd, "r")) != 0) {
1304         int count = 0;
1305         int col = 0;
1306         int row = 0;
1307         int len = 0;
1308         while (fgets(buffer, sizeof(buffer), pp) != 0) {
1309             debugmsg2("[%5d] %s", count + 1, buffer);
1310             if (strlen(buffer) > 160) {         /* 80 columns would be enough */
1311                 okay = FALSE;
1312                 break;
1313             }
1314             if (count++ == 0) {
1315                 if (match_c(buffer,
1316                             "# ImageMagick pixel enumeration: %d,%d,%d,%s ",
1317                             &col, &row, &len, dummy)) {
1318                     result->name = strdup(filename);
1319                     result->wide = (short) col;
1320                     result->high = (short) row;
1321
1322                     begin_c_values(256);
1323
1324                     result->cells = typeCalloc(PICS_CELL, (size_t) (col * row));
1325                     how_much.cell += (sizeof(PICS_CELL) * (size_t) (col * row));
1326                 } else {
1327                     okay = FALSE;
1328                     break;
1329                 }
1330             } else {
1331                 /* subsequent lines begin "col,row: (r,g,b,a) #RGB" */
1332                 int r, g, b, nocolor;
1333                 unsigned check;
1334                 int which, c;
1335                 char *t;
1336                 char *s = t = strchr(buffer, '#');
1337                 if (s != 0) {
1338                     /* after the "#RGB", there are differences - just ignore */
1339                     while (*s != '\0' && !isspace(UChar(*s)))
1340                         ++s;
1341                     *++s = '\0';
1342                 }
1343                 if (match_c(buffer,
1344                             "%d,%d: (%d,%d,%d,%d) #%x ",
1345                             &col, &row,
1346                             &r, &g, &b, &nocolor,
1347                             &check)) {
1348                     if ((s - t) > 8)    /* 6 hex digits vs 8 */
1349                         check /= 256;
1350                     if (r > 255 ||
1351                         g > 255 ||
1352                         b > 255 ||
1353                         check != (unsigned) ((r << 16) | (g << 8) | b)) {
1354                         okay = FALSE;
1355                         break;
1356                     }
1357                     c = gather_c_values((int) check);
1358                     which = col + (row * result->wide);
1359                     result->cells[which].ch = ((in_curses ||
1360                                                 check == 0xffffff)
1361                                                ? ' '
1362                                                : '#');
1363                     if (c >= 0 && c < reading_last) {
1364                         result->cells[which].fg = c;
1365                         reading_ncols[c].count++;
1366                     } else {
1367                         result->cells[which].fg = -1;
1368                     }
1369                 } else {
1370                     okay = FALSE;
1371                     break;
1372                 }
1373             }
1374         }
1375         finish_c_values(result);
1376         pclose(pp);
1377         if (okay) {
1378             /* FIXME - is this trimming needed? */
1379             for (len = result->colors; len > 3; len--) {
1380                 if (result->fgcol[len - 1].fgcol == 0) {
1381                     result->colors = len - 1;
1382                 } else {
1383                     break;
1384                 }
1385             }
1386         }
1387     }
1388   finish:
1389     free(cmd);
1390
1391     if (!okay) {
1392         result = free_pics_head(result);
1393     }
1394
1395     return result;
1396 }
1397
1398 static PICS_HEAD *
1399 read_picture(const char *filename, char **data)
1400 {
1401     PICS_HEAD *pics;
1402     if ((pics = parse_xbm(data)) == 0) {
1403         dispose_c_values();
1404         if ((pics = parse_xpm(data)) == 0) {
1405             dispose_c_values();
1406             if ((pics = parse_img(filename)) == 0) {
1407                 dispose_c_values();
1408                 free_data(data);
1409                 warning("unexpected file-format for \"%s\"", filename);
1410             } else if (pics->high == 0 || pics->wide == 0) {
1411                 dispose_c_values();
1412                 free_data(data);
1413                 pics = free_pics_head(pics);
1414                 warning("no picture found in \"%s\"", filename);
1415             }
1416         }
1417     }
1418     return pics;
1419 }
1420
1421 #define fg_color(pics,n) (pics->fgcol[n].fgcol)
1422
1423 static void
1424 dump_picture(PICS_HEAD * pics)
1425 {
1426     int y, x;
1427
1428     printf("Name %s\n", pics->name);
1429     printf("Size %dx%d\n", pics->high, pics->wide);
1430     printf("Color\n");
1431     for (y = 0; y < pics->colors; ++y) {
1432         if (fg_color(pics, y) < 0) {
1433             printf(" %3d: %d\n", y, fg_color(pics, y));
1434         } else {
1435             printf(" %3d: #%06x\n", y, fg_color(pics, y));
1436         }
1437     }
1438     for (y = 0; y < pics->high; ++y) {
1439         for (x = 0; x < pics->wide; ++x) {
1440             putchar(pics->cells[y * pics->wide + x].ch);
1441         }
1442         putchar('\n');
1443     }
1444 }
1445
1446 #ifndef USE_DISPLAY_DRIVER
1447 static void
1448 init_display(const char *palette_path, int opt_d)
1449 {
1450     if (isatty(fileno(stdout))) {
1451         in_curses = TRUE;
1452         initscr();
1453         cbreak();
1454         noecho();
1455         curs_set(0);
1456         if (has_colors()) {
1457             start_color();
1458 #if HAVE_USE_DEFAULT_COLORS
1459             if (opt_d)
1460                 use_default_colors();
1461 #endif
1462             init_palette(palette_path);
1463         }
1464         scrollok(stdscr, FALSE);
1465         exit_curses();
1466     }
1467 }
1468
1469 static void
1470 show_picture(PICS_HEAD * pics)
1471 {
1472     int y, x;
1473     int n;
1474     int my_pair, my_color;
1475
1476     debugmsg("called show_picture");
1477     logmsg("...using %dx%d screen", LINES, COLS);
1478 #if USE_EXTENDED_COLORS
1479     reset_color_pairs();
1480 #elif HAVE_CURSCR
1481     wclear(curscr);
1482     clear();
1483 #endif
1484     if (has_colors()) {
1485         logmsg("...using %d colors", pics->colors);
1486         for (n = 0; n < pics->colors; ++n) {
1487             my_pair = (n + 1);
1488             my_color = map_color(fg_color(pics, n));
1489 #if USE_EXTENDED_COLORS
1490             if (use_extended_pairs) {
1491                 init_extended_pair(my_pair, my_color, my_color);
1492             } else
1493 #endif
1494             {
1495                 my_pair &= 0x7fff;
1496                 my_color &= 0x7fff;
1497                 init_pair((short) my_pair, (short) my_color, (short) my_color);
1498             }
1499         }
1500         attrset(COLOR_PAIR(1));
1501         erase();
1502     }
1503     for (y = 0; y < pics->high; ++y) {
1504         if (y >= LINES)
1505             break;
1506         move(y, 0);
1507         for (x = 0; x < pics->wide; ++x) {
1508             if (x >= COLS)
1509                 break;
1510             n = (y * pics->wide + x);
1511             my_pair = pics->cells[n].fg + 1;
1512 #if USE_EXTENDED_COLORS
1513             if (use_extended_pairs) {
1514                 cchar_t temp;
1515                 wchar_t wch[2];
1516                 wch[0] = (wchar_t) pics->cells[n].ch;
1517                 wch[1] = 0;
1518                 setcchar(&temp, wch, A_NORMAL, (short) my_pair, &my_pair);
1519                 add_wch(&temp);
1520             } else
1521 #endif
1522             {
1523                 attrset(COLOR_PAIR(my_pair));
1524                 addch((chtype) pics->cells[n].ch);
1525             }
1526         }
1527     }
1528     if (slow_time >= 0) {
1529         refresh();
1530         if (slow_time > 0) {
1531 #ifdef NCURSES_VERSION
1532             napms(1000 * slow_time);
1533 #else
1534             sleep((unsigned) slow_time);
1535 #endif
1536         }
1537     } else {
1538         wmove(stdscr, 0, 0);
1539         getch();
1540     }
1541     if (!quiet)
1542         endwin();
1543 }
1544 #endif
1545
1546 static int
1547 compare_fg_counts(const void *a, const void *b)
1548 {
1549     const FG_NODE *p = (const FG_NODE *) a;
1550     const FG_NODE *q = (const FG_NODE *) b;
1551     return (q->count - p->count);
1552 }
1553
1554 static void
1555 report_colors(PICS_HEAD * pics)
1556 {
1557     int j, k;
1558     int high;
1559     int wide = 4;
1560     int accum;
1561     double level;
1562     int shift;
1563     int total;
1564     char buffer[256];
1565
1566     if (logfp == 0)
1567         return;
1568
1569     qsort(pics->fgcol, (size_t) pics->colors, sizeof(FG_NODE), compare_fg_counts);
1570     /*
1571      * For debugging, show a (short) list of the colors used.
1572      */
1573     if (debugging && (pics->colors < 1000)) {
1574         int digits = 0;
1575         for (j = pics->colors; j != 0; j /= 10) {
1576             ++digits;
1577             if (j < 10)
1578                 ++digits;
1579         }
1580         logmsg("These colors were used:");
1581         high = (pics->colors + wide - 1) / wide;
1582         for (j = 0; j < high && j < pics->colors; ++j) {
1583             char *s = buffer;
1584             *s = '\0';
1585             for (k = 0; k < wide; ++k) {
1586                 int n = j + (k * high);
1587                 if (n >= pics->colors)
1588                     break;
1589                 if (k) {
1590                     *s++ = ' ';
1591                     if (digits < 8) {
1592                         sprintf(s, "%*s", 8 - digits, " ");
1593                         s += strlen(s);
1594                     }
1595                 }
1596                 if (pics->fgcol[n].fgcol >= 0) {
1597                     sprintf(s, "%3d #%06X %*d", n,
1598                             pics->fgcol[n].fgcol,
1599                             digits, pics->fgcol[n].count);
1600                 } else {
1601                     sprintf(s, "%3d (empty) %*d", n,
1602                             digits, pics->fgcol[n].count);
1603                 }
1604                 s += strlen(s);
1605                 if ((s - buffer) > 100)
1606                     break;
1607             }
1608             logmsg("%s", buffer);
1609         }
1610     }
1611
1612     /*
1613      * Given the list of colors sorted by the number of times they are used,
1614      * log a short report showing the number of colors for 90%, 99%, 99.9%,
1615      * etc.
1616      */
1617     logmsg("Number of colors versus number of cells");
1618     total = pics->high * pics->wide;
1619     accum = 0;
1620     level = 0.1;
1621     shift = 1;
1622     for (j = 0; j < pics->colors; ++j) {
1623         accum += pics->fgcol[j].count;
1624         if (accum >= (total * (1.0 - level))) {
1625             int after = (shift > 2) ? shift - 2 : 0;
1626             logmsg("%8d colors (%.1f%%) in %d cells (%.*f%%)",
1627                    j + 1,
1628                    (100.0 * (j + 1)) / pics->colors,
1629                    accum,
1630                    after, (100.0 * accum) / total);
1631             if (accum >= total)
1632                 break;
1633             level /= 10.0;
1634             shift++;
1635         }
1636     }
1637 }
1638
1639 int
1640 main(int argc, char *argv[])
1641 {
1642     int n;
1643     int opt_d = FALSE;
1644     char ignore_ch;
1645     const char *palette_path = 0;
1646     const char *rgb_path = RGB_PATH;
1647
1648     while ((n = getopt(argc, argv, "a:dLl:p:qr:s:x:")) != -1) {
1649         switch (n) {
1650         case 'a':
1651             if (sscanf(optarg, "%lf%c", &aspect_ratio, &ignore_ch) != 1
1652                 || aspect_ratio < 0.1
1653                 || aspect_ratio > 10.) {
1654                 fprintf(stderr, "Expected a number in [0.1 to 10.]: %s\n", optarg);
1655                 usage();
1656             }
1657             break;
1658 #if HAVE_USE_DEFAULT_COLORS
1659         case 'd':
1660             opt_d = TRUE;
1661             break;
1662 #endif
1663         case 'L':
1664             debugging = TRUE;
1665             break;
1666         case 'l':
1667             if ((logfp = fopen(optarg, "a")) == 0)
1668                 failed(optarg);
1669             break;
1670         case 'p':
1671             palette_path = optarg;
1672             break;
1673         case 'q':
1674             quiet = TRUE;
1675             break;
1676         case 'r':
1677             rgb_path = optarg;
1678             break;
1679         case 's':
1680             slow_time = atoi(optarg);
1681             break;
1682 #if USE_EXTENDED_COLORS
1683         case 'x':
1684             {
1685                 char *s = optarg;
1686                 while (*s) {
1687                     switch (*s++) {
1688                     case 'p':
1689                         use_extended_pairs = TRUE;
1690                         break;
1691                     case 'c':
1692                         use_extended_colors = TRUE;
1693                         break;
1694                     default:
1695                         usage();
1696                         break;
1697                     }
1698                 }
1699             }
1700             break;
1701 #endif
1702         default:
1703             usage();
1704             break;
1705         }
1706     }
1707
1708     if (optind < argc) {
1709         char **rgb_data = read_file(rgb_path);
1710
1711         if (rgb_data)
1712             rgb_table = parse_rgb(rgb_data);
1713
1714         init_display(palette_path, opt_d);
1715         if (optind >= argc)
1716             giveup("expected at least one image filename");
1717
1718         for (n = optind; n < argc; ++n) {
1719             PICS_HEAD *pics;
1720             char **data = read_file(argv[n]);
1721
1722             if (data == 0) {
1723                 warning("cannot read \"%s\"", argv[n]);
1724                 continue;
1725             }
1726             if ((pics = read_picture(argv[n], data)) != 0) {
1727                 if (in_curses) {
1728                     show_picture(pics);
1729                 } else {
1730                     dump_picture(pics);
1731                 }
1732                 report_colors(pics);
1733                 dispose_c_values();
1734                 free_data(data);
1735                 free_pics_head(pics);
1736             }
1737         }
1738         free_data(rgb_data);
1739         free(rgb_table);
1740         free(all_colors);
1741     } else {
1742         usage();
1743     }
1744
1745     cleanup(EXIT_SUCCESS);
1746 }