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