specialize getopt for FLAC
[platform/upstream/flac.git] / src / metaflac / main.c
1 /* metaflac - Command-line FLAC metadata editor
2  * Copyright (C) 2001,2002  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 /*@@@
20 more powerful operations yet to add:
21         add a seektable, using same args as flac
22 */
23
24 #if HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include "FLAC/assert.h"
29 #include "FLAC/metadata.h"
30 #include <ctype.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #if 0
37 /*[JEC] was:#if HAVE_GETOPT_LONG*/
38 /*[JEC] see flac/include/share/getopt.h as to why the change */
39 #  include <getopt.h>
40 #else
41 #  include "share/getopt.h"
42 #endif
43
44 /*
45    FLAC__share__getopt format struct; note we don't use short options so we just
46    set the 'val' field to 0 everywhere to indicate a valid option.
47 */
48 static struct FLAC__share__option long_options_[] = {
49         /* global options */
50     { "preserve-modtime", 0, 0, 0 },
51     { "with-filename", 0, 0, 0 },
52     { "no-filename", 0, 0, 0 },
53     { "dont-use-padding", 0, 0, 0 },
54         /* shorthand operations */
55     { "show-md5sum", 0, 0, 0 },
56     { "show-min-blocksize", 0, 0, 0 },
57     { "show-max-blocksize", 0, 0, 0 },
58     { "show-min-framesize", 0, 0, 0 },
59     { "show-max-framesize", 0, 0, 0 },
60     { "show-sample-rate", 0, 0, 0 },
61     { "show-channels", 0, 0, 0 },
62     { "show-bps", 0, 0, 0 },
63     { "show-total-samples", 0, 0, 0 },
64     { "show-vc-vendor", 0, 0, 0 },
65     { "show-vc-field", 1, 0, 0 },
66     { "remove-vc-all", 0, 0, 0 },
67     { "remove-vc-field", 1, 0, 0 },
68     { "remove-vc-firstfield", 1, 0, 0 },
69     { "set-vc-field", 1, 0, 0 },
70     { "add-padding", 1, 0, 0 },
71         /* major operations */
72     { "help", 0, 0, 0 },
73     { "list", 0, 0, 0 },
74     { "append", 0, 0, 0 },
75     { "remove", 0, 0, 0 },
76     { "remove-all", 0, 0, 0 },
77     { "merge-padding", 0, 0, 0 },
78     { "sort-padding", 0, 0, 0 },
79         /* major operation arguments */
80     { "block-number", 1, 0, 0 },
81     { "block-type", 1, 0, 0 },
82     { "except-block-type", 1, 0, 0 },
83     { "data-format", 1, 0, 0 },
84     { "application-data-format", 1, 0, 0 },
85     { "from-file", 1, 0, 0 },
86     {0, 0, 0, 0}
87 };
88
89 typedef enum {
90         OP__SHOW_MD5SUM,
91         OP__SHOW_MIN_BLOCKSIZE,
92         OP__SHOW_MAX_BLOCKSIZE,
93         OP__SHOW_MIN_FRAMESIZE,
94         OP__SHOW_MAX_FRAMESIZE,
95         OP__SHOW_SAMPLE_RATE,
96         OP__SHOW_CHANNELS,
97         OP__SHOW_BPS,
98         OP__SHOW_TOTAL_SAMPLES,
99         OP__SHOW_VC_VENDOR,
100         OP__SHOW_VC_FIELD,
101         OP__REMOVE_VC_ALL,
102         OP__REMOVE_VC_FIELD,
103         OP__REMOVE_VC_FIRSTFIELD,
104         OP__SET_VC_FIELD,
105         OP__ADD_PADDING,
106         OP__LIST,
107         OP__APPEND,
108         OP__REMOVE,
109         OP__REMOVE_ALL,
110         OP__MERGE_PADDING,
111         OP__SORT_PADDING
112 } OperationType;
113
114 typedef enum {
115         ARG__BLOCK_NUMBER,
116         ARG__BLOCK_TYPE,
117         ARG__EXCEPT_BLOCK_TYPE,
118         ARG__DATA_FORMAT,
119         ARG__FROM_FILE
120 } ArgumentType;
121
122 typedef struct {
123         char *field_name;
124 } Argument_VcFieldName;
125
126 typedef struct {
127         char *field; /* the whole field as passed on the command line, i.e. "NAME=VALUE" */
128         char *field_name;
129         /* according to the vorbis spec, field values can contain \0 so simple C strings are not enough here */
130         unsigned field_value_length;
131         char *field_value;
132 } Argument_VcField;
133
134 typedef struct {
135         unsigned num_entries;
136         unsigned *entries;
137 } Argument_BlockNumber;
138
139 typedef struct {
140         FLAC__MetadataType type;
141         char application_id[4]; /* only relevant if type == FLAC__STREAM_METADATA_TYPE_APPLICATION */
142         FLAC__bool filter_application_by_id;
143 } Argument_BlockTypeEntry;
144
145 typedef struct {
146         unsigned num_entries;
147         Argument_BlockTypeEntry *entries;
148 } Argument_BlockType;
149
150 typedef struct {
151         FLAC__bool is_binary;
152 } Argument_DataFormat;
153
154 typedef struct {
155         char *file_name;
156 } Argument_FromFile;
157
158 typedef struct {
159         unsigned length;
160 } Argument_AddPadding;
161
162 typedef struct {
163         OperationType type;
164         union {
165                 Argument_VcFieldName show_vc_field;
166                 Argument_VcFieldName remove_vc_field;
167                 Argument_VcFieldName remove_vc_firstfield;
168                 Argument_VcField set_vc_field;
169                 Argument_AddPadding add_padding;
170         } argument;
171 } Operation;
172
173 typedef struct {
174         ArgumentType type;
175         union {
176                 Argument_BlockNumber block_number;
177                 Argument_BlockType block_type;
178                 Argument_DataFormat data_format;
179                 Argument_FromFile from_file;
180         } value;
181 } Argument;
182
183 typedef struct {
184         FLAC__bool preserve_modtime;
185         FLAC__bool prefix_with_filename;
186         FLAC__bool use_padding;
187         FLAC__bool show_long_help;
188         FLAC__bool application_data_format_is_hexdump;
189         struct {
190                 Operation *operations;
191                 unsigned num_operations;
192                 unsigned capacity;
193         } ops;
194         struct {
195                 struct {
196                         unsigned num_shorthand_ops;
197                         unsigned num_major_ops;
198                         FLAC__bool has_block_type;
199                         FLAC__bool has_except_block_type;
200                 } checks;
201                 Argument *arguments;
202                 unsigned num_arguments;
203                 unsigned capacity;
204         } args;
205         unsigned num_files;
206         char **filenames;
207 } CommandLineOptions;
208
209 static void die(const char *message);
210 static void init_options(CommandLineOptions *options);
211 static FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options);
212 static FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options);
213 static void free_options(CommandLineOptions *options);
214 static void append_new_operation(CommandLineOptions *options, Operation operation);
215 static void append_new_argument(CommandLineOptions *options, Argument argument);
216 static Operation *append_major_operation(CommandLineOptions *options, OperationType type);
217 static Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type);
218 static Argument *append_argument(CommandLineOptions *options, ArgumentType type);
219 static int short_usage(const char *message, ...);
220 static int long_usage(const char *message, ...);
221 static char *local_strdup(const char *source);
222 static FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length);
223 static FLAC__bool parse_add_padding(const char *in, unsigned *out);
224 static FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out);
225 static FLAC__bool parse_block_type(const char *in, Argument_BlockType *out);
226 static FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out);
227 static FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out);
228 static FLAC__bool do_operations(const CommandLineOptions *options);
229 static FLAC__bool do_major_operation(const CommandLineOptions *options);
230 static FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options);
231 static FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
232 static FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
233 static FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
234 static FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
235 static FLAC__bool do_shorthand_operations(const CommandLineOptions *options);
236 static FLAC__bool do_shorthand_operations_on_file(const char *fielname, const CommandLineOptions *options);
237 static FLAC__bool do_shorthand_operation(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write);
238 static FLAC__bool do_shorthand_operation__add_padding(FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write);
239 static FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__Metadata_Chain *chain, OperationType op);
240 static FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write);
241 static FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number);
242 static void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool hexdump_application);
243 static void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry);
244 static void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries);
245 static FLAC__bool remove_vc_all(FLAC__StreamMetadata *block, FLAC__bool *needs_write);
246 static FLAC__bool remove_vc_field(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write);
247 static FLAC__bool remove_vc_firstfield(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write);
248 static FLAC__bool set_vc_field(FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write);
249 static FLAC__bool field_name_matches_entry(const char *field_name, unsigned field_name_length, const FLAC__StreamMetadata_VorbisComment_Entry *entry);
250 static void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent);
251
252 int main(int argc, char *argv[])
253 {
254         CommandLineOptions options;
255         int ret = 0;
256
257         init_options(&options);
258
259         if(parse_options(argc, argv, &options))
260                 ret = !do_operations(&options);
261
262         free_options(&options);
263
264         return ret;
265 }
266
267 void die(const char *message)
268 {
269         FLAC__ASSERT(0 != message);
270         fprintf(stderr, "ERROR: %s\n", message);
271         exit(1);
272 }
273
274 void init_options(CommandLineOptions *options)
275 {
276         options->preserve_modtime = false;
277
278         /* '2' is hack to mean "use default if not forced on command line" */
279         FLAC__ASSERT(true != 2);
280         options->prefix_with_filename = 2;
281
282         options->use_padding = true;
283         options->show_long_help = false;
284         options->application_data_format_is_hexdump = false;
285
286         options->ops.operations = 0;
287         options->ops.num_operations = 0;
288         options->ops.capacity = 0;
289
290         options->args.arguments = 0;
291         options->args.num_arguments = 0;
292         options->args.capacity = 0;
293
294         options->args.checks.num_shorthand_ops = 0;
295         options->args.checks.num_major_ops = 0;
296         options->args.checks.has_block_type = false;
297         options->args.checks.has_except_block_type = false;
298
299         options->num_files = 0;
300         options->filenames = 0;
301 }
302
303 FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options)
304 {
305     int ret;
306     int option_index = 1;
307         FLAC__bool had_error = false;
308
309     while ((ret = FLAC__share__getopt_long(argc, argv, "", long_options_, &option_index)) != -1) {
310         switch (ret) {
311             case 0:
312                                 had_error |= !parse_option(option_index, FLAC__share__optarg, options);
313                 break;
314                         case '?':
315                         case ':':
316                 had_error = true;
317                 break;
318             default:
319                                 FLAC__ASSERT(0);
320                                 break;
321         }
322     }
323
324         if(options->prefix_with_filename == 2)
325                 options->prefix_with_filename = (argc - FLAC__share__optind > 1);
326
327         if(FLAC__share__optind >= argc && !options->show_long_help) {
328                 fprintf(stderr,"ERROR: you must specify at least one FLAC file;\n");
329                 fprintf(stderr,"       metaflac cannot be used as a pipe\n");
330                 had_error = true;
331         }
332
333         options->num_files = argc - FLAC__share__optind;
334
335         if(options->num_files > 0) {
336                 unsigned i = 0;
337                 if(0 == (options->filenames = malloc(sizeof(char *) * options->num_files)))
338                         die("out of memory allocating space for file names list");
339                 while(FLAC__share__optind < argc)
340                         options->filenames[i++] = local_strdup(argv[FLAC__share__optind++]);
341         }
342
343         if(options->args.checks.num_major_ops > 0) {
344                 if(options->args.checks.num_major_ops > 1) {
345                         fprintf(stderr, "ERROR: you may only specify one major operation at a time\n");
346                         had_error = true;
347                 }
348                 else if(options->args.checks.num_shorthand_ops > 0) {
349                         fprintf(stderr, "ERROR: you may not mix shorthand and major operations\n");
350                         had_error = true;
351                 }
352         }
353
354         if(options->args.checks.has_block_type && options->args.checks.has_except_block_type) {
355                 fprintf(stderr, "ERROR: you may not specify both '--block-type' and '--except-block-type'\n");
356                 had_error = true;
357         }
358
359         if(had_error)
360                 short_usage(0);
361
362         return !had_error;
363 }
364
365 FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options)
366 {
367         const char *opt = long_options_[option_index].name;
368         Operation *op;
369         Argument *arg;
370         FLAC__bool ok = true;
371
372     if(0 == strcmp(opt, "preserve-modtime")) {
373                 options->preserve_modtime = true;
374         }
375     else if(0 == strcmp(opt, "with-filename")) {
376                 options->prefix_with_filename = true;
377         }
378     else if(0 == strcmp(opt, "no-filename")) {
379                 options->prefix_with_filename = false;
380         }
381     else if(0 == strcmp(opt, "dont-use-padding")) {
382                 options->use_padding = false;
383         }
384     else if(0 == strcmp(opt, "show-md5sum")) {
385                 (void) append_shorthand_operation(options, OP__SHOW_MD5SUM);
386         }
387     else if(0 == strcmp(opt, "show-min-blocksize")) {
388                 (void) append_shorthand_operation(options, OP__SHOW_MIN_BLOCKSIZE);
389         }
390     else if(0 == strcmp(opt, "show-max-blocksize")) {
391                 (void) append_shorthand_operation(options, OP__SHOW_MAX_BLOCKSIZE);
392         }
393     else if(0 == strcmp(opt, "show-min-framesize")) {
394                 (void) append_shorthand_operation(options, OP__SHOW_MIN_FRAMESIZE);
395         }
396     else if(0 == strcmp(opt, "show-max-framesize")) {
397                 (void) append_shorthand_operation(options, OP__SHOW_MAX_FRAMESIZE);
398         }
399     else if(0 == strcmp(opt, "show-sample-rate")) {
400                 (void) append_shorthand_operation(options, OP__SHOW_SAMPLE_RATE);
401         }
402     else if(0 == strcmp(opt, "show-channels")) {
403                 (void) append_shorthand_operation(options, OP__SHOW_CHANNELS);
404         }
405     else if(0 == strcmp(opt, "show-bps")) {
406                 (void) append_shorthand_operation(options, OP__SHOW_BPS);
407         }
408     else if(0 == strcmp(opt, "show-total-samples")) {
409                 (void) append_shorthand_operation(options, OP__SHOW_TOTAL_SAMPLES);
410         }
411     else if(0 == strcmp(opt, "show-vc-vendor")) {
412                 (void) append_shorthand_operation(options, OP__SHOW_VC_VENDOR);
413         }
414     else if(0 == strcmp(opt, "show-vc-field")) {
415                 op = append_shorthand_operation(options, OP__SHOW_VC_FIELD);
416                 FLAC__ASSERT(0 != option_argument);
417                 op->argument.show_vc_field.field_name = local_strdup(option_argument);
418         }
419     else if(0 == strcmp(opt, "remove-vc-all")) {
420                 (void) append_shorthand_operation(options, OP__REMOVE_VC_ALL);
421         }
422     else if(0 == strcmp(opt, "remove-vc-field")) {
423                 op = append_shorthand_operation(options, OP__REMOVE_VC_FIELD);
424                 FLAC__ASSERT(0 != option_argument);
425                 op->argument.remove_vc_field.field_name = local_strdup(option_argument);
426         }
427     else if(0 == strcmp(opt, "remove-vc-firstfield")) {
428                 op = append_shorthand_operation(options, OP__REMOVE_VC_FIRSTFIELD);
429                 FLAC__ASSERT(0 != option_argument);
430                 op->argument.remove_vc_firstfield.field_name = local_strdup(option_argument);
431         }
432     else if(0 == strcmp(opt, "set-vc-field")) {
433                 op = append_shorthand_operation(options, OP__SET_VC_FIELD);
434                 FLAC__ASSERT(0 != option_argument);
435                 if(!parse_vorbis_comment_field(option_argument, &(op->argument.set_vc_field.field), &(op->argument.set_vc_field.field_name), &(op->argument.set_vc_field.field_value), &(op->argument.set_vc_field.field_value_length))) {
436                         fprintf(stderr, "ERROR: malformed vorbis comment field \"%s\"\n", option_argument);
437                         ok = false;
438                 }
439         }
440     else if(0 == strcmp(opt, "add-padding")) {
441                 op = append_shorthand_operation(options, OP__ADD_PADDING);
442                 FLAC__ASSERT(0 != option_argument);
443                 if(!parse_add_padding(option_argument, &(op->argument.add_padding.length))) {
444                         fprintf(stderr, "ERROR: illegal length \"%s\", length must be >= 0 and < 2^%u\n", option_argument, FLAC__STREAM_METADATA_LENGTH_LEN);
445                         ok = false;
446                 }
447         }
448     else if(0 == strcmp(opt, "help")) {
449                 options->show_long_help = true;
450         }
451     else if(0 == strcmp(opt, "list")) {
452                 (void) append_major_operation(options, OP__LIST);
453         }
454     else if(0 == strcmp(opt, "append")) {
455                 (void) append_major_operation(options, OP__APPEND);
456         }
457     else if(0 == strcmp(opt, "remove")) {
458                 (void) append_major_operation(options, OP__REMOVE);
459         }
460     else if(0 == strcmp(opt, "remove-all")) {
461                 (void) append_major_operation(options, OP__REMOVE_ALL);
462         }
463     else if(0 == strcmp(opt, "merge-padding")) {
464                 (void) append_major_operation(options, OP__MERGE_PADDING);
465         }
466     else if(0 == strcmp(opt, "sort-padding")) {
467                 (void) append_major_operation(options, OP__SORT_PADDING);
468         }
469     else if(0 == strcmp(opt, "block-number")) {
470                 arg = append_argument(options, ARG__BLOCK_NUMBER);
471                 FLAC__ASSERT(0 != option_argument);
472                 if(!parse_block_number(option_argument, &(arg->value.block_number))) {
473                         fprintf(stderr, "ERROR: malformed block number specification \"%s\"\n", option_argument);
474                         ok = false;
475                 }
476         }
477     else if(0 == strcmp(opt, "block-type")) {
478                 arg = append_argument(options, ARG__BLOCK_TYPE);
479                 FLAC__ASSERT(0 != option_argument);
480                 if(!parse_block_type(option_argument, &(arg->value.block_type))) {
481                         fprintf(stderr, "ERROR: malformed block type specification \"%s\"\n", option_argument);
482                         ok = false;
483                 }
484                 options->args.checks.has_block_type = true;
485         }
486     else if(0 == strcmp(opt, "except-block-type")) {
487                 arg = append_argument(options, ARG__EXCEPT_BLOCK_TYPE);
488                 FLAC__ASSERT(0 != option_argument);
489                 if(!parse_block_type(option_argument, &(arg->value.block_type))) {
490                         fprintf(stderr, "ERROR: malformed block type specification \"%s\"\n", option_argument);
491                         ok = false;
492                 }
493                 options->args.checks.has_except_block_type = true;
494         }
495     else if(0 == strcmp(opt, "data-format")) {
496                 arg = append_argument(options, ARG__DATA_FORMAT);
497                 FLAC__ASSERT(0 != option_argument);
498                 if(!parse_data_format(option_argument, &(arg->value.data_format))) {
499                         fprintf(stderr, "ERROR: illegal data format \"%s\"\n", option_argument);
500                         ok = false;
501                 }
502         }
503     else if(0 == strcmp(opt, "application-data-format")) {
504                 FLAC__ASSERT(0 != option_argument);
505                 if(!parse_application_data_format(option_argument, &(options->application_data_format_is_hexdump))) {
506                         fprintf(stderr, "ERROR: illegal application data format \"%s\"\n", option_argument);
507                         ok = false;
508                 }
509         }
510     else if(0 == strcmp(opt, "from-file")) {
511                 arg = append_argument(options, ARG__FROM_FILE);
512                 FLAC__ASSERT(0 != option_argument);
513                 arg->value.from_file.file_name = local_strdup(option_argument);
514         }
515         else {
516                 FLAC__ASSERT(0);
517         }
518
519         return ok;
520 }
521
522 void free_options(CommandLineOptions *options)
523 {
524         unsigned i;
525         Operation *op;
526         Argument *arg;
527
528         FLAC__ASSERT(0 == options->ops.operations || options->ops.num_operations > 0);
529         FLAC__ASSERT(0 == options->args.arguments || options->args.num_arguments > 0);
530
531         for(i = 0, op = options->ops.operations; i < options->ops.num_operations; i++, op++) {
532                 switch(op->type) {
533                         case OP__SHOW_VC_FIELD:
534                         case OP__REMOVE_VC_FIELD:
535                         case OP__REMOVE_VC_FIRSTFIELD:
536                                 if(0 != op->argument.show_vc_field.field_name)
537                                         free(op->argument.show_vc_field.field_name);
538                                 break;
539                         case OP__SET_VC_FIELD:
540                                 if(0 != op->argument.set_vc_field.field)
541                                         free(op->argument.set_vc_field.field);
542                                 if(0 != op->argument.set_vc_field.field_name)
543                                         free(op->argument.set_vc_field.field_name);
544                                 if(0 != op->argument.set_vc_field.field_value)
545                                         free(op->argument.set_vc_field.field_value);
546                                 break;
547                         default:
548                                 break;
549                 }
550         }
551
552         for(i = 0, arg = options->args.arguments; i < options->args.num_arguments; i++, arg++) {
553                 switch(arg->type) {
554                         case ARG__BLOCK_NUMBER:
555                                 if(0 != arg->value.block_number.entries)
556                                         free(arg->value.block_number.entries);
557                                 break;
558                         case ARG__BLOCK_TYPE:
559                         case ARG__EXCEPT_BLOCK_TYPE:
560                                 if(0 != arg->value.block_type.entries)
561                                         free(arg->value.block_type.entries);
562                                 break;
563                         case ARG__FROM_FILE:
564                                 if(0 != arg->value.from_file.file_name)
565                                         free(arg->value.from_file.file_name);
566                                 break;
567                         default:
568                                 break;
569                 }
570         }
571
572         if(0 != options->ops.operations)
573                 free(options->ops.operations);
574
575         if(0 != options->args.arguments)
576                 free(options->args.arguments);
577
578         if(0 != options->filenames)
579                 free(options->filenames);
580 }
581
582 void append_new_operation(CommandLineOptions *options, Operation operation)
583 {
584         if(options->ops.capacity == 0) {
585                 options->ops.capacity = 50;
586                 if(0 == (options->ops.operations = malloc(sizeof(Operation) * options->ops.capacity)))
587                         die("out of memory allocating space for option list");
588                 memset(options->ops.operations, 0, sizeof(Operation) * options->ops.capacity);
589         }
590         if(options->ops.capacity <= options->ops.num_operations) {
591                 unsigned original_capacity = options->ops.capacity;
592                 options->ops.capacity *= 4;
593                 if(0 == (options->ops.operations = realloc(options->ops.operations, sizeof(Operation) * options->ops.capacity)))
594                         die("out of memory allocating space for option list");
595                 memset(options->ops.operations + original_capacity, 0, sizeof(Operation) * (options->ops.capacity - original_capacity));
596         }
597
598         options->ops.operations[options->ops.num_operations++] = operation;
599 }
600
601 void append_new_argument(CommandLineOptions *options, Argument argument)
602 {
603         if(options->args.capacity == 0) {
604                 options->args.capacity = 50;
605                 if(0 == (options->args.arguments = malloc(sizeof(Argument) * options->args.capacity)))
606                         die("out of memory allocating space for option list");
607                 memset(options->args.arguments, 0, sizeof(Argument) * options->args.capacity);
608         }
609         if(options->args.capacity <= options->args.num_arguments) {
610                 unsigned original_capacity = options->args.capacity;
611                 options->args.capacity *= 4;
612                 if(0 == (options->args.arguments = realloc(options->args.arguments, sizeof(Argument) * options->args.capacity)))
613                         die("out of memory allocating space for option list");
614                 memset(options->args.arguments + original_capacity, 0, sizeof(Argument) * (options->args.capacity - original_capacity));
615         }
616
617         options->args.arguments[options->args.num_arguments++] = argument;
618 }
619
620 Operation *append_major_operation(CommandLineOptions *options, OperationType type)
621 {
622         Operation op;
623         memset(&op, 0, sizeof(op));
624         op.type = type;
625         append_new_operation(options, op);
626         options->args.checks.num_major_ops++;
627         return options->ops.operations + (options->ops.num_operations - 1);
628 }
629
630 Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type)
631 {
632         Operation op;
633         memset(&op, 0, sizeof(op));
634         op.type = type;
635         append_new_operation(options, op);
636         options->args.checks.num_shorthand_ops++;
637         return options->ops.operations + (options->ops.num_operations - 1);
638 }
639
640 Argument *append_argument(CommandLineOptions *options, ArgumentType type)
641 {
642         Argument arg;
643         memset(&arg, 0, sizeof(arg));
644         arg.type = type;
645         append_new_argument(options, arg);
646         return options->args.arguments + (options->args.num_arguments - 1);
647 }
648
649 static void usage_header(FILE *out)
650 {
651         fprintf(out, "==============================================================================\n");
652         fprintf(out, "metaflac - Command-line FLAC metadata editor version %s\n", FLAC__VERSION_STRING);
653         fprintf(out, "Copyright (C) 2001,2002  Josh Coalson\n");
654         fprintf(out, "\n");
655         fprintf(out, "This program is free software; you can redistribute it and/or\n");
656         fprintf(out, "modify it under the terms of the GNU General Public License\n");
657         fprintf(out, "as published by the Free Software Foundation; either version 2\n");
658         fprintf(out, "of the License, or (at your option) any later version.\n");
659         fprintf(out, "\n");
660         fprintf(out, "This program is distributed in the hope that it will be useful,\n");
661         fprintf(out, "but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
662         fprintf(out, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
663         fprintf(out, "GNU General Public License for more details.\n");
664         fprintf(out, "\n");
665         fprintf(out, "You should have received a copy of the GNU General Public License\n");
666         fprintf(out, "along with this program; if not, write to the Free Software\n");
667         fprintf(out, "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n");
668         fprintf(out, "==============================================================================\n");
669 }
670
671 static void usage_summary(FILE *out)
672 {
673     fprintf(out, "Usage:\n");
674     fprintf(out, "  metaflac [options] [operations] FLACfile [FLACfile ...]\n");
675     fprintf(out, "\n");
676     fprintf(out, "Use metaflac to list, add, remove, or edit metadata in one or more FLAC files.\n");
677     fprintf(out, "You may perform one major operation, or many shorthand operations at a time.\n");
678     fprintf(out, "\n");
679     fprintf(out, "Options:\n");
680     fprintf(out, "--preserve-modtime    Preserve the original modification time in spite of edits\n");
681     fprintf(out, "--with-filename       Prefix each output line with the FLAC file name\n");
682     fprintf(out, "                      (the default if more than one FLAC file is specified)\n");
683     fprintf(out, "--no-filename         Do not prefix each output line with the FLAC file name\n");
684     fprintf(out, "                      (the default if only one FLAC file is specified)\n");
685     fprintf(out, "--dont-use-padding    By default metaflac tries to use padding where possible\n");
686     fprintf(out, "                      to avoid rewriting the entire file if the metadata size\n");
687     fprintf(out, "                      changes.  Use this option to tell metaflac to not take\n");
688     fprintf(out, "                      advantage of padding this way.\n");
689 }
690
691 int short_usage(const char *message, ...)
692 {
693         va_list args;
694
695         if(message) {
696                 va_start(args, message);
697
698                 (void) vfprintf(stderr, message, args);
699
700                 va_end(args);
701
702         }
703         usage_header(stderr);
704         fprintf(stderr, "\n");
705         fprintf(stderr, "This is the short help; for full help use 'metaflac --help'\n");
706         fprintf(stderr, "\n");
707         usage_summary(stderr);
708
709         return message? 1 : 0;
710 }
711
712 int long_usage(const char *message, ...)
713 {
714         FILE *out = (message? stderr : stdout);
715         va_list args;
716
717         if(message) {
718                 va_start(args, message);
719
720                 (void) vfprintf(stderr, message, args);
721
722                 va_end(args);
723
724         }
725         usage_header(out);
726     fprintf(out, "\n");
727         usage_summary(out);
728     fprintf(out, "\n");
729     fprintf(out, "Shorthand operations:\n");
730     fprintf(out, "--show-md5sum         Show the MD5 signature from the STREAMINFO block.\n");
731     fprintf(out, "--show-min-blocksize  Show the minimum block size from the STREAMINFO block.\n");
732     fprintf(out, "--show-max-blocksize  Show the maximum block size from the STREAMINFO block.\n");
733     fprintf(out, "--show-min-framesize  Show the minimum frame size from the STREAMINFO block.\n");
734     fprintf(out, "--show-max-framesize  Show the maximum frame size from the STREAMINFO block.\n");
735     fprintf(out, "--show-sample-rate    Show the sample rate from the STREAMINFO block.\n");
736     fprintf(out, "--show-channels       Show the number of channels from the STREAMINFO block.\n");
737     fprintf(out, "--show-bps            Show the # of bits per sample from the STREAMINFO block.\n");
738     fprintf(out, "--show-total-samples  Show the total # of samples from the STREAMINFO block.\n");
739     fprintf(out, "\n");
740     fprintf(out, "--show-vc-vendor      Show the vendor string from the VORBIS_COMMENT block.\n");
741     fprintf(out, "--show-vc-field=name  Show all Vorbis comment fields where the the field name\n");
742     fprintf(out, "                      matches 'name'.\n");
743     fprintf(out, "--remove-vc-field=name\n");
744     fprintf(out, "                      Remove all Vorbis comment fields whose field name is\n");
745     fprintf(out, "                      'name'.\n");
746     fprintf(out, "--remove-vc-firstfield=name\n");
747     fprintf(out, "                      Remove first Vorbis comment field whose field name is\n");
748     fprintf(out, "                      'name'.\n");
749     fprintf(out, "--remove-vc-all       Remove all Vorbis comment fields, leaving only the\n");
750     fprintf(out, "                      vendor string in the VORBIS_COMMENT block.\n");
751     fprintf(out, "--set-vc-field=field  Add a Vorbis comment field.  The field must comply with\n");
752     fprintf(out, "                      the Vorbis comment spec, of the form \"NAME=VALUE\".  If\n");
753     fprintf(out, "                      there is currently no VORBIS_COMMENT block, one will be\n");
754     fprintf(out, "                      created.\n");
755     fprintf(out, "--add-padding=length  Add a padding block of the given length (in bytes).\n");
756     fprintf(out, "                      The overall length of the new block will be 4 + length;\n");
757     fprintf(out, "                      the extra 4 bytes is for the metadata block header.\n");
758     fprintf(out, "\n");
759     fprintf(out, "Major operations:\n");
760     fprintf(out, "--list\n");
761     fprintf(out, "    List the contents of one or more metadata blocks to stdout.  By default,\n");
762     fprintf(out, "    all metadata blocks are listed in text format.  Use the following options\n");
763     fprintf(out, "    to change this behavior:\n");
764     fprintf(out, "\n");
765     fprintf(out, "    --block-number=#[,#[...]]\n");
766     fprintf(out, "    An optional comma-separated list of block numbers to display.  The first\n");
767     fprintf(out, "    block, the STREAMINFO block, is block 0.\n");
768     fprintf(out, "\n");
769     fprintf(out, "    --block-type=type[,type[...]]\n");
770     fprintf(out, "    --except-block-type=type[,type[...]]\n");
771     fprintf(out, "    An optional comma-separated list of block types to included or ignored\n");
772     fprintf(out, "    with this option.  Use only one of --block-type or --except-block-type.\n");
773     fprintf(out, "    The valid block types are: STREAMINFO, PADDING, APPLICATION, SEEKTABLE,\n");
774     fprintf(out, "    VORBIS_COMMENT.  You may narrow down the types of APPLICATION blocks\n");
775     fprintf(out, "    displayed as follows:\n");
776     fprintf(out, "        APPLICATION:abcd        The APPLICATION block(s) whose textual repre-\n");
777     fprintf(out, "                                sentation of the 4-byte ID is \"abcd\"\n");
778     fprintf(out, "        APPLICATION:0xXXXXXXXX  The APPLICATION block(s) whose hexadecimal big-\n");
779     fprintf(out, "                                endian representation of the 4-byte ID is\n");
780     fprintf(out, "                                \"0xXXXXXXXX\".  For the example \"abcd\" above the\n");
781     fprintf(out, "                                hexadecimal equivalalent is 0x61626364\n");
782     fprintf(out, "\n");
783     fprintf(out, "    NOTE: if both --block-number and --[except-]block-type are specified,\n");
784     fprintf(out, "          the result is the logical AND of both arguments.\n");
785     fprintf(out, "\n");
786 #if 0
787         /*@@@ not implemented yet */
788     fprintf(out, "    --data-format=binary|text\n");
789     fprintf(out, "    By default a human-readable text representation of the data is displayed.\n");
790     fprintf(out, "    You may specify --data-format=binary to dump the raw binary form of each\n");
791     fprintf(out, "    metadata block.  The output can be read in using a subsequent call to\n");
792     fprintf(out, "    "metaflac --append --from-file=..."\n");
793     fprintf(out, "\n");
794 #endif
795     fprintf(out, "    --application-data-format=hexdump|text\n");
796     fprintf(out, "    If the application block you are displaying contains binary data but your\n");
797     fprintf(out, "    --data-format=text, you can display a hex dump of the application data\n");
798     fprintf(out, "    contents instead using --application-data-format=hexdump\n");
799     fprintf(out, "\n");
800 #if 0
801         /*@@@ not implemented yet */
802     fprintf(out, "--append\n");
803     fprintf(out, "    Insert a metadata block from a file.  The input file must be in the same\n");
804     fprintf(out, "    format as generated with --list.\n");
805     fprintf(out, "\n");
806     fprintf(out, "    --block-number=#\n");
807     fprintf(out, "    Specify the insertion point (defaults to last block).  The new block will\n");
808     fprintf(out, "    be added after the given block number.  This prevents the illegal insertion\n");
809     fprintf(out, "    of a block before the first STREAMINFO block.  You may not --append another\n");
810     fprintf(out, "    STREAMINFO block.\n");
811     fprintf(out, "\n");
812     fprintf(out, "    --from-file=filename\n");
813     fprintf(out, "    Mandatory 'option' to specify the input file containing the block contents.\n");
814     fprintf(out, "\n");
815     fprintf(out, "    --data-format=binary|text\n");
816     fprintf(out, "    By default the block contents are assumed to be in binary format.  You can\n");
817     fprintf(out, "    override this by specifying --data-format=text\n");
818     fprintf(out, "\n");
819 #endif
820     fprintf(out, "--remove\n");
821     fprintf(out, "    Remove one or more metadata blocks from the metadata.  Unless\n");
822     fprintf(out, "    --dont-use-padding is specified, the blocks will be replaced with padding.\n");
823     fprintf(out, "    You may not remove the STREAMINFO block.\n");
824     fprintf(out, "\n");
825     fprintf(out, "    --block-number=#[,#[...]]\n");
826     fprintf(out, "    --block-type=type[,type[...]]\n");
827     fprintf(out, "    --except-block-type=type[,type[...]]\n");
828     fprintf(out, "    See --list above for usage.\n");
829     fprintf(out, "\n");
830     fprintf(out, "    NOTE: if both --block-number and --[except-]block-type are specified,\n");
831     fprintf(out, "          the result is the logical AND of both arguments.\n");
832     fprintf(out, "\n");
833     fprintf(out, "--remove-all\n");
834     fprintf(out, "    Remove all metadata blocks (except the STREAMINFO block) from the\n");
835     fprintf(out, "    metadata.  Unless --dont-use-padding is specified, the blocks will be\n");
836     fprintf(out, "    replaced with padding.\n");
837     fprintf(out, "\n");
838     fprintf(out, "--merge-padding\n");
839     fprintf(out, "    Merge adjacent PADDING blocks into single blocks.\n");
840     fprintf(out, "\n");
841     fprintf(out, "--sort-padding\n");
842     fprintf(out, "    Move all PADDING blocks to the end of the metadata and merge them into a\n");
843     fprintf(out, "    single block.\n");
844
845         return message? 1 : 0;
846 }
847
848 char *local_strdup(const char *source)
849 {
850         char *ret;
851         FLAC__ASSERT(0 != source);
852         if(0 == (ret = strdup(source)))
853                 die("out of memory during strdup()");
854         return ret;
855 }
856
857 FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length)
858 {
859         char *p, *s;
860
861         if(0 != field)
862                 *field = local_strdup(field_ref);
863
864         s = local_strdup(field_ref);
865
866         if(0 == (p = strchr(s, '='))) {
867                 free(s);
868                 return false;
869         }
870         *p++ = '\0';
871         *name = local_strdup(s);
872         *value = local_strdup(p);
873         *length = strlen(p);
874
875         free(s);
876         return true;
877 }
878
879 FLAC__bool parse_add_padding(const char *in, unsigned *out)
880 {
881         *out = (unsigned)strtoul(in, 0, 10);
882         return *out < (1u << FLAC__STREAM_METADATA_LENGTH_LEN);
883 }
884
885 FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out)
886 {
887         char *p, *q, *s, *end;
888         long i;
889         unsigned entry;
890
891         if(*in == '\0')
892                 return false;
893
894         s = local_strdup(in);
895
896         /* first count the entries */
897         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
898                 ;
899
900         /* make space */
901         FLAC__ASSERT(out->num_entries > 0);
902         if(0 == (out->entries = malloc(sizeof(unsigned) * out->num_entries)))
903                 die("out of memory allocating space for option list");
904
905         /* load 'em up */
906         entry = 0;
907         q = s;
908         while(q) {
909                 FLAC__ASSERT(entry < out->num_entries);
910                 if(0 != (p = strchr(q, ',')))
911                         *p++ = '\0';
912                 if(!isdigit((int)(*q)) || (i = strtol(q, &end, 10)) < 0 || *end) {
913                         free(s);
914                         return false;
915                 }
916                 out->entries[entry++] = (unsigned)i;
917                 q = p;
918         }
919         FLAC__ASSERT(entry == out->num_entries);
920
921         free(s);
922         return true;
923 }
924
925 FLAC__bool parse_block_type(const char *in, Argument_BlockType *out)
926 {
927         char *p, *q, *r, *s;
928         unsigned entry;
929
930         if(*in == '\0')
931                 return false;
932
933         s = local_strdup(in);
934
935         /* first count the entries */
936         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
937                 ;
938
939         /* make space */
940         FLAC__ASSERT(out->num_entries > 0);
941         if(0 == (out->entries = malloc(sizeof(Argument_BlockTypeEntry) * out->num_entries)))
942                 die("out of memory allocating space for option list");
943
944         /* load 'em up */
945         entry = 0;
946         q = s;
947         while(q) {
948                 FLAC__ASSERT(entry < out->num_entries);
949                 if(0 != (p = strchr(q, ',')))
950                         *p++ = 0;
951                 r = strchr(q, ':');
952                 if(r)
953                         *r++ = '\0';
954                 if(0 != r && 0 != strcmp(q, "APPLICATION")) {
955                         free(s);
956                         return false;
957                 }
958                 if(0 == strcmp(q, "STREAMINFO")) {
959                         out->entries[entry++].type = FLAC__METADATA_TYPE_STREAMINFO;
960                 }
961                 else if(0 == strcmp(q, "PADDING")) {
962                         out->entries[entry++].type = FLAC__METADATA_TYPE_PADDING;
963                 }
964                 else if(0 == strcmp(q, "APPLICATION")) {
965                         out->entries[entry].type = FLAC__METADATA_TYPE_APPLICATION;
966                         out->entries[entry].filter_application_by_id = (0 != r);
967                         if(0 != r) {
968                                 if(strlen(r) == 4) {
969                                         strcpy(out->entries[entry].application_id, r);
970                                 }
971                                 else if(strlen(r) == 10 && strncmp(r, "0x", 2) == 0 && strspn(r+2, "0123456789ABCDEFabcdef") == 8) {
972                                         FLAC__uint32 x = strtoul(r+2, 0, 16);
973                                         out->entries[entry].application_id[3] = (FLAC__byte)(x & 0xff);
974                                         out->entries[entry].application_id[2] = (FLAC__byte)((x>>=8) & 0xff);
975                                         out->entries[entry].application_id[1] = (FLAC__byte)((x>>=8) & 0xff);
976                                         out->entries[entry].application_id[0] = (FLAC__byte)((x>>=8) & 0xff);
977                                 }
978                                 else {
979                                         free(s);
980                                         return false;
981                                 }
982                         }
983                         entry++;
984                 }
985                 else if(0 == strcmp(q, "SEEKTABLE")) {
986                         out->entries[entry++].type = FLAC__METADATA_TYPE_SEEKTABLE;
987                 }
988                 else if(0 == strcmp(q, "VORBIS_COMMENT")) {
989                         out->entries[entry++].type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
990                 }
991                 else {
992                         free(s);
993                         return false;
994                 }
995                 q = p;
996         }
997         FLAC__ASSERT(entry == out->num_entries);
998
999         free(s);
1000         return true;
1001 }
1002
1003 FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out)
1004 {
1005         if(0 == strcmp(in, "binary"))
1006                 out->is_binary = true;
1007         else if(0 == strcmp(in, "text"))
1008                 out->is_binary = false;
1009         else
1010                 return false;
1011         return true;
1012 }
1013
1014 FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out)
1015 {
1016         if(0 == strcmp(in, "hexdump"))
1017                 *out = true;
1018         else if(0 == strcmp(in, "text"))
1019                 *out = false;
1020         else
1021                 return false;
1022         return true;
1023 }
1024
1025 FLAC__bool do_operations(const CommandLineOptions *options)
1026 {
1027         FLAC__bool ok = true;
1028
1029         if(options->show_long_help) {
1030                 long_usage(0);
1031         }
1032         else if(options->args.checks.num_major_ops > 0) {
1033                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == 0);
1034                 FLAC__ASSERT(options->args.checks.num_major_ops == 1);
1035                 FLAC__ASSERT(options->args.checks.num_major_ops == options->ops.num_operations);
1036                 ok = do_major_operation(options);
1037         }
1038         else if(options->args.checks.num_shorthand_ops > 0) {
1039                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == options->ops.num_operations);
1040                 ok = do_shorthand_operations(options);
1041         }
1042
1043         return ok;
1044 }
1045
1046 FLAC__bool do_major_operation(const CommandLineOptions *options)
1047 {
1048         unsigned i;
1049         FLAC__bool ok = true;
1050
1051         /*@@@ to die after first error,  v---  add '&& ok' here */
1052         for(i = 0; i < options->num_files; i++)
1053                 ok &= do_major_operation_on_file(options->filenames[i], options);
1054
1055         return ok;
1056 }
1057
1058 FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options)
1059 {
1060         FLAC__bool ok = true, needs_write = false;
1061         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1062
1063         if(0 == chain)
1064                 die("out of memory allocating chain");
1065
1066         if(!FLAC__metadata_chain_read(chain, filename)) {
1067                 fprintf(stderr, "ERROR: reading metadata, status = \"%s\"\n", FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1068                 return false;
1069         }
1070
1071         switch(options->ops.operations[0].type) {
1072                 case OP__LIST:
1073                         ok = do_major_operation__list(options->prefix_with_filename? filename : 0, chain, options);
1074                         break;
1075                 case OP__APPEND:
1076                         ok = do_major_operation__append(chain, options);
1077                         needs_write = true;
1078                         break;
1079                 case OP__REMOVE:
1080                         ok = do_major_operation__remove(chain, options);
1081                         needs_write = true;
1082                         break;
1083                 case OP__REMOVE_ALL:
1084                         ok = do_major_operation__remove_all(chain, options);
1085                         needs_write = true;
1086                         break;
1087                 case OP__MERGE_PADDING:
1088                         FLAC__metadata_chain_merge_padding(chain);
1089                         needs_write = true;
1090                         break;
1091                 case OP__SORT_PADDING:
1092                         FLAC__metadata_chain_sort_padding(chain);
1093                         needs_write = true;
1094                         break;
1095                 default:
1096                         FLAC__ASSERT(0);
1097                         return false;
1098         }
1099
1100         if(ok && needs_write) {
1101                 if(options->use_padding)
1102                         FLAC__metadata_chain_sort_padding(chain);
1103                 ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime);
1104                 if(!ok)
1105                         fprintf(stderr, "ERROR: writing FLAC file %s, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1106         }
1107
1108         FLAC__metadata_chain_delete(chain);
1109
1110         return ok;
1111 }
1112
1113 FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1114 {
1115         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1116         FLAC__StreamMetadata *block;
1117         FLAC__bool ok = true;
1118         unsigned block_number;
1119
1120         if(0 == iterator)
1121                 die("out of memory allocating iterator");
1122
1123         FLAC__metadata_iterator_init(iterator, chain);
1124
1125         block_number = 0;
1126         do {
1127                 block = FLAC__metadata_iterator_get_block(iterator);
1128                 ok &= (0 != block);
1129                 if(!ok)
1130                         fprintf(stderr, "ERROR: couldn't get block from chain\n");
1131                 else if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number))
1132                         write_metadata(filename, block, block_number, options->application_data_format_is_hexdump);
1133                 block_number++;
1134         } while(ok && FLAC__metadata_iterator_next(iterator));
1135
1136         FLAC__metadata_iterator_delete(iterator);
1137
1138         return ok;
1139 }
1140
1141 FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1142 {
1143         (void) chain, (void) options;
1144         fprintf(stderr, "ERROR: --append not implemented yet\n"); /*@@@*/
1145         return false;
1146 }
1147
1148 FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1149 {
1150         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1151         FLAC__bool ok = true;
1152         unsigned block_number;
1153
1154         if(0 == iterator)
1155                 die("out of memory allocating iterator");
1156
1157         FLAC__metadata_iterator_init(iterator, chain);
1158
1159         block_number = 0;
1160         while(ok && FLAC__metadata_iterator_next(iterator)) {
1161                 block_number++;
1162                 if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) {
1163                         ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1164                         if(options->use_padding)
1165                                 ok &= FLAC__metadata_iterator_next(iterator);
1166                 }
1167         }
1168
1169         FLAC__metadata_iterator_delete(iterator);
1170
1171         return ok;
1172 }
1173
1174 FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1175 {
1176         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1177         FLAC__bool ok = true;
1178
1179         if(0 == iterator)
1180                 die("out of memory allocating iterator");
1181
1182         FLAC__metadata_iterator_init(iterator, chain);
1183
1184         while(ok && FLAC__metadata_iterator_next(iterator)) {
1185                 ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1186                 if(options->use_padding)
1187                         ok &= FLAC__metadata_iterator_next(iterator);
1188         }
1189
1190         FLAC__metadata_iterator_delete(iterator);
1191
1192         return ok;
1193 }
1194
1195 FLAC__bool do_shorthand_operations(const CommandLineOptions *options)
1196 {
1197         unsigned i;
1198         FLAC__bool ok = true;
1199
1200         /*@@@ to die after first error,  v---  add '&& ok' here */
1201         for(i = 0; i < options->num_files; i++)
1202                 ok &= do_shorthand_operations_on_file(options->filenames[i], options);
1203
1204         return ok;
1205 }
1206
1207 FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options)
1208 {
1209         unsigned i;
1210         FLAC__bool ok = true, needs_write = false;
1211         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1212
1213         if(0 == chain)
1214                 die("out of memory allocating chain");
1215
1216         if(!FLAC__metadata_chain_read(chain, filename)) {
1217                 fprintf(stderr, "ERROR: reading metadata, status = \"%s\"\n", FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1218                 return false;
1219         }
1220
1221         for(i = 0; i < options->ops.num_operations && ok; i++)
1222                 ok &= do_shorthand_operation(options->prefix_with_filename? filename : 0, chain, &options->ops.operations[i], &needs_write);
1223
1224         if(ok) {
1225                 if(options->use_padding)
1226                         FLAC__metadata_chain_sort_padding(chain);
1227                 ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime);
1228                 if(!ok)
1229                         fprintf(stderr, "ERROR: writing FLAC file %s, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1230         }
1231
1232         FLAC__metadata_chain_delete(chain);
1233
1234         return ok;
1235 }
1236
1237 FLAC__bool do_shorthand_operation(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write)
1238 {
1239         FLAC__bool ok = true;
1240
1241         switch(operation->type) {
1242                 case OP__SHOW_MD5SUM:
1243                 case OP__SHOW_MIN_BLOCKSIZE:
1244                 case OP__SHOW_MAX_BLOCKSIZE:
1245                 case OP__SHOW_MIN_FRAMESIZE:
1246                 case OP__SHOW_MAX_FRAMESIZE:
1247                 case OP__SHOW_SAMPLE_RATE:
1248                 case OP__SHOW_CHANNELS:
1249                 case OP__SHOW_BPS:
1250                 case OP__SHOW_TOTAL_SAMPLES:
1251                         ok = do_shorthand_operation__streaminfo(filename, chain, operation->type);
1252                         break;
1253                 case OP__SHOW_VC_VENDOR:
1254                 case OP__SHOW_VC_FIELD:
1255                 case OP__REMOVE_VC_ALL:
1256                 case OP__REMOVE_VC_FIELD:
1257                 case OP__REMOVE_VC_FIRSTFIELD:
1258                 case OP__SET_VC_FIELD:
1259                         ok = do_shorthand_operation__vorbis_comment(filename, chain, operation, needs_write);
1260                         break;
1261                 case OP__ADD_PADDING:
1262                         ok = do_shorthand_operation__add_padding(chain, operation->argument.add_padding.length, needs_write);
1263                         break;
1264                 default:
1265                         ok = false;
1266                         FLAC__ASSERT(0);
1267                         break;
1268         };
1269
1270         return ok;
1271 }
1272
1273 FLAC__bool do_shorthand_operation__add_padding(FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write)
1274 {
1275         FLAC__StreamMetadata *padding = 0;
1276         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1277
1278         if(0 == iterator)
1279                 die("out of memory allocating iterator");
1280
1281         FLAC__metadata_iterator_init(iterator, chain);
1282
1283         while(FLAC__metadata_iterator_next(iterator))
1284                 ;
1285
1286         padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1287         if(0 == padding)
1288                 die("out of memory allocating PADDING block");
1289
1290         padding->length = length;
1291
1292         if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) {
1293                 fprintf(stderr, "ERROR: adding new PADDING block to metadata, status =\"%s\"\n", FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1294                 FLAC__metadata_object_delete(padding);
1295                 return false;
1296         }
1297
1298         *needs_write = true;
1299         return true;
1300 }
1301
1302 FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__Metadata_Chain *chain, OperationType op)
1303 {
1304         unsigned i;
1305         FLAC__bool ok = true;
1306         FLAC__StreamMetadata *block;
1307         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1308
1309         if(0 == iterator)
1310                 die("out of memory allocating iterator");
1311
1312         FLAC__metadata_iterator_init(iterator, chain);
1313
1314         block = FLAC__metadata_iterator_get_block(iterator);
1315
1316         FLAC__ASSERT(0 != block);
1317         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_STREAMINFO);
1318
1319         if(0 != filename)
1320                 printf("%s:", filename);
1321
1322         switch(op) {
1323                 case OP__SHOW_MD5SUM:
1324                         for(i = 0; i < 16; i++)
1325                                 printf("%02x", block->data.stream_info.md5sum[i]);
1326                         printf("\n");
1327                         break;
1328                 case OP__SHOW_MIN_BLOCKSIZE:
1329                         printf("%u\n", block->data.stream_info.min_blocksize);
1330                         break;
1331                 case OP__SHOW_MAX_BLOCKSIZE:
1332                         printf("%u\n", block->data.stream_info.max_blocksize);
1333                         break;
1334                 case OP__SHOW_MIN_FRAMESIZE:
1335                         printf("%u\n", block->data.stream_info.min_framesize);
1336                         break;
1337                 case OP__SHOW_MAX_FRAMESIZE:
1338                         printf("%u\n", block->data.stream_info.max_framesize);
1339                         break;
1340                 case OP__SHOW_SAMPLE_RATE:
1341                         printf("%u\n", block->data.stream_info.sample_rate);
1342                         break;
1343                 case OP__SHOW_CHANNELS:
1344                         printf("%u\n", block->data.stream_info.channels);
1345                         break;
1346                 case OP__SHOW_BPS:
1347                         printf("%u\n", block->data.stream_info.bits_per_sample);
1348                         break;
1349                 case OP__SHOW_TOTAL_SAMPLES:
1350                         printf("%llu\n", block->data.stream_info.total_samples);
1351                         break;
1352                 default:
1353                         ok = false;
1354                         FLAC__ASSERT(0);
1355                         break;
1356         };
1357
1358         FLAC__metadata_iterator_delete(iterator);
1359
1360         return ok;
1361 }
1362
1363 FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write)
1364 {
1365         FLAC__bool ok = true, found_vc_block = false;
1366         FLAC__StreamMetadata *block = 0;
1367         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1368
1369         if(0 == iterator)
1370                 die("out of memory allocating iterator");
1371
1372         FLAC__metadata_iterator_init(iterator, chain);
1373
1374         do {
1375                 block = FLAC__metadata_iterator_get_block(iterator);
1376                 if(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1377                         found_vc_block = true;
1378         } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
1379
1380         /* create a new block if necessary */
1381         if(!found_vc_block && operation->type == OP__SET_VC_FIELD) {
1382                 block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
1383                 if(0 == block)
1384                         die("out of memory allocating VORBIS_COMMENT block");
1385                 while(FLAC__metadata_iterator_next(iterator))
1386                         ;
1387                 if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) {
1388                         fprintf(stderr, "ERROR: adding new VORBIS_COMMENT block to metadata, status =\"%s\"\n", FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1389                         return false;
1390                 }
1391                 /* iterator is left pointing to new block */
1392                 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block);
1393         }
1394
1395         FLAC__ASSERT(0 != block);
1396         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1397
1398         switch(operation->type) {
1399                 case OP__SHOW_VC_VENDOR:
1400                         write_vc_field(filename, &block->data.vorbis_comment.vendor_string);
1401                         break;
1402                 case OP__SHOW_VC_FIELD:
1403                         write_vc_fields(filename, operation->argument.show_vc_field.field_name, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments);
1404                         break;
1405                 case OP__REMOVE_VC_ALL:
1406                         ok = remove_vc_all(block, needs_write);
1407                         break;
1408                 case OP__REMOVE_VC_FIELD:
1409                         ok = remove_vc_field(block, operation->argument.remove_vc_field.field_name, needs_write);
1410                         break;
1411                 case OP__REMOVE_VC_FIRSTFIELD:
1412                         ok = remove_vc_firstfield(block, operation->argument.remove_vc_firstfield.field_name, needs_write);
1413                         break;
1414                 case OP__SET_VC_FIELD:
1415                         ok = set_vc_field(block, &operation->argument.set_vc_field, needs_write);
1416                         break;
1417                 default:
1418                         ok = false;
1419                         FLAC__ASSERT(0);
1420                         break;
1421         };
1422
1423         return ok;
1424 }
1425
1426 FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number)
1427 {
1428         unsigned i, j;
1429         FLAC__bool matches_number = false, matches_type = false;
1430         FLAC__bool has_block_number_arg = false;
1431
1432         for(i = 0; i < options->args.num_arguments; i++) {
1433                 if(options->args.arguments[i].type == ARG__BLOCK_TYPE || options->args.arguments[i].type == ARG__EXCEPT_BLOCK_TYPE) {
1434                         for(j = 0; j < options->args.arguments[i].value.block_type.num_entries; j++) {
1435                                 if(options->args.arguments[i].value.block_type.entries[j].type == block->type) {
1436                                         if(block->type != FLAC__METADATA_TYPE_APPLICATION || !options->args.arguments[i].value.block_type.entries[j].filter_application_by_id || 0 == memcmp(options->args.arguments[i].value.block_type.entries[j].application_id, block->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1437                                                 matches_type = true;
1438                                 }
1439                         }
1440                 }
1441                 else if(options->args.arguments[i].type == ARG__BLOCK_NUMBER) {
1442                         has_block_number_arg = true;
1443                         for(j = 0; j < options->args.arguments[i].value.block_number.num_entries; j++) {
1444                                 if(options->args.arguments[i].value.block_number.entries[j] == block_number)
1445                                         matches_number = true;
1446                         }
1447                 }
1448         }
1449
1450         if(!has_block_number_arg)
1451                 matches_number = true;
1452
1453         if(options->args.checks.has_block_type) {
1454                 FLAC__ASSERT(!options->args.checks.has_except_block_type);
1455         }
1456         else if(options->args.checks.has_except_block_type)
1457                 matches_type = !matches_type;
1458         else
1459                 matches_type = true;
1460
1461         return matches_number && matches_type;
1462 }
1463
1464 void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool hexdump_application)
1465 {
1466         unsigned i;
1467
1468 /*@@@ yuck, should do this with a varargs function or something: */
1469 #define PPR if(filename)printf("%s:",filename);
1470         PPR; printf("METADATA block #%u\n", block_number);
1471         PPR; printf("  type: %u (%s)\n", (unsigned)block->type, block->type<=FLAC__METADATA_TYPE_VORBIS_COMMENT? FLAC__MetadataTypeString[block->type] : "UNKNOWN");
1472         PPR; printf("  is last: %s\n", block->is_last? "true":"false");
1473         PPR; printf("  length: %u\n", block->length);
1474
1475         switch(block->type) {
1476                 case FLAC__METADATA_TYPE_STREAMINFO:
1477                         PPR; printf("  minumum blocksize: %u samples\n", block->data.stream_info.min_blocksize);
1478                         PPR; printf("  maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize);
1479                         PPR; printf("  minimum framesize: %u bytes\n", block->data.stream_info.min_framesize);
1480                         PPR; printf("  maximum framesize: %u bytes\n", block->data.stream_info.max_framesize);
1481                         PPR; printf("  sample_rate: %u Hz\n", block->data.stream_info.sample_rate);
1482                         PPR; printf("  channels: %u\n", block->data.stream_info.channels);
1483                         PPR; printf("  bits-per-sample: %u\n", block->data.stream_info.bits_per_sample);
1484                         PPR; printf("  total samples: %llu\n", block->data.stream_info.total_samples);
1485                         PPR; printf("  MD5 signature: ");
1486                         for(i = 0; i < 16; i++) {
1487                                 PPR; printf("%02x", block->data.stream_info.md5sum[i]);
1488                         }
1489                         PPR; printf("\n");
1490                         break;
1491                 case FLAC__METADATA_TYPE_PADDING:
1492                         /* nothing to print */
1493                         break;
1494                 case FLAC__METADATA_TYPE_APPLICATION:
1495                         PPR; printf("  application ID: ");
1496                         for(i = 0; i < 4; i++) {
1497                                 PPR; printf("%02x", block->data.application.id[i]);
1498                         }
1499                         PPR; printf("\n");
1500                         PPR; printf("  data contents:\n");
1501                         if(0 != block->data.application.data) {
1502                                 if(hexdump_application)
1503                                         hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, "    ");
1504                                 else
1505                                         (void) fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout);
1506                         }
1507                         break;
1508                 case FLAC__METADATA_TYPE_SEEKTABLE:
1509                         PPR; printf("  seek points: %u\n", block->data.seek_table.num_points);
1510                         for(i = 0; i < block->data.seek_table.num_points; i++) {
1511                                 PPR; printf("    point %d: sample_number=%llu, stream_offset=%llu, frame_samples=%u\n", i, block->data.seek_table.points[i].sample_number, block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples);
1512                         }
1513                         break;
1514                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1515                         PPR; printf("  vendor string: ");
1516                         fwrite(block->data.vorbis_comment.vendor_string.entry, 1, block->data.vorbis_comment.vendor_string.length, stdout);
1517                         printf("\n");
1518                         PPR; printf("  comments: %u\n", block->data.vorbis_comment.num_comments);
1519                         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
1520                                 PPR; printf("    comment[%u]: ", i);
1521                                 fwrite(block->data.vorbis_comment.comments[i].entry, 1, block->data.vorbis_comment.comments[i].length, stdout);
1522                                 printf("\n");
1523                         }
1524                         break;
1525                 default:
1526                         PPR; printf("SKIPPING block of unknown type\n");
1527                         break;
1528         }
1529 #undef PPR
1530 }
1531
1532 void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry)
1533 {
1534         if(filename)
1535                 printf("%s:", filename);
1536         (void) fwrite(entry->entry, 1, entry->length, stdout);
1537         printf("\n");
1538 }
1539
1540 void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries)
1541 {
1542         unsigned i;
1543         const unsigned field_name_length = strlen(field_name);
1544
1545         for(i = 0; i < num_entries; i++) {
1546                 if(field_name_matches_entry(field_name, field_name_length, entry + i))
1547                         write_vc_field(filename, entry + i);
1548         }
1549 }
1550
1551 FLAC__bool remove_vc_all(FLAC__StreamMetadata *block, FLAC__bool *needs_write)
1552 {
1553         FLAC__ASSERT(0 != block);
1554         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1555         FLAC__ASSERT(0 != needs_write);
1556
1557         if(0 != block->data.vorbis_comment.comments) {
1558                 FLAC__ASSERT(block->data.vorbis_comment.num_comments > 0);
1559                 if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, 0))
1560                         return false;
1561                 *needs_write = true;
1562         }
1563         else {
1564                 FLAC__ASSERT(block->data.vorbis_comment.num_comments == 0);
1565         }
1566
1567         return true;
1568 }
1569
1570 FLAC__bool remove_vc_field(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
1571 {
1572         FLAC__bool ok = true;
1573         const unsigned field_name_length = strlen(field_name);
1574         int i;
1575
1576         FLAC__ASSERT(0 != block);
1577         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1578         FLAC__ASSERT(0 != needs_write);
1579
1580         /* must delete from end to start otherwise it will interfere with our iteration */
1581         for(i = (int)block->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) {
1582                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
1583                         ok &= FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i);
1584                         if(ok)
1585                                 *needs_write = true;
1586                 }
1587         }
1588
1589         return ok;
1590 }
1591
1592 FLAC__bool remove_vc_firstfield(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
1593 {
1594         const unsigned field_name_length = strlen(field_name);
1595         unsigned i;
1596
1597         FLAC__ASSERT(0 != block);
1598         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1599         FLAC__ASSERT(0 != needs_write);
1600
1601         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
1602                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
1603                         if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i))
1604                                 return false;
1605                         else
1606                                 *needs_write = true;
1607                         break;
1608                 }
1609         }
1610
1611         return true;
1612 }
1613
1614 FLAC__bool set_vc_field(FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write)
1615 {
1616         FLAC__StreamMetadata_VorbisComment_Entry entry;
1617         FLAC__ASSERT(0 != block);
1618         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1619         FLAC__ASSERT(0 != field);
1620         FLAC__ASSERT(0 != needs_write);
1621
1622         entry.length = strlen(field->field);
1623         entry.entry = field->field;
1624
1625         if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, block->data.vorbis_comment.num_comments, entry, /*copy=*/true)) {
1626                 return false;
1627         }
1628         else {
1629                 *needs_write = true;
1630                 return true;
1631         }
1632 }
1633
1634 FLAC__bool field_name_matches_entry(const char *field_name, unsigned field_name_length, const FLAC__StreamMetadata_VorbisComment_Entry *entry)
1635 {
1636         return (0 != memchr(entry->entry, '=', entry->length) && 0 == strncmp(field_name, entry->entry, field_name_length));
1637 }
1638
1639 void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent)
1640 {
1641         unsigned i, left = bytes;
1642         const FLAC__byte *b = buf;
1643
1644         for(i = 0; i < bytes; i += 16) {
1645                 printf("%s%s%s%08X: "
1646                         "%02X %02X %02X %02X %02X %02X %02X %02X "
1647                         "%02X %02X %02X %02X %02X %02X %02X %02X "
1648                         "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",
1649                         filename? filename:"", filename? ":":"",
1650                         indent, i,
1651                         left >  0? (unsigned char)b[ 0] : 0,
1652                         left >  1? (unsigned char)b[ 1] : 0,
1653                         left >  2? (unsigned char)b[ 2] : 0,
1654                         left >  3? (unsigned char)b[ 3] : 0,
1655                         left >  4? (unsigned char)b[ 4] : 0,
1656                         left >  5? (unsigned char)b[ 5] : 0,
1657                         left >  6? (unsigned char)b[ 6] : 0,
1658                         left >  7? (unsigned char)b[ 7] : 0,
1659                         left >  8? (unsigned char)b[ 8] : 0,
1660                         left >  9? (unsigned char)b[ 9] : 0,
1661                         left > 10? (unsigned char)b[10] : 0,
1662                         left > 11? (unsigned char)b[11] : 0,
1663                         left > 12? (unsigned char)b[12] : 0,
1664                         left > 13? (unsigned char)b[13] : 0,
1665                         left > 14? (unsigned char)b[14] : 0,
1666                         left > 15? (unsigned char)b[15] : 0,
1667                         (left >  0) ? (isprint(b[ 0]) ? b[ 0] : '.') : ' ',
1668                         (left >  1) ? (isprint(b[ 1]) ? b[ 1] : '.') : ' ',
1669                         (left >  2) ? (isprint(b[ 2]) ? b[ 2] : '.') : ' ',
1670                         (left >  3) ? (isprint(b[ 3]) ? b[ 3] : '.') : ' ',
1671                         (left >  4) ? (isprint(b[ 4]) ? b[ 4] : '.') : ' ',
1672                         (left >  5) ? (isprint(b[ 5]) ? b[ 5] : '.') : ' ',
1673                         (left >  6) ? (isprint(b[ 6]) ? b[ 6] : '.') : ' ',
1674                         (left >  7) ? (isprint(b[ 7]) ? b[ 7] : '.') : ' ',
1675                         (left >  8) ? (isprint(b[ 8]) ? b[ 8] : '.') : ' ',
1676                         (left >  9) ? (isprint(b[ 9]) ? b[ 9] : '.') : ' ',
1677                         (left > 10) ? (isprint(b[10]) ? b[10] : '.') : ' ',
1678                         (left > 11) ? (isprint(b[11]) ? b[11] : '.') : ' ',
1679                         (left > 12) ? (isprint(b[12]) ? b[12] : '.') : ' ',
1680                         (left > 13) ? (isprint(b[13]) ? b[13] : '.') : ' ',
1681                         (left > 14) ? (isprint(b[14]) ? b[14] : '.') : ' ',
1682                         (left > 15) ? (isprint(b[15]) ? b[15] : '.') : ' '
1683                 );
1684                 left -= 16;
1685                 b += 16;
1686    }
1687 }